diff --git a/.gitattributes b/.gitattributes index 804414352feffd368697a10a629e6462931da8d5..f9da35e7e42a2b12b05ba62a6c41ef4a45040944 100644 --- a/.gitattributes +++ b/.gitattributes @@ -428,3 +428,4 @@ loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/blob loan-advisor-agent/.venv/Lib/site-packages/google/cloud/storage/__pycache__/bucket.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/models.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text loan-advisor-agent/.venv/Lib/site-packages/google/genai/__pycache__/types.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/descriptor_pb2.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/text_content_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/text_content_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9c3befd81b835c76fc058f5648262b8c0d610c2d Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/text_content_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/thinking_level.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/thinking_level.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b6fab0d6ed94091822e8151781c40ab7e948fea2 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/thinking_level.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/thought_content.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/thought_content.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43dbe7519306fdbcae0a37d837b514871c5581eb Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/thought_content.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/thought_content_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/thought_content_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae27744a562761c4a1337d1a6f5edfd3f85fb731 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/thought_content_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/tool.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/tool.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d6786c3e7226b1c3430c07863bb29f9544bd0e7 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/tool.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/tool_choice_config.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/tool_choice_config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d2d9105998707a09a54a7220b5028b8c0d05a14 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/tool_choice_config.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/tool_choice_config_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/tool_choice_config_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a9845f941b59224d6486349ea8e58516bc5b8ef0 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/tool_choice_config_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/tool_choice_type.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/tool_choice_type.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d021251d577953e7872109efb5ae1f86cca50029 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/tool_choice_type.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/tool_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/tool_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97ba2e3955388edcca21e0e21fc52e420227e8d0 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/tool_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/turn.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/turn.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..98e7e4a0e27ce1807746a1e46fd7acf8aece92a3 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/turn.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/turn_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/turn_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f36e52ce8d55684511e6576c1f0146f5f123b20 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/turn_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/url_citation.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/url_citation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..09d72dbcf336834e0f0b2102c4a446e89ed3ff4c Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/url_citation.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/url_citation_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/url_citation_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..576abd98a5288db7369696be5b2a8629e06d6139 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/url_citation_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/url_context_call_arguments.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/url_context_call_arguments.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1cd6e0bd01f755f1e2271514d51918c3cd8835be Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/url_context_call_arguments.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/url_context_call_arguments_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/url_context_call_arguments_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f79af9b2d8509d7d0491d4ef9a475b50f47ca7a7 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/url_context_call_arguments_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/url_context_call_content.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/url_context_call_content.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91f5e7280d61a135b2dbded7eb6ea7c75159ee3d Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/url_context_call_content.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/url_context_call_content_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/url_context_call_content_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dff03c146dc2bfd799b42d1069f7a6ae22d695cd Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/url_context_call_content_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/url_context_result.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/url_context_result.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..26173a25ec69d1cc9a9bef6fe1cf12198cc2cc58 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/url_context_result.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/url_context_result_content.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/url_context_result_content.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b3bb4f07a5af4df09a26c0e6d4356b29785b6986 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/url_context_result_content.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/url_context_result_content_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/url_context_result_content_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d40c86f3f797d0cebbfa380be7d7cf24b2b70663 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/url_context_result_content_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/url_context_result_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/url_context_result_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b31560ffac663435b69009202823529b2f84b31 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/url_context_result_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/usage.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/usage.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f2ef1fcf7dcdc859c9be32f6df809307278d3b26 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/usage.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/usage_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/usage_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ca1e1fef2b8655fa922fcc0dc352a392707b28c Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/usage_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/video_content.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/video_content.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee7cb4b5b7dd99b0359ab919c54a583bfbe85d78 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/video_content.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/video_content_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/video_content_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e354642f25e46d48d3ae67751d3578fc571f15f0 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/video_content_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/webhook.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/webhook.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ca910b7bddf56aa9bb2a77d7e63be0a26bbe280 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/webhook.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/webhook_config.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/webhook_config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..892eb30a393485de4c0b35264b7c88a7ff59126a Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/webhook_config.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/webhook_config_param.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/webhook_config_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c04c02b0ab89cd48a4d6c03a5c6a8449c81acb9 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/webhook_config_param.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/webhook_create_params.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/webhook_create_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ace484c6ba6877fa594d881295ea3e3107793541 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/webhook_create_params.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/webhook_delete_response.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/webhook_delete_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..17ffbfad73f65e9df6026927077ef667e3bcae15 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/webhook_delete_response.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/webhook_list_params.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/webhook_list_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..af6ce6a6673dc0d09804acdec5df952d00525040 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/webhook_list_params.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/webhook_list_response.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/webhook_list_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c55300296b36260d62718d1a1dc249da7d9db52b Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/webhook_list_response.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/webhook_ping_params.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/webhook_ping_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ae66fc3bbfab6f1308b876e4b2ab350e98bba93 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/webhook_ping_params.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/webhook_ping_response.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/webhook_ping_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..feeba91fa4a14164487891bda59d714b147d874f Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/webhook_ping_response.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/webhook_rotate_signing_secret_params.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/webhook_rotate_signing_secret_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6092239fd578d2a446aa53407d6ebad11a6e6914 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/webhook_rotate_signing_secret_params.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/webhook_rotate_signing_secret_response.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/webhook_rotate_signing_secret_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a8546508a07edcb978f11cfc3b76ed5fb3667c1d Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/webhook_rotate_signing_secret_response.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/webhook_update_params.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/webhook_update_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1dbf1b1f6d6495c1f7d4116ea9ff3752518190b1 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/__pycache__/webhook_update_params.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/allowed_tools.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/allowed_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..903310eb6f58c99b759ab73633cbbd74d7f56aae --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/allowed_tools.py @@ -0,0 +1,33 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional + +from .._models import BaseModel +from .tool_choice_type import ToolChoiceType + +__all__ = ["AllowedTools"] + + +class AllowedTools(BaseModel): + """The configuration for allowed tools.""" + + mode: Optional[ToolChoiceType] = None + """The mode of the tool choice.""" + + tools: Optional[List[str]] = None + """The names of the allowed tools.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/allowed_tools_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/allowed_tools_param.py new file mode 100644 index 0000000000000000000000000000000000000000..566017d3144ed8d7e9a59382de193c550b426416 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/allowed_tools_param.py @@ -0,0 +1,35 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import TypedDict + +from .._types import SequenceNotStr +from .tool_choice_type import ToolChoiceType + +__all__ = ["AllowedToolsParam"] + + +class AllowedToolsParam(TypedDict, total=False): + """The configuration for allowed tools.""" + + mode: ToolChoiceType + """The mode of the tool choice.""" + + tools: SequenceNotStr[str] + """The names of the allowed tools.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/annotation.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/annotation.py new file mode 100644 index 0000000000000000000000000000000000000000..9c38a05c884dea21ac99a662a295777b6ceadfc5 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/annotation.py @@ -0,0 +1,28 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Annotated, TypeAlias + +from .._utils import PropertyInfo +from .url_citation import URLCitation +from .file_citation import FileCitation +from .place_citation import PlaceCitation + +__all__ = ["Annotation"] + +Annotation: TypeAlias = Annotated[Union[URLCitation, FileCitation, PlaceCitation], PropertyInfo(discriminator="type")] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/annotation_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/annotation_param.py new file mode 100644 index 0000000000000000000000000000000000000000..ae6875035a64338b52f6b5187467d3e0aecf0001 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/annotation_param.py @@ -0,0 +1,29 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import TypeAlias + +from .url_citation_param import URLCitationParam +from .file_citation_param import FileCitationParam +from .place_citation_param import PlaceCitationParam + +__all__ = ["AnnotationParam"] + +AnnotationParam: TypeAlias = Union[URLCitationParam, FileCitationParam, PlaceCitationParam] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/audio_content.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/audio_content.py new file mode 100644 index 0000000000000000000000000000000000000000..898847a83e74a529820e99e29de1989169fc8b08 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/audio_content.py @@ -0,0 +1,59 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["AudioContent"] + + +class AudioContent(BaseModel): + """An audio content block.""" + + type: Literal["audio"] + + channels: Optional[int] = None + """The number of audio channels.""" + + data: Optional[str] = None + """The audio content.""" + + mime_type: Optional[ + Literal[ + "audio/wav", + "audio/mp3", + "audio/aiff", + "audio/aac", + "audio/ogg", + "audio/flac", + "audio/mpeg", + "audio/m4a", + "audio/l16", + "audio/opus", + "audio/alaw", + "audio/mulaw", + ] + ] = None + """The mime type of the audio.""" + + rate: Optional[int] = None + """The sample rate of the audio.""" + + uri: Optional[str] = None + """The URI of the audio.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/audio_content_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/audio_content_param.py new file mode 100644 index 0000000000000000000000000000000000000000..5f9d69074db3f9930ee5ad0f376fcc939eee6763 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/audio_content_param.py @@ -0,0 +1,64 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import Literal, Required, Annotated, TypedDict + +from .._types import Base64FileInput +from .._utils import PropertyInfo +from .._models import set_pydantic_config + +__all__ = ["AudioContentParam"] + + +class AudioContentParam(TypedDict, total=False): + """An audio content block.""" + + type: Required[Literal["audio"]] + + channels: int + """The number of audio channels.""" + + data: Annotated[Union[str, Base64FileInput], PropertyInfo(format="base64")] + """The audio content.""" + + mime_type: Literal[ + "audio/wav", + "audio/mp3", + "audio/aiff", + "audio/aac", + "audio/ogg", + "audio/flac", + "audio/mpeg", + "audio/m4a", + "audio/l16", + "audio/opus", + "audio/alaw", + "audio/mulaw", + ] + """The mime type of the audio.""" + + rate: int + """The sample rate of the audio.""" + + uri: str + """The URI of the audio.""" + + +set_pydantic_config(AudioContentParam, {"arbitrary_types_allowed": True}) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/code_execution_call_arguments.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/code_execution_call_arguments.py new file mode 100644 index 0000000000000000000000000000000000000000..dce40529674a1f8f5794fad9a28070ce63f2fa4a --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/code_execution_call_arguments.py @@ -0,0 +1,33 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["CodeExecutionCallArguments"] + + +class CodeExecutionCallArguments(BaseModel): + """The arguments to pass to the code execution.""" + + code: Optional[str] = None + """The code to be executed.""" + + language: Optional[Literal["python"]] = None + """Programming language of the `code`.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/code_execution_call_arguments_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/code_execution_call_arguments_param.py new file mode 100644 index 0000000000000000000000000000000000000000..87fc40d7e4b1ac64ded433fd1932a5f0802a2306 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/code_execution_call_arguments_param.py @@ -0,0 +1,32 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, TypedDict + +__all__ = ["CodeExecutionCallArgumentsParam"] + + +class CodeExecutionCallArgumentsParam(TypedDict, total=False): + """The arguments to pass to the code execution.""" + + code: str + """The code to be executed.""" + + language: Literal["python"] + """Programming language of the `code`.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/code_execution_call_content.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/code_execution_call_content.py new file mode 100644 index 0000000000000000000000000000000000000000..0488f89c677b9e24bd005521274453110b559daa --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/code_execution_call_content.py @@ -0,0 +1,39 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .._models import BaseModel +from .code_execution_call_arguments import CodeExecutionCallArguments + +__all__ = ["CodeExecutionCallContent"] + + +class CodeExecutionCallContent(BaseModel): + """Code execution content.""" + + id: str + """Required. A unique ID for this specific tool call.""" + + arguments: CodeExecutionCallArguments + """Required. The arguments to pass to the code execution.""" + + type: Literal["code_execution_call"] + + signature: Optional[str] = None + """A signature hash for backend validation.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/code_execution_call_content_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/code_execution_call_content_param.py new file mode 100644 index 0000000000000000000000000000000000000000..33e5e0a617fbbf68345ee1207994082db57c4574 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/code_execution_call_content_param.py @@ -0,0 +1,46 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import Literal, Required, Annotated, TypedDict + +from .._types import Base64FileInput +from .._utils import PropertyInfo +from .._models import set_pydantic_config +from .code_execution_call_arguments_param import CodeExecutionCallArgumentsParam + +__all__ = ["CodeExecutionCallContentParam"] + + +class CodeExecutionCallContentParam(TypedDict, total=False): + """Code execution content.""" + + id: Required[str] + """Required. A unique ID for this specific tool call.""" + + arguments: Required[CodeExecutionCallArgumentsParam] + """Required. The arguments to pass to the code execution.""" + + type: Required[Literal["code_execution_call"]] + + signature: Annotated[Union[str, Base64FileInput], PropertyInfo(format="base64")] + """A signature hash for backend validation.""" + + +set_pydantic_config(CodeExecutionCallContentParam, {"arbitrary_types_allowed": True}) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/code_execution_result_content.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/code_execution_result_content.py new file mode 100644 index 0000000000000000000000000000000000000000..1d300aeda721f8a20ef62a1f47ba989b8391dbcb --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/code_execution_result_content.py @@ -0,0 +1,41 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["CodeExecutionResultContent"] + + +class CodeExecutionResultContent(BaseModel): + """Code execution result content.""" + + call_id: str + """Required. ID to match the ID from the function call block.""" + + result: str + """Required. The output of the code execution.""" + + type: Literal["code_execution_result"] + + is_error: Optional[bool] = None + """Whether the code execution resulted in an error.""" + + signature: Optional[str] = None + """A signature hash for backend validation.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/code_execution_result_content_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/code_execution_result_content_param.py new file mode 100644 index 0000000000000000000000000000000000000000..b4e64370f1fa82ffbbe86bad9158715d47aa518c --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/code_execution_result_content_param.py @@ -0,0 +1,48 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import Literal, Required, Annotated, TypedDict + +from .._types import Base64FileInput +from .._utils import PropertyInfo +from .._models import set_pydantic_config + +__all__ = ["CodeExecutionResultContentParam"] + + +class CodeExecutionResultContentParam(TypedDict, total=False): + """Code execution result content.""" + + call_id: Required[str] + """Required. ID to match the ID from the function call block.""" + + result: Required[str] + """Required. The output of the code execution.""" + + type: Required[Literal["code_execution_result"]] + + is_error: bool + """Whether the code execution resulted in an error.""" + + signature: Annotated[Union[str, Base64FileInput], PropertyInfo(format="base64")] + """A signature hash for backend validation.""" + + +set_pydantic_config(CodeExecutionResultContentParam, {"arbitrary_types_allowed": True}) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/content.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/content.py new file mode 100644 index 0000000000000000000000000000000000000000..4145241012f9c65d02c68afe40b661dec65316dd --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/content.py @@ -0,0 +1,69 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Annotated, TypeAlias + +from .._utils import PropertyInfo +from .text_content import TextContent +from .audio_content import AudioContent +from .image_content import ImageContent +from .video_content import VideoContent +from .thought_content import ThoughtContent +from .document_content import DocumentContent +from .function_call_content import FunctionCallContent +from .function_result_content import FunctionResultContent +from .file_search_call_content import FileSearchCallContent +from .google_maps_call_content import GoogleMapsCallContent +from .url_context_call_content import URLContextCallContent +from .file_search_result_content import FileSearchResultContent +from .google_maps_result_content import GoogleMapsResultContent +from .google_search_call_content import GoogleSearchCallContent +from .url_context_result_content import URLContextResultContent +from .code_execution_call_content import CodeExecutionCallContent +from .google_search_result_content import GoogleSearchResultContent +from .mcp_server_tool_call_content import MCPServerToolCallContent +from .code_execution_result_content import CodeExecutionResultContent +from .mcp_server_tool_result_content import MCPServerToolResultContent + +__all__ = ["Content"] + +Content: TypeAlias = Annotated[ + Union[ + TextContent, + ImageContent, + AudioContent, + DocumentContent, + VideoContent, + ThoughtContent, + FunctionCallContent, + CodeExecutionCallContent, + URLContextCallContent, + MCPServerToolCallContent, + GoogleSearchCallContent, + FileSearchCallContent, + GoogleMapsCallContent, + FunctionResultContent, + CodeExecutionResultContent, + URLContextResultContent, + GoogleSearchResultContent, + MCPServerToolResultContent, + FileSearchResultContent, + GoogleMapsResultContent, + ], + PropertyInfo(discriminator="type"), +] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/content_delta.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/content_delta.py new file mode 100644 index 0000000000000000000000000000000000000000..415aef3166e9dc7d526078dc4f59f30dcf2995b6 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/content_delta.py @@ -0,0 +1,427 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, List, Union, Optional +from typing_extensions import Literal, Annotated, TypeAlias + +from .._utils import PropertyInfo +from .._models import BaseModel +from .annotation import Annotation +from .text_content import TextContent +from .image_content import ImageContent +from .google_maps_result import GoogleMapsResult +from .url_context_result import URLContextResult +from .google_search_result import GoogleSearchResult +from .google_maps_call_arguments import GoogleMapsCallArguments +from .url_context_call_arguments import URLContextCallArguments +from .google_search_call_arguments import GoogleSearchCallArguments +from .code_execution_call_arguments import CodeExecutionCallArguments + +__all__ = [ + "ContentDelta", + "Delta", + "DeltaText", + "DeltaImage", + "DeltaAudio", + "DeltaDocument", + "DeltaVideo", + "DeltaThoughtSummary", + "DeltaThoughtSummaryContent", + "DeltaThoughtSignature", + "DeltaFunctionCall", + "DeltaCodeExecutionCall", + "DeltaURLContextCall", + "DeltaGoogleSearchCall", + "DeltaMCPServerToolCall", + "DeltaFileSearchCall", + "DeltaGoogleMapsCall", + "DeltaFunctionResult", + "DeltaFunctionResultResultFunctionResultSubcontentList", + "DeltaCodeExecutionResult", + "DeltaURLContextResult", + "DeltaGoogleSearchResult", + "DeltaMCPServerToolResult", + "DeltaMCPServerToolResultResultFunctionResultSubcontentList", + "DeltaFileSearchResult", + "DeltaFileSearchResultResult", + "DeltaGoogleMapsResult", + "DeltaTextAnnotation", +] + + +class DeltaText(BaseModel): + text: str + + type: Literal["text"] + + +class DeltaImage(BaseModel): + type: Literal["image"] + + data: Optional[str] = None + + mime_type: Optional[ + Literal[ + "image/png", "image/jpeg", "image/webp", "image/heic", "image/heif", "image/gif", "image/bmp", "image/tiff" + ] + ] = None + + resolution: Optional[Literal["low", "medium", "high", "ultra_high"]] = None + """The resolution of the media.""" + + uri: Optional[str] = None + + +class DeltaAudio(BaseModel): + type: Literal["audio"] + + channels: Optional[int] = None + """The number of audio channels.""" + + data: Optional[str] = None + + mime_type: Optional[ + Literal[ + "audio/wav", + "audio/mp3", + "audio/aiff", + "audio/aac", + "audio/ogg", + "audio/flac", + "audio/mpeg", + "audio/m4a", + "audio/l16", + "audio/opus", + "audio/alaw", + "audio/mulaw", + ] + ] = None + + rate: Optional[int] = None + """The sample rate of the audio.""" + + uri: Optional[str] = None + + +class DeltaDocument(BaseModel): + type: Literal["document"] + + data: Optional[str] = None + + mime_type: Optional[Literal["application/pdf"]] = None + + uri: Optional[str] = None + + +class DeltaVideo(BaseModel): + type: Literal["video"] + + data: Optional[str] = None + + mime_type: Optional[ + Literal[ + "video/mp4", + "video/mpeg", + "video/mpg", + "video/mov", + "video/avi", + "video/x-flv", + "video/webm", + "video/wmv", + "video/3gpp", + ] + ] = None + + resolution: Optional[Literal["low", "medium", "high", "ultra_high"]] = None + """The resolution of the media.""" + + uri: Optional[str] = None + + +DeltaThoughtSummaryContent: TypeAlias = Annotated[Union[TextContent, ImageContent], PropertyInfo(discriminator="type")] + + +class DeltaThoughtSummary(BaseModel): + type: Literal["thought_summary"] + + content: Optional[DeltaThoughtSummaryContent] = None + """A new summary item to be added to the thought.""" + + +class DeltaThoughtSignature(BaseModel): + type: Literal["thought_signature"] + + signature: Optional[str] = None + """Signature to match the backend source to be part of the generation.""" + + +class DeltaFunctionCall(BaseModel): + id: str + """Required. A unique ID for this specific tool call.""" + + arguments: Dict[str, object] + + name: str + + type: Literal["function_call"] + + signature: Optional[str] = None + """A signature hash for backend validation.""" + + +class DeltaCodeExecutionCall(BaseModel): + id: str + """Required. A unique ID for this specific tool call.""" + + arguments: CodeExecutionCallArguments + """The arguments to pass to the code execution.""" + + type: Literal["code_execution_call"] + + signature: Optional[str] = None + """A signature hash for backend validation.""" + + +class DeltaURLContextCall(BaseModel): + id: str + """Required. A unique ID for this specific tool call.""" + + arguments: URLContextCallArguments + """The arguments to pass to the URL context.""" + + type: Literal["url_context_call"] + + signature: Optional[str] = None + """A signature hash for backend validation.""" + + +class DeltaGoogleSearchCall(BaseModel): + id: str + """Required. A unique ID for this specific tool call.""" + + arguments: GoogleSearchCallArguments + """The arguments to pass to Google Search.""" + + type: Literal["google_search_call"] + + signature: Optional[str] = None + """A signature hash for backend validation.""" + + +class DeltaMCPServerToolCall(BaseModel): + id: str + """Required. A unique ID for this specific tool call.""" + + arguments: Dict[str, object] + + name: str + + server_name: str + + type: Literal["mcp_server_tool_call"] + + signature: Optional[str] = None + """A signature hash for backend validation.""" + + +class DeltaFileSearchCall(BaseModel): + id: str + """Required. A unique ID for this specific tool call.""" + + type: Literal["file_search_call"] + + signature: Optional[str] = None + """A signature hash for backend validation.""" + + +class DeltaGoogleMapsCall(BaseModel): + id: str + """Required. A unique ID for this specific tool call.""" + + type: Literal["google_maps_call"] + + arguments: Optional[GoogleMapsCallArguments] = None + """The arguments to pass to the Google Maps tool.""" + + signature: Optional[str] = None + """A signature hash for backend validation.""" + + +DeltaFunctionResultResultFunctionResultSubcontentList: TypeAlias = Annotated[ + Union[TextContent, ImageContent], PropertyInfo(discriminator="type") +] + + +class DeltaFunctionResult(BaseModel): + call_id: str + """Required. ID to match the ID from the function call block.""" + + result: Union[List[DeltaFunctionResultResultFunctionResultSubcontentList], str, object] + + type: Literal["function_result"] + + is_error: Optional[bool] = None + + name: Optional[str] = None + + signature: Optional[str] = None + """A signature hash for backend validation.""" + + +class DeltaCodeExecutionResult(BaseModel): + call_id: str + """Required. ID to match the ID from the function call block.""" + + result: str + + type: Literal["code_execution_result"] + + is_error: Optional[bool] = None + + signature: Optional[str] = None + """A signature hash for backend validation.""" + + +class DeltaURLContextResult(BaseModel): + call_id: str + """Required. ID to match the ID from the function call block.""" + + result: List[URLContextResult] + + type: Literal["url_context_result"] + + is_error: Optional[bool] = None + + signature: Optional[str] = None + """A signature hash for backend validation.""" + + +class DeltaGoogleSearchResult(BaseModel): + call_id: str + """Required. ID to match the ID from the function call block.""" + + result: List[GoogleSearchResult] + + type: Literal["google_search_result"] + + is_error: Optional[bool] = None + + signature: Optional[str] = None + """A signature hash for backend validation.""" + + +DeltaMCPServerToolResultResultFunctionResultSubcontentList: TypeAlias = Annotated[ + Union[TextContent, ImageContent], PropertyInfo(discriminator="type") +] + + +class DeltaMCPServerToolResult(BaseModel): + call_id: str + """Required. ID to match the ID from the function call block.""" + + result: Union[List[DeltaMCPServerToolResultResultFunctionResultSubcontentList], str, object] + + type: Literal["mcp_server_tool_result"] + + name: Optional[str] = None + + server_name: Optional[str] = None + + signature: Optional[str] = None + """A signature hash for backend validation.""" + + +class DeltaFileSearchResultResult(BaseModel): + """The result of the File Search.""" + + custom_metadata: Optional[List[object]] = None + """User provided metadata about the FileSearchResult.""" + + +class DeltaFileSearchResult(BaseModel): + call_id: str + """Required. ID to match the ID from the function call block.""" + + result: List[DeltaFileSearchResultResult] + + type: Literal["file_search_result"] + + signature: Optional[str] = None + """A signature hash for backend validation.""" + + +class DeltaGoogleMapsResult(BaseModel): + call_id: str + """Required. ID to match the ID from the function call block.""" + + type: Literal["google_maps_result"] + + result: Optional[List[GoogleMapsResult]] = None + """The results of the Google Maps.""" + + signature: Optional[str] = None + """A signature hash for backend validation.""" + + +class DeltaTextAnnotation(BaseModel): + type: Literal["text_annotation"] + + annotations: Optional[List[Annotation]] = None + """Citation information for model-generated content.""" + + +Delta: TypeAlias = Annotated[ + Union[ + DeltaText, + DeltaImage, + DeltaAudio, + DeltaDocument, + DeltaVideo, + DeltaThoughtSummary, + DeltaThoughtSignature, + DeltaFunctionCall, + DeltaCodeExecutionCall, + DeltaURLContextCall, + DeltaGoogleSearchCall, + DeltaMCPServerToolCall, + DeltaFileSearchCall, + DeltaGoogleMapsCall, + DeltaFunctionResult, + DeltaCodeExecutionResult, + DeltaURLContextResult, + DeltaGoogleSearchResult, + DeltaMCPServerToolResult, + DeltaFileSearchResult, + DeltaGoogleMapsResult, + DeltaTextAnnotation, + ], + PropertyInfo(discriminator="type"), +] + + +class ContentDelta(BaseModel): + delta: Delta + """The delta content data for a content block.""" + + event_type: Literal["content.delta"] + + index: int + + event_id: Optional[str] = None + """ + The event_id token to be used to resume the interaction stream, from this event. + """ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/content_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/content_param.py new file mode 100644 index 0000000000000000000000000000000000000000..34b864a33ee8121baa022984dcd2c9497d6d6313 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/content_param.py @@ -0,0 +1,67 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import TypeAlias + +from .text_content_param import TextContentParam +from .audio_content_param import AudioContentParam +from .image_content_param import ImageContentParam +from .video_content_param import VideoContentParam +from .thought_content_param import ThoughtContentParam +from .document_content_param import DocumentContentParam +from .function_call_content_param import FunctionCallContentParam +from .function_result_content_param import FunctionResultContentParam +from .file_search_call_content_param import FileSearchCallContentParam +from .google_maps_call_content_param import GoogleMapsCallContentParam +from .url_context_call_content_param import URLContextCallContentParam +from .file_search_result_content_param import FileSearchResultContentParam +from .google_maps_result_content_param import GoogleMapsResultContentParam +from .google_search_call_content_param import GoogleSearchCallContentParam +from .url_context_result_content_param import URLContextResultContentParam +from .code_execution_call_content_param import CodeExecutionCallContentParam +from .google_search_result_content_param import GoogleSearchResultContentParam +from .mcp_server_tool_call_content_param import MCPServerToolCallContentParam +from .code_execution_result_content_param import CodeExecutionResultContentParam +from .mcp_server_tool_result_content_param import MCPServerToolResultContentParam + +__all__ = ["ContentParam"] + +ContentParam: TypeAlias = Union[ + TextContentParam, + ImageContentParam, + AudioContentParam, + DocumentContentParam, + VideoContentParam, + ThoughtContentParam, + FunctionCallContentParam, + CodeExecutionCallContentParam, + URLContextCallContentParam, + MCPServerToolCallContentParam, + GoogleSearchCallContentParam, + FileSearchCallContentParam, + GoogleMapsCallContentParam, + FunctionResultContentParam, + CodeExecutionResultContentParam, + URLContextResultContentParam, + GoogleSearchResultContentParam, + MCPServerToolResultContentParam, + FileSearchResultContentParam, + GoogleMapsResultContentParam, +] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/content_start.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/content_start.py new file mode 100644 index 0000000000000000000000000000000000000000..1431cb1eb717c0df51108412b5da2585536bb3a8 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/content_start.py @@ -0,0 +1,38 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .content import Content +from .._models import BaseModel + +__all__ = ["ContentStart"] + + +class ContentStart(BaseModel): + content: Content + """The content of the response.""" + + event_type: Literal["content.start"] + + index: int + + event_id: Optional[str] = None + """ + The event_id token to be used to resume the interaction stream, from this event. + """ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/content_stop.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/content_stop.py new file mode 100644 index 0000000000000000000000000000000000000000..578c1f2c9587644c96cffa9d740a0e41416944af --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/content_stop.py @@ -0,0 +1,34 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["ContentStop"] + + +class ContentStop(BaseModel): + event_type: Literal["content.stop"] + + index: int + + event_id: Optional[str] = None + """ + The event_id token to be used to resume the interaction stream, from this event. + """ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/deep_research_agent_config.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/deep_research_agent_config.py new file mode 100644 index 0000000000000000000000000000000000000000..f98b6734869532a380dbc78a33aa7fe0acf6518b --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/deep_research_agent_config.py @@ -0,0 +1,43 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["DeepResearchAgentConfig"] + + +class DeepResearchAgentConfig(BaseModel): + """Configuration for the Deep Research agent.""" + + type: Literal["deep-research"] + + collaborative_planning: Optional[bool] = None + """Enables human-in-the-loop planning for the Deep Research agent. + + If set to true, the Deep Research agent will provide a research plan in its + response. The agent will then proceed only if the user confirms the plan in the + next turn. Relevant issue: b/482352502. + """ + + thinking_summaries: Optional[Literal["auto", "none"]] = None + """Whether to include thought summaries in the response.""" + + visualization: Optional[Literal["off", "auto"]] = None + """Whether to include visualizations in the response.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/deep_research_agent_config_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/deep_research_agent_config_param.py new file mode 100644 index 0000000000000000000000000000000000000000..fa2350429918b5ba73eb160741659f0acf2bdae6 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/deep_research_agent_config_param.py @@ -0,0 +1,42 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["DeepResearchAgentConfigParam"] + + +class DeepResearchAgentConfigParam(TypedDict, total=False): + """Configuration for the Deep Research agent.""" + + type: Required[Literal["deep-research"]] + + collaborative_planning: bool + """Enables human-in-the-loop planning for the Deep Research agent. + + If set to true, the Deep Research agent will provide a research plan in its + response. The agent will then proceed only if the user confirms the plan in the + next turn. Relevant issue: b/482352502. + """ + + thinking_summaries: Literal["auto", "none"] + """Whether to include thought summaries in the response.""" + + visualization: Literal["off", "auto"] + """Whether to include visualizations in the response.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/document_content.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/document_content.py new file mode 100644 index 0000000000000000000000000000000000000000..846f7b5683f844906e6725799339240ded58b759 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/document_content.py @@ -0,0 +1,38 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["DocumentContent"] + + +class DocumentContent(BaseModel): + """A document content block.""" + + type: Literal["document"] + + data: Optional[str] = None + """The document content.""" + + mime_type: Optional[Literal["application/pdf"]] = None + """The mime type of the document.""" + + uri: Optional[str] = None + """The URI of the document.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/document_content_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/document_content_param.py new file mode 100644 index 0000000000000000000000000000000000000000..f8b4c6cb93f1973c5499aac819da992b37be1978 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/document_content_param.py @@ -0,0 +1,45 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import Literal, Required, Annotated, TypedDict + +from .._types import Base64FileInput +from .._utils import PropertyInfo +from .._models import set_pydantic_config + +__all__ = ["DocumentContentParam"] + + +class DocumentContentParam(TypedDict, total=False): + """A document content block.""" + + type: Required[Literal["document"]] + + data: Annotated[Union[str, Base64FileInput], PropertyInfo(format="base64")] + """The document content.""" + + mime_type: Literal["application/pdf"] + """The mime type of the document.""" + + uri: str + """The URI of the document.""" + + +set_pydantic_config(DocumentContentParam, {"arbitrary_types_allowed": True}) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/dynamic_agent_config.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/dynamic_agent_config.py new file mode 100644 index 0000000000000000000000000000000000000000..e217d9df92ebcb248152651ca24e5e420ba84aea --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/dynamic_agent_config.py @@ -0,0 +1,43 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import TYPE_CHECKING, Dict +from typing_extensions import Literal + +from pydantic import Field as FieldInfo + +from .._models import BaseModel + +__all__ = ["DynamicAgentConfig"] + + +class DynamicAgentConfig(BaseModel): + """Configuration for dynamic agents.""" + + type: Literal["dynamic"] + + if TYPE_CHECKING: + # Some versions of Pydantic <2.8.0 have a bug and don’t allow assigning a + # value to this field, so for compatibility we avoid doing it at runtime. + __pydantic_extra__: Dict[str, object] = FieldInfo(init=False) # pyright: ignore[reportIncompatibleVariableOverride] + + # Stub to indicate that arbitrary properties are accepted. + # To access properties that are not valid identifiers you can use `getattr`, e.g. + # `getattr(obj, '$type')` + def __getattr__(self, attr: str) -> object: ... + else: + __pydantic_extra__: Dict[str, object] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/dynamic_agent_config_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/dynamic_agent_config_param.py new file mode 100644 index 0000000000000000000000000000000000000000..bc7844e22acfb9e81947b203a0b874060ed88570 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/dynamic_agent_config_param.py @@ -0,0 +1,28 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["DynamicAgentConfigParam"] + + +class DynamicAgentConfigParam(TypedDict, total=False, extra_items=object): # type: ignore[call-arg] + """Configuration for dynamic agents.""" + + type: Required[Literal["dynamic"]] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/error_event.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/error_event.py new file mode 100644 index 0000000000000000000000000000000000000000..8abf8ca3e983346ace001a1f222c24c165be624c --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/error_event.py @@ -0,0 +1,45 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["ErrorEvent", "Error"] + + +class Error(BaseModel): + """Error message from an interaction.""" + + code: Optional[str] = None + """A URI that identifies the error type.""" + + message: Optional[str] = None + """A human-readable error message.""" + + +class ErrorEvent(BaseModel): + event_type: Literal["error"] + + error: Optional[Error] = None + """Error message from an interaction.""" + + event_id: Optional[str] = None + """ + The event_id token to be used to resume the interaction stream, from this event. + """ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/file_citation.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/file_citation.py new file mode 100644 index 0000000000000000000000000000000000000000..d6f7605058c87677d368b4dd260da661a26669ab --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/file_citation.py @@ -0,0 +1,47 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["FileCitation"] + + +class FileCitation(BaseModel): + """A file citation annotation.""" + + type: Literal["file_citation"] + + document_uri: Optional[str] = None + """The URI of the file.""" + + end_index: Optional[int] = None + """End of the attributed segment, exclusive.""" + + file_name: Optional[str] = None + """The name of the file.""" + + source: Optional[str] = None + """Source attributed for a portion of the text.""" + + start_index: Optional[int] = None + """Start of segment of the response that is attributed to this source. + + Index indicates the start of the segment, measured in bytes. + """ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/file_citation_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/file_citation_param.py new file mode 100644 index 0000000000000000000000000000000000000000..e7ccff9346870310cd01f46ec23de33b2bd6667a --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/file_citation_param.py @@ -0,0 +1,46 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["FileCitationParam"] + + +class FileCitationParam(TypedDict, total=False): + """A file citation annotation.""" + + type: Required[Literal["file_citation"]] + + document_uri: str + """The URI of the file.""" + + end_index: int + """End of the attributed segment, exclusive.""" + + file_name: str + """The name of the file.""" + + source: str + """Source attributed for a portion of the text.""" + + start_index: int + """Start of segment of the response that is attributed to this source. + + Index indicates the start of the segment, measured in bytes. + """ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/file_search_call_content.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/file_search_call_content.py new file mode 100644 index 0000000000000000000000000000000000000000..d1e4b9fc5f72af2ca8752cdcfc0e342e9e9938c4 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/file_search_call_content.py @@ -0,0 +1,35 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["FileSearchCallContent"] + + +class FileSearchCallContent(BaseModel): + """File Search content.""" + + id: str + """Required. A unique ID for this specific tool call.""" + + type: Literal["file_search_call"] + + signature: Optional[str] = None + """A signature hash for backend validation.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/file_search_call_content_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/file_search_call_content_param.py new file mode 100644 index 0000000000000000000000000000000000000000..e9ff0c725ca0a82c5f1d69dc74b5248d1ad01f2f --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/file_search_call_content_param.py @@ -0,0 +1,42 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import Literal, Required, Annotated, TypedDict + +from .._types import Base64FileInput +from .._utils import PropertyInfo +from .._models import set_pydantic_config + +__all__ = ["FileSearchCallContentParam"] + + +class FileSearchCallContentParam(TypedDict, total=False): + """File Search content.""" + + id: Required[str] + """Required. A unique ID for this specific tool call.""" + + type: Required[Literal["file_search_call"]] + + signature: Annotated[Union[str, Base64FileInput], PropertyInfo(format="base64")] + """A signature hash for backend validation.""" + + +set_pydantic_config(FileSearchCallContentParam, {"arbitrary_types_allowed": True}) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/file_search_result_content.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/file_search_result_content.py new file mode 100644 index 0000000000000000000000000000000000000000..84644074d3cdfd30f50968be4b75c7d66b06f9f0 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/file_search_result_content.py @@ -0,0 +1,45 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["FileSearchResultContent", "Result"] + + +class Result(BaseModel): + """The result of the File Search.""" + + custom_metadata: Optional[List[object]] = None + """User provided metadata about the FileSearchResult.""" + + +class FileSearchResultContent(BaseModel): + """File Search result content.""" + + call_id: str + """Required. ID to match the ID from the function call block.""" + + result: List[Result] + """Required. The results of the File Search.""" + + type: Literal["file_search_result"] + + signature: Optional[str] = None + """A signature hash for backend validation.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/file_search_result_content_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/file_search_result_content_param.py new file mode 100644 index 0000000000000000000000000000000000000000..16ddc80a6b2a85207f5e3aaef005d41be4c78e8b --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/file_search_result_content_param.py @@ -0,0 +1,52 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Iterable +from typing_extensions import Literal, Required, Annotated, TypedDict + +from .._types import Base64FileInput +from .._utils import PropertyInfo +from .._models import set_pydantic_config + +__all__ = ["FileSearchResultContentParam", "Result"] + + +class Result(TypedDict, total=False): + """The result of the File Search.""" + + custom_metadata: Iterable[object] + """User provided metadata about the FileSearchResult.""" + + +class FileSearchResultContentParam(TypedDict, total=False): + """File Search result content.""" + + call_id: Required[str] + """Required. ID to match the ID from the function call block.""" + + result: Required[Iterable[Result]] + """Required. The results of the File Search.""" + + type: Required[Literal["file_search_result"]] + + signature: Annotated[Union[str, Base64FileInput], PropertyInfo(format="base64")] + """A signature hash for backend validation.""" + + +set_pydantic_config(FileSearchResultContentParam, {"arbitrary_types_allowed": True}) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/function.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/function.py new file mode 100644 index 0000000000000000000000000000000000000000..ce14b04148de4d5adc0660ce1832376c896b4f4d --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/function.py @@ -0,0 +1,38 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["Function"] + + +class Function(BaseModel): + """A tool that can be used by the model.""" + + type: Literal["function"] + + description: Optional[str] = None + """A description of the function.""" + + name: Optional[str] = None + """The name of the function.""" + + parameters: Optional[object] = None + """The JSON Schema for the function's parameters.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/function_call_content.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/function_call_content.py new file mode 100644 index 0000000000000000000000000000000000000000..49bcaa635b20ca2828b571fdf4ddece849bae17b --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/function_call_content.py @@ -0,0 +1,41 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, Optional +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["FunctionCallContent"] + + +class FunctionCallContent(BaseModel): + """A function tool call content block.""" + + id: str + """Required. A unique ID for this specific tool call.""" + + arguments: Dict[str, object] + """Required. The arguments to pass to the function.""" + + name: str + """Required. The name of the tool to call.""" + + type: Literal["function_call"] + + signature: Optional[str] = None + """A signature hash for backend validation.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/function_call_content_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/function_call_content_param.py new file mode 100644 index 0000000000000000000000000000000000000000..d3c51bc57ef60d3d08b3999010fb194a45efe6d4 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/function_call_content_param.py @@ -0,0 +1,48 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, Union +from typing_extensions import Literal, Required, Annotated, TypedDict + +from .._types import Base64FileInput +from .._utils import PropertyInfo +from .._models import set_pydantic_config + +__all__ = ["FunctionCallContentParam"] + + +class FunctionCallContentParam(TypedDict, total=False): + """A function tool call content block.""" + + id: Required[str] + """Required. A unique ID for this specific tool call.""" + + arguments: Required[Dict[str, object]] + """Required. The arguments to pass to the function.""" + + name: Required[str] + """Required. The name of the tool to call.""" + + type: Required[Literal["function_call"]] + + signature: Annotated[Union[str, Base64FileInput], PropertyInfo(format="base64")] + """A signature hash for backend validation.""" + + +set_pydantic_config(FunctionCallContentParam, {"arbitrary_types_allowed": True}) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/function_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/function_param.py new file mode 100644 index 0000000000000000000000000000000000000000..32da748bd3e92865c4b9fa4f8a59c85b0abe0ff6 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/function_param.py @@ -0,0 +1,37 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["FunctionParam"] + + +class FunctionParam(TypedDict, total=False): + """A tool that can be used by the model.""" + + type: Required[Literal["function"]] + + description: str + """A description of the function.""" + + name: str + """The name of the function.""" + + parameters: object + """The JSON Schema for the function's parameters.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/function_result_content.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/function_result_content.py new file mode 100644 index 0000000000000000000000000000000000000000..bb398f05d3e7204fb961e5fc9ee0df071ba26c83 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/function_result_content.py @@ -0,0 +1,51 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union, Optional +from typing_extensions import Literal, Annotated, TypeAlias + +from .._utils import PropertyInfo +from .._models import BaseModel +from .text_content import TextContent +from .image_content import ImageContent + +__all__ = ["FunctionResultContent", "ResultFunctionResultSubcontentList"] + +ResultFunctionResultSubcontentList: TypeAlias = Annotated[ + Union[TextContent, ImageContent], PropertyInfo(discriminator="type") +] + + +class FunctionResultContent(BaseModel): + """A function tool result content block.""" + + call_id: str + """Required. ID to match the ID from the function call block.""" + + result: Union[List[ResultFunctionResultSubcontentList], str, object] + """The result of the tool call.""" + + type: Literal["function_result"] + + is_error: Optional[bool] = None + """Whether the tool call resulted in an error.""" + + name: Optional[str] = None + """The name of the tool that was called.""" + + signature: Optional[str] = None + """A signature hash for backend validation.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/function_result_content_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/function_result_content_param.py new file mode 100644 index 0000000000000000000000000000000000000000..df24036097a9d195af0af3a1704d557173fbe5db --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/function_result_content_param.py @@ -0,0 +1,55 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Iterable +from typing_extensions import Literal, Required, Annotated, TypeAlias, TypedDict + +from .._types import Base64FileInput +from .._utils import PropertyInfo +from .._models import set_pydantic_config +from .text_content_param import TextContentParam +from .image_content_param import ImageContentParam + +__all__ = ["FunctionResultContentParam", "ResultFunctionResultSubcontentList"] + +ResultFunctionResultSubcontentList: TypeAlias = Union[TextContentParam, ImageContentParam] + + +class FunctionResultContentParam(TypedDict, total=False): + """A function tool result content block.""" + + call_id: Required[str] + """Required. ID to match the ID from the function call block.""" + + result: Required[Union[Iterable[ResultFunctionResultSubcontentList], str, object]] + """The result of the tool call.""" + + type: Required[Literal["function_result"]] + + is_error: bool + """Whether the tool call resulted in an error.""" + + name: str + """The name of the tool that was called.""" + + signature: Annotated[Union[str, Base64FileInput], PropertyInfo(format="base64")] + """A signature hash for backend validation.""" + + +set_pydantic_config(FunctionResultContentParam, {"arbitrary_types_allowed": True}) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/generation_config.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/generation_config.py new file mode 100644 index 0000000000000000000000000000000000000000..cf2b99c9a2f98a61cc233379e74ed5094458d251 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/generation_config.py @@ -0,0 +1,64 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union, Optional +from typing_extensions import Literal, TypeAlias + +from .._models import BaseModel +from .image_config import ImageConfig +from .speech_config import SpeechConfig +from .thinking_level import ThinkingLevel +from .tool_choice_type import ToolChoiceType +from .tool_choice_config import ToolChoiceConfig + +__all__ = ["GenerationConfig", "ToolChoice"] + +ToolChoice: TypeAlias = Union[ToolChoiceType, ToolChoiceConfig] + + +class GenerationConfig(BaseModel): + """Configuration parameters for model interactions.""" + + image_config: Optional[ImageConfig] = None + """Configuration for image interaction.""" + + max_output_tokens: Optional[int] = None + """The maximum number of tokens to include in the response.""" + + seed: Optional[int] = None + """Seed used in decoding for reproducibility.""" + + speech_config: Optional[List[SpeechConfig]] = None + """Configuration for speech interaction.""" + + stop_sequences: Optional[List[str]] = None + """A list of character sequences that will stop output interaction.""" + + temperature: Optional[float] = None + """Controls the randomness of the output.""" + + thinking_level: Optional[ThinkingLevel] = None + """The level of thought tokens that the model should generate.""" + + thinking_summaries: Optional[Literal["auto", "none"]] = None + """Whether to include thought summaries in the response.""" + + tool_choice: Optional[ToolChoice] = None + """The tool choice configuration.""" + + top_p: Optional[float] = None + """The maximum cumulative probability of tokens to consider when sampling.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/generation_config_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/generation_config_param.py new file mode 100644 index 0000000000000000000000000000000000000000..286df776660708c229c18a1760088a107d72ee2e --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/generation_config_param.py @@ -0,0 +1,66 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Iterable +from typing_extensions import Literal, TypeAlias, TypedDict + +from .._types import SequenceNotStr +from .thinking_level import ThinkingLevel +from .tool_choice_type import ToolChoiceType +from .image_config_param import ImageConfigParam +from .speech_config_param import SpeechConfigParam +from .tool_choice_config_param import ToolChoiceConfigParam + +__all__ = ["GenerationConfigParam", "ToolChoice"] + +ToolChoice: TypeAlias = Union[ToolChoiceType, ToolChoiceConfigParam] + + +class GenerationConfigParam(TypedDict, total=False): + """Configuration parameters for model interactions.""" + + image_config: ImageConfigParam + """Configuration for image interaction.""" + + max_output_tokens: int + """The maximum number of tokens to include in the response.""" + + seed: int + """Seed used in decoding for reproducibility.""" + + speech_config: Iterable[SpeechConfigParam] + """Configuration for speech interaction.""" + + stop_sequences: SequenceNotStr[str] + """A list of character sequences that will stop output interaction.""" + + temperature: float + """Controls the randomness of the output.""" + + thinking_level: ThinkingLevel + """The level of thought tokens that the model should generate.""" + + thinking_summaries: Literal["auto", "none"] + """Whether to include thought summaries in the response.""" + + tool_choice: ToolChoice + """The tool choice configuration.""" + + top_p: float + """The maximum cumulative probability of tokens to consider when sampling.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_maps_call_arguments.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_maps_call_arguments.py new file mode 100644 index 0000000000000000000000000000000000000000..3976e8779b28a49431a2a8b33c16c604b7e2a39a --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_maps_call_arguments.py @@ -0,0 +1,29 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional + +from .._models import BaseModel + +__all__ = ["GoogleMapsCallArguments"] + + +class GoogleMapsCallArguments(BaseModel): + """The arguments to pass to the Google Maps tool.""" + + queries: Optional[List[str]] = None + """The queries to be executed.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_maps_call_arguments_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_maps_call_arguments_param.py new file mode 100644 index 0000000000000000000000000000000000000000..26cb3bf9752e7e89e162ddc966fe30354f713e50 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_maps_call_arguments_param.py @@ -0,0 +1,31 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import TypedDict + +from .._types import SequenceNotStr + +__all__ = ["GoogleMapsCallArgumentsParam"] + + +class GoogleMapsCallArgumentsParam(TypedDict, total=False): + """The arguments to pass to the Google Maps tool.""" + + queries: SequenceNotStr[str] + """The queries to be executed.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_maps_call_content.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_maps_call_content.py new file mode 100644 index 0000000000000000000000000000000000000000..688108a7172e2561d30ded5b22121d3706995661 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_maps_call_content.py @@ -0,0 +1,39 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .._models import BaseModel +from .google_maps_call_arguments import GoogleMapsCallArguments + +__all__ = ["GoogleMapsCallContent"] + + +class GoogleMapsCallContent(BaseModel): + """Google Maps content.""" + + id: str + """Required. A unique ID for this specific tool call.""" + + type: Literal["google_maps_call"] + + arguments: Optional[GoogleMapsCallArguments] = None + """The arguments to pass to the Google Maps tool.""" + + signature: Optional[str] = None + """A signature hash for backend validation.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_maps_call_content_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_maps_call_content_param.py new file mode 100644 index 0000000000000000000000000000000000000000..c39d1e2389adaaacc7be26053a37130a5e21b062 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_maps_call_content_param.py @@ -0,0 +1,46 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import Literal, Required, Annotated, TypedDict + +from .._types import Base64FileInput +from .._utils import PropertyInfo +from .._models import set_pydantic_config +from .google_maps_call_arguments_param import GoogleMapsCallArgumentsParam + +__all__ = ["GoogleMapsCallContentParam"] + + +class GoogleMapsCallContentParam(TypedDict, total=False): + """Google Maps content.""" + + id: Required[str] + """Required. A unique ID for this specific tool call.""" + + type: Required[Literal["google_maps_call"]] + + arguments: GoogleMapsCallArgumentsParam + """The arguments to pass to the Google Maps tool.""" + + signature: Annotated[Union[str, Base64FileInput], PropertyInfo(format="base64")] + """A signature hash for backend validation.""" + + +set_pydantic_config(GoogleMapsCallContentParam, {"arbitrary_types_allowed": True}) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_maps_result.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_maps_result.py new file mode 100644 index 0000000000000000000000000000000000000000..bc2bc528b9f8891058584d0b7d7596bc2e3acfe2 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_maps_result.py @@ -0,0 +1,65 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional + +from .._models import BaseModel + +__all__ = ["GoogleMapsResult", "Place", "PlaceReviewSnippet"] + + +class PlaceReviewSnippet(BaseModel): + """ + Encapsulates a snippet of a user review that answers a question about + the features of a specific place in Google Maps. + """ + + review_id: Optional[str] = None + """The ID of the review snippet.""" + + title: Optional[str] = None + """Title of the review.""" + + url: Optional[str] = None + """A link that corresponds to the user review on Google Maps.""" + + +class Place(BaseModel): + name: Optional[str] = None + """Title of the place.""" + + place_id: Optional[str] = None + """The ID of the place, in `places/{place_id}` format.""" + + review_snippets: Optional[List[PlaceReviewSnippet]] = None + """ + Snippets of reviews that are used to generate answers about the features of a + given place in Google Maps. + """ + + url: Optional[str] = None + """URI reference of the place.""" + + +class GoogleMapsResult(BaseModel): + """The result of the Google Maps.""" + + places: Optional[List[Place]] = None + """The places that were found.""" + + widget_context_token: Optional[str] = None + """Resource name of the Google Maps widget context token.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_maps_result_content.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_maps_result_content.py new file mode 100644 index 0000000000000000000000000000000000000000..4e959ba5690e8a663cfe990056097403e1d097cd --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_maps_result_content.py @@ -0,0 +1,39 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional +from typing_extensions import Literal + +from .._models import BaseModel +from .google_maps_result import GoogleMapsResult + +__all__ = ["GoogleMapsResultContent"] + + +class GoogleMapsResultContent(BaseModel): + """Google Maps result content.""" + + call_id: str + """Required. ID to match the ID from the function call block.""" + + result: List[GoogleMapsResult] + """Required. The results of the Google Maps.""" + + type: Literal["google_maps_result"] + + signature: Optional[str] = None + """A signature hash for backend validation.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_maps_result_content_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_maps_result_content_param.py new file mode 100644 index 0000000000000000000000000000000000000000..e29b9c3f40b5b4c00a52b522ef178ea9bb7e8aaa --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_maps_result_content_param.py @@ -0,0 +1,46 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Iterable +from typing_extensions import Literal, Required, Annotated, TypedDict + +from .._types import Base64FileInput +from .._utils import PropertyInfo +from .._models import set_pydantic_config +from .google_maps_result_param import GoogleMapsResultParam + +__all__ = ["GoogleMapsResultContentParam"] + + +class GoogleMapsResultContentParam(TypedDict, total=False): + """Google Maps result content.""" + + call_id: Required[str] + """Required. ID to match the ID from the function call block.""" + + result: Required[Iterable[GoogleMapsResultParam]] + """Required. The results of the Google Maps.""" + + type: Required[Literal["google_maps_result"]] + + signature: Annotated[Union[str, Base64FileInput], PropertyInfo(format="base64")] + """A signature hash for backend validation.""" + + +set_pydantic_config(GoogleMapsResultContentParam, {"arbitrary_types_allowed": True}) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_maps_result_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_maps_result_param.py new file mode 100644 index 0000000000000000000000000000000000000000..9774a5357be302e243cdb1f38ae48fecf319f7f6 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_maps_result_param.py @@ -0,0 +1,66 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable +from typing_extensions import TypedDict + +__all__ = ["GoogleMapsResultParam", "Place", "PlaceReviewSnippet"] + + +class PlaceReviewSnippet(TypedDict, total=False): + """ + Encapsulates a snippet of a user review that answers a question about + the features of a specific place in Google Maps. + """ + + review_id: str + """The ID of the review snippet.""" + + title: str + """Title of the review.""" + + url: str + """A link that corresponds to the user review on Google Maps.""" + + +class Place(TypedDict, total=False): + name: str + """Title of the place.""" + + place_id: str + """The ID of the place, in `places/{place_id}` format.""" + + review_snippets: Iterable[PlaceReviewSnippet] + """ + Snippets of reviews that are used to generate answers about the features of a + given place in Google Maps. + """ + + url: str + """URI reference of the place.""" + + +class GoogleMapsResultParam(TypedDict, total=False): + """The result of the Google Maps.""" + + places: Iterable[Place] + """The places that were found.""" + + widget_context_token: str + """Resource name of the Google Maps widget context token.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_search_call_arguments.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_search_call_arguments.py new file mode 100644 index 0000000000000000000000000000000000000000..9d93e71f29edfc035c6f36b17e26366b46a44926 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_search_call_arguments.py @@ -0,0 +1,29 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional + +from .._models import BaseModel + +__all__ = ["GoogleSearchCallArguments"] + + +class GoogleSearchCallArguments(BaseModel): + """The arguments to pass to Google Search.""" + + queries: Optional[List[str]] = None + """Web search queries for the following-up web search.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_search_call_arguments_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_search_call_arguments_param.py new file mode 100644 index 0000000000000000000000000000000000000000..086c2382ebf392dda74dccdccc5af79b3c754e02 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_search_call_arguments_param.py @@ -0,0 +1,31 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import TypedDict + +from .._types import SequenceNotStr + +__all__ = ["GoogleSearchCallArgumentsParam"] + + +class GoogleSearchCallArgumentsParam(TypedDict, total=False): + """The arguments to pass to Google Search.""" + + queries: SequenceNotStr[str] + """Web search queries for the following-up web search.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_search_call_content.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_search_call_content.py new file mode 100644 index 0000000000000000000000000000000000000000..5703202fe9fa17e33681d49ab024fa284986e6d1 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_search_call_content.py @@ -0,0 +1,42 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .._models import BaseModel +from .google_search_call_arguments import GoogleSearchCallArguments + +__all__ = ["GoogleSearchCallContent"] + + +class GoogleSearchCallContent(BaseModel): + """Google Search content.""" + + id: str + """Required. A unique ID for this specific tool call.""" + + arguments: GoogleSearchCallArguments + """Required. The arguments to pass to Google Search.""" + + type: Literal["google_search_call"] + + search_type: Optional[Literal["web_search", "image_search", "enterprise_web_search"]] = None + """The type of search grounding enabled.""" + + signature: Optional[str] = None + """A signature hash for backend validation.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_search_call_content_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_search_call_content_param.py new file mode 100644 index 0000000000000000000000000000000000000000..7e98d0d079e6f9327b7a74787d2d13132e211eca --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_search_call_content_param.py @@ -0,0 +1,49 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import Literal, Required, Annotated, TypedDict + +from .._types import Base64FileInput +from .._utils import PropertyInfo +from .._models import set_pydantic_config +from .google_search_call_arguments_param import GoogleSearchCallArgumentsParam + +__all__ = ["GoogleSearchCallContentParam"] + + +class GoogleSearchCallContentParam(TypedDict, total=False): + """Google Search content.""" + + id: Required[str] + """Required. A unique ID for this specific tool call.""" + + arguments: Required[GoogleSearchCallArgumentsParam] + """Required. The arguments to pass to Google Search.""" + + type: Required[Literal["google_search_call"]] + + search_type: Literal["web_search", "image_search", "enterprise_web_search"] + """The type of search grounding enabled.""" + + signature: Annotated[Union[str, Base64FileInput], PropertyInfo(format="base64")] + """A signature hash for backend validation.""" + + +set_pydantic_config(GoogleSearchCallContentParam, {"arbitrary_types_allowed": True}) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_search_result.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_search_result.py new file mode 100644 index 0000000000000000000000000000000000000000..9691f5d40e399cc4de0b22f661d1853d1092cc18 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_search_result.py @@ -0,0 +1,29 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from .._models import BaseModel + +__all__ = ["GoogleSearchResult"] + + +class GoogleSearchResult(BaseModel): + """The result of the Google Search.""" + + search_suggestions: Optional[str] = None + """Web content snippet that can be embedded in a web page or an app webview.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_search_result_content.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_search_result_content.py new file mode 100644 index 0000000000000000000000000000000000000000..be15b8c623b5bb7ac8e7e083dacf7522d46885d0 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_search_result_content.py @@ -0,0 +1,42 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional +from typing_extensions import Literal + +from .._models import BaseModel +from .google_search_result import GoogleSearchResult + +__all__ = ["GoogleSearchResultContent"] + + +class GoogleSearchResultContent(BaseModel): + """Google Search result content.""" + + call_id: str + """Required. ID to match the ID from the function call block.""" + + result: List[GoogleSearchResult] + """Required. The results of the Google Search.""" + + type: Literal["google_search_result"] + + is_error: Optional[bool] = None + """Whether the Google Search resulted in an error.""" + + signature: Optional[str] = None + """A signature hash for backend validation.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_search_result_content_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_search_result_content_param.py new file mode 100644 index 0000000000000000000000000000000000000000..039d00efc1f693c7075a7aea4a01ae17cb477893 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_search_result_content_param.py @@ -0,0 +1,49 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Iterable +from typing_extensions import Literal, Required, Annotated, TypedDict + +from .._types import Base64FileInput +from .._utils import PropertyInfo +from .._models import set_pydantic_config +from .google_search_result_param import GoogleSearchResultParam + +__all__ = ["GoogleSearchResultContentParam"] + + +class GoogleSearchResultContentParam(TypedDict, total=False): + """Google Search result content.""" + + call_id: Required[str] + """Required. ID to match the ID from the function call block.""" + + result: Required[Iterable[GoogleSearchResultParam]] + """Required. The results of the Google Search.""" + + type: Required[Literal["google_search_result"]] + + is_error: bool + """Whether the Google Search resulted in an error.""" + + signature: Annotated[Union[str, Base64FileInput], PropertyInfo(format="base64")] + """A signature hash for backend validation.""" + + +set_pydantic_config(GoogleSearchResultContentParam, {"arbitrary_types_allowed": True}) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_search_result_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_search_result_param.py new file mode 100644 index 0000000000000000000000000000000000000000..be1d11d519d1aaacc890c8a253a419fe9a24de47 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/google_search_result_param.py @@ -0,0 +1,29 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import TypedDict + +__all__ = ["GoogleSearchResultParam"] + + +class GoogleSearchResultParam(TypedDict, total=False): + """The result of the Google Search.""" + + search_suggestions: str + """Web content snippet that can be embedded in a web page or an app webview.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/image_config.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/image_config.py new file mode 100644 index 0000000000000000000000000000000000000000..a0d35b37a0b6add4faa7e35e13f898e08eb56d80 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/image_config.py @@ -0,0 +1,33 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["ImageConfig"] + + +class ImageConfig(BaseModel): + """The configuration for image interaction.""" + + aspect_ratio: Optional[ + Literal["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9", "1:8", "8:1", "1:4", "4:1"] + ] = None + + image_size: Optional[Literal["1K", "2K", "4K", "512"]] = None diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/image_config_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/image_config_param.py new file mode 100644 index 0000000000000000000000000000000000000000..d88dad86992739137833c58831a8c8bda46d5f75 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/image_config_param.py @@ -0,0 +1,32 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, TypedDict + +__all__ = ["ImageConfigParam"] + + +class ImageConfigParam(TypedDict, total=False): + """The configuration for image interaction.""" + + aspect_ratio: Literal[ + "1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9", "1:8", "8:1", "1:4", "4:1" + ] + + image_size: Literal["1K", "2K", "4K", "512"] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/image_content.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/image_content.py new file mode 100644 index 0000000000000000000000000000000000000000..c0c90ed6323ff8a84d68b3d7d57de92991e8622e --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/image_content.py @@ -0,0 +1,45 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["ImageContent"] + + +class ImageContent(BaseModel): + """An image content block.""" + + type: Literal["image"] + + data: Optional[str] = None + """The image content.""" + + mime_type: Optional[ + Literal[ + "image/png", "image/jpeg", "image/webp", "image/heic", "image/heif", "image/gif", "image/bmp", "image/tiff" + ] + ] = None + """The mime type of the image.""" + + resolution: Optional[Literal["low", "medium", "high", "ultra_high"]] = None + """The resolution of the media.""" + + uri: Optional[str] = None + """The URI of the image.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/image_content_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/image_content_param.py new file mode 100644 index 0000000000000000000000000000000000000000..7fd5456b21d0d64243aed6fcf36d0a9b88f579d4 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/image_content_param.py @@ -0,0 +1,50 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import Literal, Required, Annotated, TypedDict + +from .._types import Base64FileInput +from .._utils import PropertyInfo +from .._models import set_pydantic_config + +__all__ = ["ImageContentParam"] + + +class ImageContentParam(TypedDict, total=False): + """An image content block.""" + + type: Required[Literal["image"]] + + data: Annotated[Union[str, Base64FileInput], PropertyInfo(format="base64")] + """The image content.""" + + mime_type: Literal[ + "image/png", "image/jpeg", "image/webp", "image/heic", "image/heif", "image/gif", "image/bmp", "image/tiff" + ] + """The mime type of the image.""" + + resolution: Literal["low", "medium", "high", "ultra_high"] + """The resolution of the media.""" + + uri: str + """The URI of the image.""" + + +set_pydantic_config(ImageContentParam, {"arbitrary_types_allowed": True}) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/interaction.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/interaction.py new file mode 100644 index 0000000000000000000000000000000000000000..1beedbde2bc4bc2435b3aa91aaeb1c4e6ae5241f --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/interaction.py @@ -0,0 +1,159 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union, Optional +from datetime import datetime +from typing_extensions import Literal, Annotated, TypeAlias + +from .tool import Tool +from .turn import Turn +from .model import Model +from .usage import Usage +from .._utils import PropertyInfo +from .content import Content +from .._models import BaseModel +from .text_content import TextContent +from .audio_content import AudioContent +from .image_content import ImageContent +from .video_content import VideoContent +from .webhook_config import WebhookConfig +from .thought_content import ThoughtContent +from .document_content import DocumentContent +from .dynamic_agent_config import DynamicAgentConfig +from .function_call_content import FunctionCallContent +from .function_result_content import FunctionResultContent +from .file_search_call_content import FileSearchCallContent +from .google_maps_call_content import GoogleMapsCallContent +from .url_context_call_content import URLContextCallContent +from .deep_research_agent_config import DeepResearchAgentConfig +from .file_search_result_content import FileSearchResultContent +from .google_maps_result_content import GoogleMapsResultContent +from .google_search_call_content import GoogleSearchCallContent +from .url_context_result_content import URLContextResultContent +from .code_execution_call_content import CodeExecutionCallContent +from .google_search_result_content import GoogleSearchResultContent +from .mcp_server_tool_call_content import MCPServerToolCallContent +from .code_execution_result_content import CodeExecutionResultContent +from .mcp_server_tool_result_content import MCPServerToolResultContent + +__all__ = ["Interaction", "AgentConfig", "Input"] + +AgentConfig: TypeAlias = Annotated[ + Union[DynamicAgentConfig, DeepResearchAgentConfig], PropertyInfo(discriminator="type") +] + +Input: TypeAlias = Union[ + List[Content], + str, + List[Turn], + TextContent, + ImageContent, + AudioContent, + DocumentContent, + VideoContent, + ThoughtContent, + FunctionCallContent, + CodeExecutionCallContent, + URLContextCallContent, + MCPServerToolCallContent, + GoogleSearchCallContent, + FileSearchCallContent, + GoogleMapsCallContent, + FunctionResultContent, + CodeExecutionResultContent, + URLContextResultContent, + GoogleSearchResultContent, + MCPServerToolResultContent, + FileSearchResultContent, + GoogleMapsResultContent, +] + + +class Interaction(BaseModel): + """The Interaction resource.""" + + id: str + """Required. Output only. A unique identifier for the interaction completion.""" + + created: datetime + """Required. + + Output only. The time at which the response was created in ISO 8601 format + (YYYY-MM-DDThh:mm:ssZ). + """ + + status: Literal["in_progress", "requires_action", "completed", "failed", "cancelled", "incomplete"] + """Required. Output only. The status of the interaction.""" + + updated: datetime + """Required. + + Output only. The time at which the response was last updated in ISO 8601 format + (YYYY-MM-DDThh:mm:ssZ). + """ + + agent: Union[str, Literal["deep-research-pro-preview-12-2025"], None] = None + """The name of the `Agent` used for generating the interaction.""" + + agent_config: Optional[AgentConfig] = None + """Configuration parameters for the agent interaction.""" + + input: Optional[Input] = None + """The input for the interaction.""" + + model: Optional[Model] = None + """The name of the `Model` used for generating the interaction.""" + + outputs: Optional[List[Content]] = None + """Output only. Responses from the model.""" + + previous_interaction_id: Optional[str] = None + """The ID of the previous interaction, if any.""" + + response_format: Optional[object] = None + """ + Enforces that the generated response is a JSON object that complies with the + JSON schema specified in this field. + """ + + response_mime_type: Optional[str] = None + """The mime type of the response. This is required if response_format is set.""" + + response_modalities: Optional[List[Literal["text", "image", "audio", "video", "document"]]] = None + """The requested modalities of the response (TEXT, IMAGE, AUDIO).""" + + role: Optional[str] = None + """Output only. The role of the interaction.""" + + service_tier: Optional[Literal["flex", "standard", "priority"]] = None + """The service tier for the interaction.""" + + system_instruction: Optional[str] = None + """System instruction for the interaction.""" + + tools: Optional[List[Tool]] = None + """A list of tool declarations the model may call during interaction.""" + + usage: Optional[Usage] = None + """Output only. Statistics on the interaction request's token usage.""" + + webhook_config: Optional[WebhookConfig] = None + """Optional. + + Webhook configuration for receiving notifications when the interaction + completes. + """ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/interaction_complete_event.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/interaction_complete_event.py new file mode 100644 index 0000000000000000000000000000000000000000..493e2b96fbdf6bd90b7c113952f49daea3d70072 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/interaction_complete_event.py @@ -0,0 +1,40 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .._models import BaseModel +from .interaction import Interaction + +__all__ = ["InteractionCompleteEvent"] + + +class InteractionCompleteEvent(BaseModel): + event_type: Literal["interaction.complete"] + + interaction: Interaction + """Required. + + The completed interaction with empty outputs to reduce the payload size. Use the + preceding ContentDelta events for the actual output. + """ + + event_id: Optional[str] = None + """ + The event_id token to be used to resume the interaction stream, from this event. + """ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/interaction_create_params.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/interaction_create_params.py new file mode 100644 index 0000000000000000000000000000000000000000..61a1f2aa42fbf5ac70d69002f163800bdc1ec144 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/interaction_create_params.py @@ -0,0 +1,219 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Union, Iterable +from typing_extensions import Literal, Required, TypeAlias, TypedDict + +from .tool_param import ToolParam +from .turn_param import TurnParam +from .model_param import ModelParam +from .content_param import ContentParam +from .text_content_param import TextContentParam +from .audio_content_param import AudioContentParam +from .image_content_param import ImageContentParam +from .video_content_param import VideoContentParam +from .webhook_config_param import WebhookConfigParam +from .thought_content_param import ThoughtContentParam +from .document_content_param import DocumentContentParam +from .generation_config_param import GenerationConfigParam +from .dynamic_agent_config_param import DynamicAgentConfigParam +from .function_call_content_param import FunctionCallContentParam +from .function_result_content_param import FunctionResultContentParam +from .file_search_call_content_param import FileSearchCallContentParam +from .google_maps_call_content_param import GoogleMapsCallContentParam +from .url_context_call_content_param import URLContextCallContentParam +from .deep_research_agent_config_param import DeepResearchAgentConfigParam +from .file_search_result_content_param import FileSearchResultContentParam +from .google_maps_result_content_param import GoogleMapsResultContentParam +from .google_search_call_content_param import GoogleSearchCallContentParam +from .url_context_result_content_param import URLContextResultContentParam +from .code_execution_call_content_param import CodeExecutionCallContentParam +from .google_search_result_content_param import GoogleSearchResultContentParam +from .mcp_server_tool_call_content_param import MCPServerToolCallContentParam +from .code_execution_result_content_param import CodeExecutionResultContentParam +from .mcp_server_tool_result_content_param import MCPServerToolResultContentParam + +__all__ = [ + "BaseCreateModelInteractionParams", + "Input", + "BaseCreateAgentInteractionParams", + "AgentConfig", + "CreateModelInteractionParamsNonStreaming", + "CreateModelInteractionParamsStreaming", + "CreateAgentInteractionParamsNonStreaming", + "CreateAgentInteractionParamsStreaming", +] + + +class BaseCreateModelInteractionParams(TypedDict, total=False): + api_version: str + + input: Required[Input] + """The input for the interaction.""" + + model: Required[ModelParam] + """The name of the `Model` used for generating the interaction.""" + + background: bool + """Input only. Whether to run the model interaction in the background.""" + + generation_config: GenerationConfigParam + """Input only. Configuration parameters for the model interaction.""" + + previous_interaction_id: str + """The ID of the previous interaction, if any.""" + + response_format: object + """ + Enforces that the generated response is a JSON object that complies with the + JSON schema specified in this field. + """ + + response_mime_type: str + """The mime type of the response. This is required if response_format is set.""" + + response_modalities: List[Literal["text", "image", "audio", "video", "document"]] + """The requested modalities of the response (TEXT, IMAGE, AUDIO).""" + + service_tier: Literal["flex", "standard", "priority"] + """The service tier for the interaction.""" + + store: bool + """Input only. Whether to store the response and request for later retrieval.""" + + system_instruction: str + """System instruction for the interaction.""" + + tools: Iterable[ToolParam] + """A list of tool declarations the model may call during interaction.""" + + webhook_config: WebhookConfigParam + """Optional. + + Webhook configuration for receiving notifications when the interaction + completes. + """ + + +Input: TypeAlias = Union[ + Iterable[ContentParam], + str, + Iterable[TurnParam], + TextContentParam, + ImageContentParam, + AudioContentParam, + DocumentContentParam, + VideoContentParam, + ThoughtContentParam, + FunctionCallContentParam, + CodeExecutionCallContentParam, + URLContextCallContentParam, + MCPServerToolCallContentParam, + GoogleSearchCallContentParam, + FileSearchCallContentParam, + GoogleMapsCallContentParam, + FunctionResultContentParam, + CodeExecutionResultContentParam, + URLContextResultContentParam, + GoogleSearchResultContentParam, + MCPServerToolResultContentParam, + FileSearchResultContentParam, + GoogleMapsResultContentParam, +] + + +class BaseCreateAgentInteractionParams(TypedDict, total=False): + api_version: str + + agent: Required[Union[str, Literal["deep-research-pro-preview-12-2025"]]] + """The name of the `Agent` used for generating the interaction.""" + + input: Required[Input] + """The input for the interaction.""" + + agent_config: AgentConfig + """Configuration parameters for the agent interaction.""" + + background: bool + """Input only. Whether to run the model interaction in the background.""" + + previous_interaction_id: str + """The ID of the previous interaction, if any.""" + + response_format: object + """ + Enforces that the generated response is a JSON object that complies with the + JSON schema specified in this field. + """ + + response_mime_type: str + """The mime type of the response. This is required if response_format is set.""" + + response_modalities: List[Literal["text", "image", "audio", "video", "document"]] + """The requested modalities of the response (TEXT, IMAGE, AUDIO).""" + + service_tier: Literal["flex", "standard", "priority"] + """The service tier for the interaction.""" + + store: bool + """Input only. Whether to store the response and request for later retrieval.""" + + system_instruction: str + """System instruction for the interaction.""" + + tools: Iterable[ToolParam] + """A list of tool declarations the model may call during interaction.""" + + webhook_config: WebhookConfigParam + """Optional. + + Webhook configuration for receiving notifications when the interaction + completes. + """ + + +AgentConfig: TypeAlias = Union[DynamicAgentConfigParam, DeepResearchAgentConfigParam] + + +class CreateModelInteractionParamsNonStreaming(BaseCreateModelInteractionParams, total=False): + stream: Literal[False] + """Input only. Whether the interaction will be streamed.""" + + +class CreateModelInteractionParamsStreaming(BaseCreateModelInteractionParams): + stream: Required[Literal[True]] + """Input only. Whether the interaction will be streamed.""" + + +class CreateAgentInteractionParamsNonStreaming(BaseCreateAgentInteractionParams, total=False): + stream: Literal[False] + """Input only. Whether the interaction will be streamed.""" + + +class CreateAgentInteractionParamsStreaming(BaseCreateAgentInteractionParams): + stream: Required[Literal[True]] + """Input only. Whether the interaction will be streamed.""" + + +InteractionCreateParams = Union[ + CreateModelInteractionParamsNonStreaming, + CreateModelInteractionParamsStreaming, + CreateAgentInteractionParamsNonStreaming, + CreateAgentInteractionParamsStreaming, +] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/interaction_get_params.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/interaction_get_params.py new file mode 100644 index 0000000000000000000000000000000000000000..d3802bf76bf1b7fd6cf0dfef41a858099c2e232b --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/interaction_get_params.py @@ -0,0 +1,50 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["InteractionGetParamsBase", "InteractionGetParamsNonStreaming", "InteractionGetParamsStreaming"] + + +class InteractionGetParamsBase(TypedDict, total=False): + api_version: str + + include_input: bool + """If set to true, includes the input in the response.""" + + last_event_id: str + """Optional. + + If set, resumes the interaction stream from the next chunk after the event + marked by the event id. Can only be used if `stream` is true. + """ + + +class InteractionGetParamsNonStreaming(InteractionGetParamsBase, total=False): + stream: Literal[False] + """If set to true, the generated content will be streamed incrementally.""" + + +class InteractionGetParamsStreaming(InteractionGetParamsBase): + stream: Required[Literal[True]] + """If set to true, the generated content will be streamed incrementally.""" + + +InteractionGetParams = Union[InteractionGetParamsNonStreaming, InteractionGetParamsStreaming] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/interaction_sse_event.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/interaction_sse_event.py new file mode 100644 index 0000000000000000000000000000000000000000..0eee49201fae5a1c872b1711300a1bc737e1bb46 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/interaction_sse_event.py @@ -0,0 +1,43 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Annotated, TypeAlias + +from .._utils import PropertyInfo +from .error_event import ErrorEvent +from .content_stop import ContentStop +from .content_delta import ContentDelta +from .content_start import ContentStart +from .interaction_start_event import InteractionStartEvent +from .interaction_status_update import InteractionStatusUpdate +from .interaction_complete_event import InteractionCompleteEvent + +__all__ = ["InteractionSSEEvent"] + +InteractionSSEEvent: TypeAlias = Annotated[ + Union[ + InteractionStartEvent, + InteractionCompleteEvent, + InteractionStatusUpdate, + ContentStart, + ContentDelta, + ContentStop, + ErrorEvent, + ], + PropertyInfo(discriminator="event_type"), +] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/interaction_start_event.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/interaction_start_event.py new file mode 100644 index 0000000000000000000000000000000000000000..1202ec849fcda61a55ea120a0c153cf6d5eafb6c --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/interaction_start_event.py @@ -0,0 +1,36 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .._models import BaseModel +from .interaction import Interaction + +__all__ = ["InteractionStartEvent"] + + +class InteractionStartEvent(BaseModel): + event_type: Literal["interaction.start"] + + interaction: Interaction + """The Interaction resource.""" + + event_id: Optional[str] = None + """ + The event_id token to be used to resume the interaction stream, from this event. + """ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/interaction_status_update.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/interaction_status_update.py new file mode 100644 index 0000000000000000000000000000000000000000..b4c571ab3d41792abf456b43f256cefb41ff0411 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/interaction_status_update.py @@ -0,0 +1,36 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["InteractionStatusUpdate"] + + +class InteractionStatusUpdate(BaseModel): + event_type: Literal["interaction.status_update"] + + interaction_id: str + + status: Literal["in_progress", "requires_action", "completed", "failed", "cancelled", "incomplete"] + + event_id: Optional[str] = None + """ + The event_id token to be used to resume the interaction stream, from this event. + """ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/mcp_server_tool_call_content.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/mcp_server_tool_call_content.py new file mode 100644 index 0000000000000000000000000000000000000000..117564d9d9f3ea0f038374e1e62bb3753f4098d6 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/mcp_server_tool_call_content.py @@ -0,0 +1,44 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, Optional +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["MCPServerToolCallContent"] + + +class MCPServerToolCallContent(BaseModel): + """MCPServer tool call content.""" + + id: str + """Required. A unique ID for this specific tool call.""" + + arguments: Dict[str, object] + """Required. The JSON object of arguments for the function.""" + + name: str + """Required. The name of the tool which was called.""" + + server_name: str + """Required. The name of the used MCP server.""" + + type: Literal["mcp_server_tool_call"] + + signature: Optional[str] = None + """A signature hash for backend validation.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/mcp_server_tool_call_content_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/mcp_server_tool_call_content_param.py new file mode 100644 index 0000000000000000000000000000000000000000..31f40c9dde0cccb570e96ef08446b1b8104b0fce --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/mcp_server_tool_call_content_param.py @@ -0,0 +1,51 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, Union +from typing_extensions import Literal, Required, Annotated, TypedDict + +from .._types import Base64FileInput +from .._utils import PropertyInfo +from .._models import set_pydantic_config + +__all__ = ["MCPServerToolCallContentParam"] + + +class MCPServerToolCallContentParam(TypedDict, total=False): + """MCPServer tool call content.""" + + id: Required[str] + """Required. A unique ID for this specific tool call.""" + + arguments: Required[Dict[str, object]] + """Required. The JSON object of arguments for the function.""" + + name: Required[str] + """Required. The name of the tool which was called.""" + + server_name: Required[str] + """Required. The name of the used MCP server.""" + + type: Required[Literal["mcp_server_tool_call"]] + + signature: Annotated[Union[str, Base64FileInput], PropertyInfo(format="base64")] + """A signature hash for backend validation.""" + + +set_pydantic_config(MCPServerToolCallContentParam, {"arbitrary_types_allowed": True}) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/mcp_server_tool_result_content.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/mcp_server_tool_result_content.py new file mode 100644 index 0000000000000000000000000000000000000000..70bfa9d86c4241f3b365d19ceb0c797cd3c9d466 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/mcp_server_tool_result_content.py @@ -0,0 +1,51 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union, Optional +from typing_extensions import Literal, Annotated, TypeAlias + +from .._utils import PropertyInfo +from .._models import BaseModel +from .text_content import TextContent +from .image_content import ImageContent + +__all__ = ["MCPServerToolResultContent", "ResultFunctionResultSubcontentList"] + +ResultFunctionResultSubcontentList: TypeAlias = Annotated[ + Union[TextContent, ImageContent], PropertyInfo(discriminator="type") +] + + +class MCPServerToolResultContent(BaseModel): + """MCPServer tool result content.""" + + call_id: str + """Required. ID to match the ID from the function call block.""" + + result: Union[List[ResultFunctionResultSubcontentList], str, object] + """The output from the MCP server call. Can be simple text or rich content.""" + + type: Literal["mcp_server_tool_result"] + + name: Optional[str] = None + """Name of the tool which is called for this specific tool call.""" + + server_name: Optional[str] = None + """The name of the used MCP server.""" + + signature: Optional[str] = None + """A signature hash for backend validation.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/mcp_server_tool_result_content_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/mcp_server_tool_result_content_param.py new file mode 100644 index 0000000000000000000000000000000000000000..d8838a847efdfed4c592e4efd93289e9fe27b680 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/mcp_server_tool_result_content_param.py @@ -0,0 +1,55 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Iterable +from typing_extensions import Literal, Required, Annotated, TypeAlias, TypedDict + +from .._types import Base64FileInput +from .._utils import PropertyInfo +from .._models import set_pydantic_config +from .text_content_param import TextContentParam +from .image_content_param import ImageContentParam + +__all__ = ["MCPServerToolResultContentParam", "ResultFunctionResultSubcontentList"] + +ResultFunctionResultSubcontentList: TypeAlias = Union[TextContentParam, ImageContentParam] + + +class MCPServerToolResultContentParam(TypedDict, total=False): + """MCPServer tool result content.""" + + call_id: Required[str] + """Required. ID to match the ID from the function call block.""" + + result: Required[Union[Iterable[ResultFunctionResultSubcontentList], str, object]] + """The output from the MCP server call. Can be simple text or rich content.""" + + type: Required[Literal["mcp_server_tool_result"]] + + name: str + """Name of the tool which is called for this specific tool call.""" + + server_name: str + """The name of the used MCP server.""" + + signature: Annotated[Union[str, Base64FileInput], PropertyInfo(format="base64")] + """A signature hash for backend validation.""" + + +set_pydantic_config(MCPServerToolResultContentParam, {"arbitrary_types_allowed": True}) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/model.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/model.py new file mode 100644 index 0000000000000000000000000000000000000000..32d9c018d4fbe53defec09bc844a8859103c98b2 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/model.py @@ -0,0 +1,45 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Literal, TypeAlias + +__all__ = ["Model"] + +Model: TypeAlias = Union[ + Literal[ + "gemini-2.5-computer-use-preview-10-2025", + "gemini-2.5-flash", + "gemini-2.5-flash-image", + "gemini-2.5-flash-lite", + "gemini-2.5-flash-lite-preview-09-2025", + "gemini-2.5-flash-native-audio-preview-12-2025", + "gemini-2.5-flash-preview-09-2025", + "gemini-2.5-flash-preview-tts", + "gemini-2.5-pro", + "gemini-2.5-pro-preview-tts", + "gemini-3-flash-preview", + "gemini-3-pro-image-preview", + "gemini-3-pro-preview", + "gemini-3.1-pro-preview", + "gemini-3.1-flash-image-preview", + "gemini-3.1-flash-lite-preview", + "lyria-3-clip-preview", + "lyria-3-pro-preview", + ], + str, +] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/model_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/model_param.py new file mode 100644 index 0000000000000000000000000000000000000000..ceabdd2c1d028fbc61423995275b9b2764d44dc1 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/model_param.py @@ -0,0 +1,47 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import Literal, TypeAlias + +__all__ = ["ModelParam"] + +ModelParam: TypeAlias = Union[ + Literal[ + "gemini-2.5-computer-use-preview-10-2025", + "gemini-2.5-flash", + "gemini-2.5-flash-image", + "gemini-2.5-flash-lite", + "gemini-2.5-flash-lite-preview-09-2025", + "gemini-2.5-flash-native-audio-preview-12-2025", + "gemini-2.5-flash-preview-09-2025", + "gemini-2.5-flash-preview-tts", + "gemini-2.5-pro", + "gemini-2.5-pro-preview-tts", + "gemini-3-flash-preview", + "gemini-3-pro-image-preview", + "gemini-3-pro-preview", + "gemini-3.1-pro-preview", + "gemini-3.1-flash-image-preview", + "gemini-3.1-flash-lite-preview", + "lyria-3-clip-preview", + "lyria-3-pro-preview", + ], + str, +] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/place_citation.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/place_citation.py new file mode 100644 index 0000000000000000000000000000000000000000..af65c0416116f2019a99eb9f2a363ef4261c4a0a --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/place_citation.py @@ -0,0 +1,69 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["PlaceCitation", "ReviewSnippet"] + + +class ReviewSnippet(BaseModel): + """ + Encapsulates a snippet of a user review that answers a question about + the features of a specific place in Google Maps. + """ + + review_id: Optional[str] = None + """The ID of the review snippet.""" + + title: Optional[str] = None + """Title of the review.""" + + url: Optional[str] = None + """A link that corresponds to the user review on Google Maps.""" + + +class PlaceCitation(BaseModel): + """A place citation annotation.""" + + type: Literal["place_citation"] + + end_index: Optional[int] = None + """End of the attributed segment, exclusive.""" + + name: Optional[str] = None + """Title of the place.""" + + place_id: Optional[str] = None + """The ID of the place, in `places/{place_id}` format.""" + + review_snippets: Optional[List[ReviewSnippet]] = None + """ + Snippets of reviews that are used to generate answers about the features of a + given place in Google Maps. + """ + + start_index: Optional[int] = None + """Start of segment of the response that is attributed to this source. + + Index indicates the start of the segment, measured in bytes. + """ + + url: Optional[str] = None + """URI reference of the place.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/place_citation_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/place_citation_param.py new file mode 100644 index 0000000000000000000000000000000000000000..78de5ed6004a6a02221ae15e5b709052c630e006 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/place_citation_param.py @@ -0,0 +1,69 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["PlaceCitationParam", "ReviewSnippet"] + + +class ReviewSnippet(TypedDict, total=False): + """ + Encapsulates a snippet of a user review that answers a question about + the features of a specific place in Google Maps. + """ + + review_id: str + """The ID of the review snippet.""" + + title: str + """Title of the review.""" + + url: str + """A link that corresponds to the user review on Google Maps.""" + + +class PlaceCitationParam(TypedDict, total=False): + """A place citation annotation.""" + + type: Required[Literal["place_citation"]] + + end_index: int + """End of the attributed segment, exclusive.""" + + name: str + """Title of the place.""" + + place_id: str + """The ID of the place, in `places/{place_id}` format.""" + + review_snippets: Iterable[ReviewSnippet] + """ + Snippets of reviews that are used to generate answers about the features of a + given place in Google Maps. + """ + + start_index: int + """Start of segment of the response that is attributed to this source. + + Index indicates the start of the segment, measured in bytes. + """ + + url: str + """URI reference of the place.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/signing_secret.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/signing_secret.py new file mode 100644 index 0000000000000000000000000000000000000000..81742069af0d50c92426b98e794cc2352f1e8883 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/signing_secret.py @@ -0,0 +1,33 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from datetime import datetime + +from .._models import BaseModel + +__all__ = ["SigningSecret"] + + +class SigningSecret(BaseModel): + """Represents a signing secret used to verify webhook payloads.""" + + expire_time: Optional[datetime] = None + """Output only. The expiration date of the signing secret.""" + + truncated_secret: Optional[str] = None + """Output only. The truncated version of the signing secret.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/speech_config.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/speech_config.py new file mode 100644 index 0000000000000000000000000000000000000000..5dca5abe2f2965f234c757eea1d188c9eaf8209a --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/speech_config.py @@ -0,0 +1,35 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from .._models import BaseModel + +__all__ = ["SpeechConfig"] + + +class SpeechConfig(BaseModel): + """The configuration for speech interaction.""" + + language: Optional[str] = None + """The language of the speech.""" + + speaker: Optional[str] = None + """The speaker's name, it should match the speaker name given in the prompt.""" + + voice: Optional[str] = None + """The voice of the speaker.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/speech_config_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/speech_config_param.py new file mode 100644 index 0000000000000000000000000000000000000000..972095125c9d8430ab1e9089f9d96f0f80c445f8 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/speech_config_param.py @@ -0,0 +1,35 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import TypedDict + +__all__ = ["SpeechConfigParam"] + + +class SpeechConfigParam(TypedDict, total=False): + """The configuration for speech interaction.""" + + language: str + """The language of the speech.""" + + speaker: str + """The speaker's name, it should match the speaker name given in the prompt.""" + + voice: str + """The voice of the speaker.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/text_content.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/text_content.py new file mode 100644 index 0000000000000000000000000000000000000000..b753059e66db5607c198ccd3afd11879f7897ee7 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/text_content.py @@ -0,0 +1,36 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional +from typing_extensions import Literal + +from .._models import BaseModel +from .annotation import Annotation + +__all__ = ["TextContent"] + + +class TextContent(BaseModel): + """A text content block.""" + + text: str + """Required. The text content.""" + + type: Literal["text"] + + annotations: Optional[List[Annotation]] = None + """Citation information for model-generated content.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/text_content_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/text_content_param.py new file mode 100644 index 0000000000000000000000000000000000000000..97eb9ebd77f39cba3a241cf229605f0c13232567 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/text_content_param.py @@ -0,0 +1,37 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable +from typing_extensions import Literal, Required, TypedDict + +from .annotation_param import AnnotationParam + +__all__ = ["TextContentParam"] + + +class TextContentParam(TypedDict, total=False): + """A text content block.""" + + text: Required[str] + """Required. The text content.""" + + type: Required[Literal["text"]] + + annotations: Iterable[AnnotationParam] + """Citation information for model-generated content.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/thinking_level.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/thinking_level.py new file mode 100644 index 0000000000000000000000000000000000000000..f824adb6cff6bed31663605a501c5fa03ec399aa --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/thinking_level.py @@ -0,0 +1,22 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal, TypeAlias + +__all__ = ["ThinkingLevel"] + +ThinkingLevel: TypeAlias = Literal["minimal", "low", "medium", "high"] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/thought_content.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/thought_content.py new file mode 100644 index 0000000000000000000000000000000000000000..d5c081f31646bf65c87ef3eb1dfd2da658854398 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/thought_content.py @@ -0,0 +1,40 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union, Optional +from typing_extensions import Literal, Annotated, TypeAlias + +from .._utils import PropertyInfo +from .._models import BaseModel +from .text_content import TextContent +from .image_content import ImageContent + +__all__ = ["ThoughtContent", "Summary"] + +Summary: TypeAlias = Annotated[Union[TextContent, ImageContent], PropertyInfo(discriminator="type")] + + +class ThoughtContent(BaseModel): + """A thought content block.""" + + type: Literal["thought"] + + signature: Optional[str] = None + """Signature to match the backend source to be part of the generation.""" + + summary: Optional[List[Summary]] = None + """A summary of the thought.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/thought_content_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/thought_content_param.py new file mode 100644 index 0000000000000000000000000000000000000000..275038d73b92a455acf5b4304a2fe213b3f070ed --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/thought_content_param.py @@ -0,0 +1,46 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Iterable +from typing_extensions import Literal, Required, Annotated, TypeAlias, TypedDict + +from .._types import Base64FileInput +from .._utils import PropertyInfo +from .._models import set_pydantic_config +from .text_content_param import TextContentParam +from .image_content_param import ImageContentParam + +__all__ = ["ThoughtContentParam", "Summary"] + +Summary: TypeAlias = Union[TextContentParam, ImageContentParam] + + +class ThoughtContentParam(TypedDict, total=False): + """A thought content block.""" + + type: Required[Literal["thought"]] + + signature: Annotated[Union[str, Base64FileInput], PropertyInfo(format="base64")] + """Signature to match the backend source to be part of the generation.""" + + summary: Iterable[Summary] + """A summary of the thought.""" + + +set_pydantic_config(ThoughtContentParam, {"arbitrary_types_allowed": True}) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/tool.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..8820e539d4db7ff97d2b518fbf1e551f6374a6b6 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/tool.py @@ -0,0 +1,151 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, List, Union, Optional +from typing_extensions import Literal, Annotated, TypeAlias + +from pydantic import Field as FieldInfo + +from .._utils import PropertyInfo +from .._models import BaseModel +from .function import Function +from .allowed_tools import AllowedTools + +__all__ = [ + "Tool", + "CodeExecution", + "URLContext", + "ComputerUse", + "MCPServer", + "GoogleSearch", + "FileSearch", + "GoogleMaps", + "Retrieval", + "RetrievalVertexAISearchConfig", +] + + +class CodeExecution(BaseModel): + """A tool that can be used by the model to execute code.""" + + type: Literal["code_execution"] + + +class URLContext(BaseModel): + """A tool that can be used by the model to fetch URL context.""" + + type: Literal["url_context"] + + +class ComputerUse(BaseModel): + """A tool that can be used by the model to interact with the computer.""" + + type: Literal["computer_use"] + + environment: Optional[Literal["browser"]] = None + """The environment being operated.""" + + excluded_predefined_functions: Optional[List[str]] = FieldInfo(alias="excludedPredefinedFunctions", default=None) + """The list of predefined functions that are excluded from the model call.""" + + +class MCPServer(BaseModel): + """A MCPServer is a server that can be called by the model to perform actions.""" + + type: Literal["mcp_server"] + + allowed_tools: Optional[List[AllowedTools]] = None + """The allowed tools.""" + + headers: Optional[Dict[str, str]] = None + """Optional: Fields for authentication headers, timeouts, etc., if needed.""" + + name: Optional[str] = None + """The name of the MCPServer.""" + + url: Optional[str] = None + """The full URL for the MCPServer endpoint. Example: "https://api.example.com/mcp" """ + + +class GoogleSearch(BaseModel): + """A tool that can be used by the model to search Google.""" + + type: Literal["google_search"] + + search_types: Optional[List[Literal["web_search", "image_search", "enterprise_web_search"]]] = None + """The types of search grounding to enable.""" + + +class FileSearch(BaseModel): + """A tool that can be used by the model to search files.""" + + type: Literal["file_search"] + + file_search_store_names: Optional[List[str]] = None + """The file search store names to search.""" + + metadata_filter: Optional[str] = None + """Metadata filter to apply to the semantic retrieval documents and chunks.""" + + top_k: Optional[int] = None + """The number of semantic retrieval chunks to retrieve.""" + + +class GoogleMaps(BaseModel): + """A tool that can be used by the model to call Google Maps.""" + + type: Literal["google_maps"] + + enable_widget: Optional[bool] = None + """ + Whether to return a widget context token in the tool call result of the + response. + """ + + latitude: Optional[float] = None + """The latitude of the user's location.""" + + longitude: Optional[float] = None + """The longitude of the user's location.""" + + +class RetrievalVertexAISearchConfig(BaseModel): + """Used to specify configuration for VertexAISearch.""" + + datastores: Optional[List[str]] = None + """Optional. Used to specify Vertex AI Search datastores.""" + + engine: Optional[str] = None + """Optional. Used to specify Vertex AI Search engine.""" + + +class Retrieval(BaseModel): + """A tool that can be used by the model to retrieve files.""" + + type: Literal["retrieval"] + + retrieval_types: Optional[List[Literal["vertex_ai_search"]]] = None + """The types of file retrieval to enable.""" + + vertex_ai_search_config: Optional[RetrievalVertexAISearchConfig] = None + """Used to specify configuration for VertexAISearch.""" + + +Tool: TypeAlias = Annotated[ + Union[Function, CodeExecution, URLContext, ComputerUse, MCPServer, GoogleSearch, FileSearch, GoogleMaps, Retrieval], + PropertyInfo(discriminator="type"), +] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/tool_choice_config.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/tool_choice_config.py new file mode 100644 index 0000000000000000000000000000000000000000..19305e7db2920f1a5d5d1127438380f50840453e --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/tool_choice_config.py @@ -0,0 +1,30 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from .._models import BaseModel +from .allowed_tools import AllowedTools + +__all__ = ["ToolChoiceConfig"] + + +class ToolChoiceConfig(BaseModel): + """The tool choice configuration containing allowed tools.""" + + allowed_tools: Optional[AllowedTools] = None + """The allowed tools.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/tool_choice_config_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/tool_choice_config_param.py new file mode 100644 index 0000000000000000000000000000000000000000..187f57d5c510a25da336d5982fdf74ba3cc42325 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/tool_choice_config_param.py @@ -0,0 +1,31 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import TypedDict + +from .allowed_tools_param import AllowedToolsParam + +__all__ = ["ToolChoiceConfigParam"] + + +class ToolChoiceConfigParam(TypedDict, total=False): + """The tool choice configuration containing allowed tools.""" + + allowed_tools: AllowedToolsParam + """The allowed tools.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/tool_choice_type.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/tool_choice_type.py new file mode 100644 index 0000000000000000000000000000000000000000..aa4b8849cadd565ef1f61ba2b008782ede09f1e9 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/tool_choice_type.py @@ -0,0 +1,22 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal, TypeAlias + +__all__ = ["ToolChoiceType"] + +ToolChoiceType: TypeAlias = Literal["auto", "any", "none", "validated"] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/tool_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/tool_param.py new file mode 100644 index 0000000000000000000000000000000000000000..169752327d4fc4727f95518711d66e77f9b958d8 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/tool_param.py @@ -0,0 +1,150 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, List, Union, Iterable +from typing_extensions import Literal, Required, Annotated, TypeAlias, TypedDict + +from .._types import SequenceNotStr +from .._utils import PropertyInfo +from .function_param import FunctionParam +from .allowed_tools_param import AllowedToolsParam + +__all__ = [ + "ToolParam", + "CodeExecution", + "URLContext", + "ComputerUse", + "MCPServer", + "GoogleSearch", + "FileSearch", + "GoogleMaps", + "Retrieval", + "RetrievalVertexAISearchConfig", +] + + +class CodeExecution(TypedDict, total=False): + """A tool that can be used by the model to execute code.""" + + type: Required[Literal["code_execution"]] + + +class URLContext(TypedDict, total=False): + """A tool that can be used by the model to fetch URL context.""" + + type: Required[Literal["url_context"]] + + +class ComputerUse(TypedDict, total=False): + """A tool that can be used by the model to interact with the computer.""" + + type: Required[Literal["computer_use"]] + + environment: Literal["browser"] + """The environment being operated.""" + + excluded_predefined_functions: Annotated[SequenceNotStr[str], PropertyInfo(alias="excludedPredefinedFunctions")] + """The list of predefined functions that are excluded from the model call.""" + + +class MCPServer(TypedDict, total=False): + """A MCPServer is a server that can be called by the model to perform actions.""" + + type: Required[Literal["mcp_server"]] + + allowed_tools: Iterable[AllowedToolsParam] + """The allowed tools.""" + + headers: Dict[str, str] + """Optional: Fields for authentication headers, timeouts, etc., if needed.""" + + name: str + """The name of the MCPServer.""" + + url: str + """The full URL for the MCPServer endpoint. Example: "https://api.example.com/mcp" """ + + +class GoogleSearch(TypedDict, total=False): + """A tool that can be used by the model to search Google.""" + + type: Required[Literal["google_search"]] + + search_types: List[Literal["web_search", "image_search", "enterprise_web_search"]] + """The types of search grounding to enable.""" + + +class FileSearch(TypedDict, total=False): + """A tool that can be used by the model to search files.""" + + type: Required[Literal["file_search"]] + + file_search_store_names: SequenceNotStr[str] + """The file search store names to search.""" + + metadata_filter: str + """Metadata filter to apply to the semantic retrieval documents and chunks.""" + + top_k: int + """The number of semantic retrieval chunks to retrieve.""" + + +class GoogleMaps(TypedDict, total=False): + """A tool that can be used by the model to call Google Maps.""" + + type: Required[Literal["google_maps"]] + + enable_widget: bool + """ + Whether to return a widget context token in the tool call result of the + response. + """ + + latitude: float + """The latitude of the user's location.""" + + longitude: float + """The longitude of the user's location.""" + + +class RetrievalVertexAISearchConfig(TypedDict, total=False): + """Used to specify configuration for VertexAISearch.""" + + datastores: SequenceNotStr[str] + """Optional. Used to specify Vertex AI Search datastores.""" + + engine: str + """Optional. Used to specify Vertex AI Search engine.""" + + +class Retrieval(TypedDict, total=False): + """A tool that can be used by the model to retrieve files.""" + + type: Required[Literal["retrieval"]] + + retrieval_types: List[Literal["vertex_ai_search"]] + """The types of file retrieval to enable.""" + + vertex_ai_search_config: RetrievalVertexAISearchConfig + """Used to specify configuration for VertexAISearch.""" + + +ToolParam: TypeAlias = Union[ + FunctionParam, CodeExecution, URLContext, ComputerUse, MCPServer, GoogleSearch, FileSearch, GoogleMaps, Retrieval +] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/turn.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/turn.py new file mode 100644 index 0000000000000000000000000000000000000000..6c28f0e4818e4654125d8a58e4b2c979259c300f --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/turn.py @@ -0,0 +1,30 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union, Optional + +from .content import Content +from .._models import BaseModel + +__all__ = ["Turn"] + + +class Turn(BaseModel): + content: Union[List[Content], str, None] = None + + role: Optional[str] = None + """The originator of this turn. Must be user for input or model for model output.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/turn_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/turn_param.py new file mode 100644 index 0000000000000000000000000000000000000000..cbbe4c456e285b88568539b637214483834f54ba --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/turn_param.py @@ -0,0 +1,32 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Iterable +from typing_extensions import TypedDict + +from .content_param import ContentParam + +__all__ = ["TurnParam"] + + +class TurnParam(TypedDict, total=False): + content: Union[Iterable[ContentParam], str] + + role: str + """The originator of this turn. Must be user for input or model for model output.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/url_citation.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/url_citation.py new file mode 100644 index 0000000000000000000000000000000000000000..818ce5bf555d6be60541187876ec3d711be33116 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/url_citation.py @@ -0,0 +1,44 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["URLCitation"] + + +class URLCitation(BaseModel): + """A URL citation annotation.""" + + type: Literal["url_citation"] + + end_index: Optional[int] = None + """End of the attributed segment, exclusive.""" + + start_index: Optional[int] = None + """Start of segment of the response that is attributed to this source. + + Index indicates the start of the segment, measured in bytes. + """ + + title: Optional[str] = None + """The title of the URL.""" + + url: Optional[str] = None + """The URL.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/url_citation_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/url_citation_param.py new file mode 100644 index 0000000000000000000000000000000000000000..1f57b573688948b72db602c438a579ac634b6b4b --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/url_citation_param.py @@ -0,0 +1,43 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["URLCitationParam"] + + +class URLCitationParam(TypedDict, total=False): + """A URL citation annotation.""" + + type: Required[Literal["url_citation"]] + + end_index: int + """End of the attributed segment, exclusive.""" + + start_index: int + """Start of segment of the response that is attributed to this source. + + Index indicates the start of the segment, measured in bytes. + """ + + title: str + """The title of the URL.""" + + url: str + """The URL.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/url_context_call_arguments.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/url_context_call_arguments.py new file mode 100644 index 0000000000000000000000000000000000000000..f1a1aca3924a22de1a0c6df68d0911d363fbf8c8 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/url_context_call_arguments.py @@ -0,0 +1,29 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional + +from .._models import BaseModel + +__all__ = ["URLContextCallArguments"] + + +class URLContextCallArguments(BaseModel): + """The arguments to pass to the URL context.""" + + urls: Optional[List[str]] = None + """The URLs to fetch.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/url_context_call_arguments_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/url_context_call_arguments_param.py new file mode 100644 index 0000000000000000000000000000000000000000..66263776d56cb49fa4d2aae3bf6889a8bd5d4380 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/url_context_call_arguments_param.py @@ -0,0 +1,31 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import TypedDict + +from .._types import SequenceNotStr + +__all__ = ["URLContextCallArgumentsParam"] + + +class URLContextCallArgumentsParam(TypedDict, total=False): + """The arguments to pass to the URL context.""" + + urls: SequenceNotStr[str] + """The URLs to fetch.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/url_context_call_content.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/url_context_call_content.py new file mode 100644 index 0000000000000000000000000000000000000000..e049b7a0d800f7d66191be5702296952ae810fdc --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/url_context_call_content.py @@ -0,0 +1,39 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .._models import BaseModel +from .url_context_call_arguments import URLContextCallArguments + +__all__ = ["URLContextCallContent"] + + +class URLContextCallContent(BaseModel): + """URL context content.""" + + id: str + """Required. A unique ID for this specific tool call.""" + + arguments: URLContextCallArguments + """Required. The arguments to pass to the URL context.""" + + type: Literal["url_context_call"] + + signature: Optional[str] = None + """A signature hash for backend validation.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/url_context_call_content_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/url_context_call_content_param.py new file mode 100644 index 0000000000000000000000000000000000000000..58cdc7e4691f7c865accb199ed47aabbcaec68aa --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/url_context_call_content_param.py @@ -0,0 +1,46 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import Literal, Required, Annotated, TypedDict + +from .._types import Base64FileInput +from .._utils import PropertyInfo +from .._models import set_pydantic_config +from .url_context_call_arguments_param import URLContextCallArgumentsParam + +__all__ = ["URLContextCallContentParam"] + + +class URLContextCallContentParam(TypedDict, total=False): + """URL context content.""" + + id: Required[str] + """Required. A unique ID for this specific tool call.""" + + arguments: Required[URLContextCallArgumentsParam] + """Required. The arguments to pass to the URL context.""" + + type: Required[Literal["url_context_call"]] + + signature: Annotated[Union[str, Base64FileInput], PropertyInfo(format="base64")] + """A signature hash for backend validation.""" + + +set_pydantic_config(URLContextCallContentParam, {"arbitrary_types_allowed": True}) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/url_context_result.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/url_context_result.py new file mode 100644 index 0000000000000000000000000000000000000000..996f43c566623792ee5aeb53dae863db4e9daa50 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/url_context_result.py @@ -0,0 +1,33 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["URLContextResult"] + + +class URLContextResult(BaseModel): + """The result of the URL context.""" + + status: Optional[Literal["success", "error", "paywall", "unsafe"]] = None + """The status of the URL retrieval.""" + + url: Optional[str] = None + """The URL that was fetched.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/url_context_result_content.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/url_context_result_content.py new file mode 100644 index 0000000000000000000000000000000000000000..1e7788133c9be4e8cc705c5cfb18862303af16a2 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/url_context_result_content.py @@ -0,0 +1,42 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional +from typing_extensions import Literal + +from .._models import BaseModel +from .url_context_result import URLContextResult + +__all__ = ["URLContextResultContent"] + + +class URLContextResultContent(BaseModel): + """URL context result content.""" + + call_id: str + """Required. ID to match the ID from the function call block.""" + + result: List[URLContextResult] + """Required. The results of the URL context.""" + + type: Literal["url_context_result"] + + is_error: Optional[bool] = None + """Whether the URL context resulted in an error.""" + + signature: Optional[str] = None + """A signature hash for backend validation.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/url_context_result_content_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/url_context_result_content_param.py new file mode 100644 index 0000000000000000000000000000000000000000..1bd95243aca441574a141acb51e79b429f1500b3 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/url_context_result_content_param.py @@ -0,0 +1,49 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Iterable +from typing_extensions import Literal, Required, Annotated, TypedDict + +from .._types import Base64FileInput +from .._utils import PropertyInfo +from .._models import set_pydantic_config +from .url_context_result_param import URLContextResultParam + +__all__ = ["URLContextResultContentParam"] + + +class URLContextResultContentParam(TypedDict, total=False): + """URL context result content.""" + + call_id: Required[str] + """Required. ID to match the ID from the function call block.""" + + result: Required[Iterable[URLContextResultParam]] + """Required. The results of the URL context.""" + + type: Required[Literal["url_context_result"]] + + is_error: bool + """Whether the URL context resulted in an error.""" + + signature: Annotated[Union[str, Base64FileInput], PropertyInfo(format="base64")] + """A signature hash for backend validation.""" + + +set_pydantic_config(URLContextResultContentParam, {"arbitrary_types_allowed": True}) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/url_context_result_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/url_context_result_param.py new file mode 100644 index 0000000000000000000000000000000000000000..67a3df9e3bb82c68bb278867262d3d7708a0dcc5 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/url_context_result_param.py @@ -0,0 +1,32 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, TypedDict + +__all__ = ["URLContextResultParam"] + + +class URLContextResultParam(TypedDict, total=False): + """The result of the URL context.""" + + status: Literal["success", "error", "paywall", "unsafe"] + """The status of the URL retrieval.""" + + url: str + """The URL that was fetched.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/usage.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/usage.py new file mode 100644 index 0000000000000000000000000000000000000000..61cf506a6f5c7094f3b194f8c8f05a6ab809114e --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/usage.py @@ -0,0 +1,106 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = [ + "Usage", + "CachedTokensByModality", + "InputTokensByModality", + "OutputTokensByModality", + "ToolUseTokensByModality", +] + + +class CachedTokensByModality(BaseModel): + """The token count for a single response modality.""" + + modality: Optional[Literal["text", "image", "audio", "video", "document"]] = None + """The modality associated with the token count.""" + + tokens: Optional[int] = None + """Number of tokens for the modality.""" + + +class InputTokensByModality(BaseModel): + """The token count for a single response modality.""" + + modality: Optional[Literal["text", "image", "audio", "video", "document"]] = None + """The modality associated with the token count.""" + + tokens: Optional[int] = None + """Number of tokens for the modality.""" + + +class OutputTokensByModality(BaseModel): + """The token count for a single response modality.""" + + modality: Optional[Literal["text", "image", "audio", "video", "document"]] = None + """The modality associated with the token count.""" + + tokens: Optional[int] = None + """Number of tokens for the modality.""" + + +class ToolUseTokensByModality(BaseModel): + """The token count for a single response modality.""" + + modality: Optional[Literal["text", "image", "audio", "video", "document"]] = None + """The modality associated with the token count.""" + + tokens: Optional[int] = None + """Number of tokens for the modality.""" + + +class Usage(BaseModel): + """Statistics on the interaction request's token usage.""" + + cached_tokens_by_modality: Optional[List[CachedTokensByModality]] = None + """A breakdown of cached token usage by modality.""" + + input_tokens_by_modality: Optional[List[InputTokensByModality]] = None + """A breakdown of input token usage by modality.""" + + output_tokens_by_modality: Optional[List[OutputTokensByModality]] = None + """A breakdown of output token usage by modality.""" + + tool_use_tokens_by_modality: Optional[List[ToolUseTokensByModality]] = None + """A breakdown of tool-use token usage by modality.""" + + total_cached_tokens: Optional[int] = None + """Number of tokens in the cached part of the prompt (the cached content).""" + + total_input_tokens: Optional[int] = None + """Number of tokens in the prompt (context).""" + + total_output_tokens: Optional[int] = None + """Total number of tokens across all the generated responses.""" + + total_thought_tokens: Optional[int] = None + """Number of tokens of thoughts for thinking models.""" + + total_tokens: Optional[int] = None + """ + Total token count for the interaction request (prompt + responses + other + internal tokens). + """ + + total_tool_use_tokens: Optional[int] = None + """Number of tokens present in tool-use prompt(s).""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/usage_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/usage_param.py new file mode 100644 index 0000000000000000000000000000000000000000..b2806aae5bad300104538b52478b8d02d1490cc5 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/usage_param.py @@ -0,0 +1,106 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable +from typing_extensions import Literal, TypedDict + +__all__ = [ + "UsageParam", + "CachedTokensByModality", + "InputTokensByModality", + "OutputTokensByModality", + "ToolUseTokensByModality", +] + + +class CachedTokensByModality(TypedDict, total=False): + """The token count for a single response modality.""" + + modality: Literal["text", "image", "audio", "video", "document"] + """The modality associated with the token count.""" + + tokens: int + """Number of tokens for the modality.""" + + +class InputTokensByModality(TypedDict, total=False): + """The token count for a single response modality.""" + + modality: Literal["text", "image", "audio", "video", "document"] + """The modality associated with the token count.""" + + tokens: int + """Number of tokens for the modality.""" + + +class OutputTokensByModality(TypedDict, total=False): + """The token count for a single response modality.""" + + modality: Literal["text", "image", "audio", "video", "document"] + """The modality associated with the token count.""" + + tokens: int + """Number of tokens for the modality.""" + + +class ToolUseTokensByModality(TypedDict, total=False): + """The token count for a single response modality.""" + + modality: Literal["text", "image", "audio", "video", "document"] + """The modality associated with the token count.""" + + tokens: int + """Number of tokens for the modality.""" + + +class UsageParam(TypedDict, total=False): + """Statistics on the interaction request's token usage.""" + + cached_tokens_by_modality: Iterable[CachedTokensByModality] + """A breakdown of cached token usage by modality.""" + + input_tokens_by_modality: Iterable[InputTokensByModality] + """A breakdown of input token usage by modality.""" + + output_tokens_by_modality: Iterable[OutputTokensByModality] + """A breakdown of output token usage by modality.""" + + tool_use_tokens_by_modality: Iterable[ToolUseTokensByModality] + """A breakdown of tool-use token usage by modality.""" + + total_cached_tokens: int + """Number of tokens in the cached part of the prompt (the cached content).""" + + total_input_tokens: int + """Number of tokens in the prompt (context).""" + + total_output_tokens: int + """Total number of tokens across all the generated responses.""" + + total_thought_tokens: int + """Number of tokens of thoughts for thinking models.""" + + total_tokens: int + """ + Total token count for the interaction request (prompt + responses + other + internal tokens). + """ + + total_tool_use_tokens: int + """Number of tokens present in tool-use prompt(s).""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/video_content.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/video_content.py new file mode 100644 index 0000000000000000000000000000000000000000..03c65b4520ecf77efd206fc74da066454e80744c --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/video_content.py @@ -0,0 +1,53 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["VideoContent"] + + +class VideoContent(BaseModel): + """A video content block.""" + + type: Literal["video"] + + data: Optional[str] = None + """The video content.""" + + mime_type: Optional[ + Literal[ + "video/mp4", + "video/mpeg", + "video/mpg", + "video/mov", + "video/avi", + "video/x-flv", + "video/webm", + "video/wmv", + "video/3gpp", + ] + ] = None + """The mime type of the video.""" + + resolution: Optional[Literal["low", "medium", "high", "ultra_high"]] = None + """The resolution of the media.""" + + uri: Optional[str] = None + """The URI of the video.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/video_content_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/video_content_param.py new file mode 100644 index 0000000000000000000000000000000000000000..df03cdaa8f662fb5276ba8b1990eab1de9c49542 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/video_content_param.py @@ -0,0 +1,58 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import Literal, Required, Annotated, TypedDict + +from .._types import Base64FileInput +from .._utils import PropertyInfo +from .._models import set_pydantic_config + +__all__ = ["VideoContentParam"] + + +class VideoContentParam(TypedDict, total=False): + """A video content block.""" + + type: Required[Literal["video"]] + + data: Annotated[Union[str, Base64FileInput], PropertyInfo(format="base64")] + """The video content.""" + + mime_type: Literal[ + "video/mp4", + "video/mpeg", + "video/mpg", + "video/mov", + "video/avi", + "video/x-flv", + "video/webm", + "video/wmv", + "video/3gpp", + ] + """The mime type of the video.""" + + resolution: Literal["low", "medium", "high", "ultra_high"] + """The resolution of the media.""" + + uri: str + """The URI of the video.""" + + +set_pydantic_config(VideoContentParam, {"arbitrary_types_allowed": True}) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/webhook.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/webhook.py new file mode 100644 index 0000000000000000000000000000000000000000..6ede43548c21cac7ce4587820dd611e650e75c8e --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/webhook.py @@ -0,0 +1,79 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union, Optional +from datetime import datetime +from typing_extensions import Literal + +from .._models import BaseModel +from .signing_secret import SigningSecret + +__all__ = ["Webhook"] + + +class Webhook(BaseModel): + """A Webhook resource.""" + + subscribed_events: List[ + Union[ + Literal[ + "batch.succeeded", + "batch.cancelled", + "batch.expired", + "batch.failed", + "interaction.requires_action", + "interaction.completed", + "interaction.failed", + "interaction.cancelled", + "video.generated", + ], + str, + ] + ] + """Required. The events that the webhook is subscribed to. Available events: + + - batch.succeeded + - batch.cancelled + - batch.expired + - batch.failed + - interaction.requires_action + - interaction.completed + - interaction.failed + - interaction.cancelled + - video.generated + """ + + uri: str + """Required. The URI to which webhook events will be sent.""" + + create_time: Optional[datetime] = None + """Output only. The timestamp when the webhook was created.""" + + name: Optional[str] = None + """Identifier. The name of the webhook. Format: `webhooks/{webhook_id}`""" + + new_signing_secret: Optional[str] = None + """Output only. The new signing secret for the webhook. Only populated on create.""" + + signing_secrets: Optional[List[SigningSecret]] = None + """Output only. The signing secrets associated with this webhook.""" + + state: Optional[Literal["enabled", "disabled", "disabled_due_to_failed_deliveries"]] = None + """The state of the webhook.""" + + update_time: Optional[datetime] = None + """Output only. The timestamp when the webhook was last updated.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/webhook_config.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/webhook_config.py new file mode 100644 index 0000000000000000000000000000000000000000..b6a16eb7c9d385263a9e0368132866b5d4e0d55b --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/webhook_config.py @@ -0,0 +1,39 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, List, Optional + +from .._models import BaseModel + +__all__ = ["WebhookConfig"] + + +class WebhookConfig(BaseModel): + """Message for configuring webhook events for a request.""" + + uris: Optional[List[str]] = None + """Optional. + + If set, these webhook URIs will be used for webhook events instead of the + registered webhooks. + """ + + user_metadata: Optional[Dict[str, object]] = None + """Optional. + + The user metadata that will be returned on each event emission to the webhooks. + """ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/webhook_config_param.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/webhook_config_param.py new file mode 100644 index 0000000000000000000000000000000000000000..c7dd382384f92349f48fcd4b4e8ecb45ad242ad3 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/webhook_config_param.py @@ -0,0 +1,42 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict +from typing_extensions import TypedDict + +from .._types import SequenceNotStr + +__all__ = ["WebhookConfigParam"] + + +class WebhookConfigParam(TypedDict, total=False): + """Message for configuring webhook events for a request.""" + + uris: SequenceNotStr[str] + """Optional. + + If set, these webhook URIs will be used for webhook events instead of the + registered webhooks. + """ + + user_metadata: Dict[str, object] + """Optional. + + The user metadata that will be returned on each event emission to the webhooks. + """ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/webhook_create_params.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/webhook_create_params.py new file mode 100644 index 0000000000000000000000000000000000000000..987a494f6b17f9d495219007f44b01a4e291adca --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/webhook_create_params.py @@ -0,0 +1,74 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Union +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["WebhookCreateParams"] + + +class WebhookCreateParams(TypedDict, total=False): + api_version: str + + subscribed_events: Required[ + List[ + Union[ + Literal[ + "batch.succeeded", + "batch.cancelled", + "batch.expired", + "batch.failed", + "interaction.requires_action", + "interaction.completed", + "interaction.failed", + "interaction.cancelled", + "video.generated", + ], + str, + ] + ] + ] + """Required. The events that the webhook is subscribed to. Available events: + + - batch.succeeded + - batch.cancelled + - batch.expired + - batch.failed + - interaction.requires_action + - interaction.completed + - interaction.failed + - interaction.cancelled + - video.generated + """ + + uri: Required[str] + """Required. The URI to which webhook events will be sent.""" + + webhook_id: str + """Optional. + + The webhook_id to use for the webhook. If not specified, the server will + generate a unique ID. + """ + + name: str + """Identifier. The name of the webhook. Format: `webhooks/{webhook_id}`""" + + state: Literal["enabled", "disabled", "disabled_due_to_failed_deliveries"] + """The state of the webhook.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/webhook_delete_response.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/webhook_delete_response.py new file mode 100644 index 0000000000000000000000000000000000000000..1d50ba0bdb22f40dbf749e16baabfa9b3fe82c5a --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/webhook_delete_response.py @@ -0,0 +1,34 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .._models import BaseModel + +__all__ = ["WebhookDeleteResponse"] + + +class WebhookDeleteResponse(BaseModel): + """ + A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to use it as the request + or the response type of an API method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); + } + """ + + pass diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/webhook_list_params.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/webhook_list_params.py new file mode 100644 index 0000000000000000000000000000000000000000..aa35c3ee577695b1cb6877ff75cd501d8498de9e --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/webhook_list_params.py @@ -0,0 +1,41 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import TypedDict + +__all__ = ["WebhookListParams"] + + +class WebhookListParams(TypedDict, total=False): + api_version: str + + page_size: int + """Optional. + + The maximum number of webhooks to return. The service may return fewer than this + value. If unspecified, at most 50 webhooks will be returned. The maximum value + is 1000. + """ + + page_token: str + """Optional. + + A page token, received from a previous `ListWebhooks` call. Provide this to + retrieve the subsequent page. + """ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/webhook_list_response.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/webhook_list_response.py new file mode 100644 index 0000000000000000000000000000000000000000..a102ade3af8a7ca3932f49fa0622f0f08cc928f4 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/webhook_list_response.py @@ -0,0 +1,36 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional + +from .webhook import Webhook +from .._models import BaseModel + +__all__ = ["WebhookListResponse"] + + +class WebhookListResponse(BaseModel): + """Response message for WebhookService.ListWebhooks.""" + + next_page_token: Optional[str] = None + """ + A token, which can be sent as `page_token` to retrieve the next page. If this + field is omitted, there are no subsequent pages. + """ + + webhooks: Optional[List[Webhook]] = None + """The webhooks.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/webhook_ping_params.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/webhook_ping_params.py new file mode 100644 index 0000000000000000000000000000000000000000..30ded197f1d9f895ceb163f8fbc828f1d32708b3 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/webhook_ping_params.py @@ -0,0 +1,35 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import TypedDict + +__all__ = ["WebhookPingParams", "Body"] + + +class WebhookPingParams(TypedDict, total=False): + api_version: str + + body: Body + """Request message for WebhookService.PingWebhook.""" + + +class Body(TypedDict, total=False): + """Request message for WebhookService.PingWebhook.""" + + pass diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/webhook_ping_response.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/webhook_ping_response.py new file mode 100644 index 0000000000000000000000000000000000000000..d2f4d474c90e37be983333670f17406cc2766753 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/webhook_ping_response.py @@ -0,0 +1,26 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .._models import BaseModel + +__all__ = ["WebhookPingResponse"] + + +class WebhookPingResponse(BaseModel): + """Response message for WebhookService.PingWebhook.""" + + pass diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/webhook_rotate_signing_secret_params.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/webhook_rotate_signing_secret_params.py new file mode 100644 index 0000000000000000000000000000000000000000..e01940837fa82583f6641852c2a511dab268e537 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/webhook_rotate_signing_secret_params.py @@ -0,0 +1,29 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, TypedDict + +__all__ = ["WebhookRotateSigningSecretParams"] + + +class WebhookRotateSigningSecretParams(TypedDict, total=False): + api_version: str + + revocation_behavior: Literal["revoke_previous_secrets_after_h24", "revoke_previous_secrets_immediately"] + """Optional. The revocation behavior for previous signing secrets.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/webhook_rotate_signing_secret_response.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/webhook_rotate_signing_secret_response.py new file mode 100644 index 0000000000000000000000000000000000000000..b8270592e6ae97ba0000acee080f3ecc687c1239 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/webhook_rotate_signing_secret_response.py @@ -0,0 +1,29 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from .._models import BaseModel + +__all__ = ["WebhookRotateSigningSecretResponse"] + + +class WebhookRotateSigningSecretResponse(BaseModel): + """Response message for WebhookService.RotateSigningSecret.""" + + secret: Optional[str] = None + """Output only. The newly generated signing secret.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/webhook_update_params.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/webhook_update_params.py new file mode 100644 index 0000000000000000000000000000000000000000..a0bd8d0355c63e877be4614e700ee50105442c2d --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_interactions/types/webhook_update_params.py @@ -0,0 +1,70 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Union +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["WebhookUpdateParams"] + + +class WebhookUpdateParams(TypedDict, total=False): + api_version: str + + subscribed_events: Required[ + List[ + Union[ + Literal[ + "batch.succeeded", + "batch.cancelled", + "batch.expired", + "batch.failed", + "interaction.requires_action", + "interaction.completed", + "interaction.failed", + "interaction.cancelled", + "video.generated", + ], + str, + ] + ] + ] + """Required. The events that the webhook is subscribed to. Available events: + + - batch.succeeded + - batch.cancelled + - batch.expired + - batch.failed + - interaction.requires_action + - interaction.completed + - interaction.failed + - interaction.cancelled + - video.generated + """ + + uri: Required[str] + """Required. The URI to which webhook events will be sent.""" + + update_mask: str + """Optional. The list of fields to update.""" + + name: str + """Identifier. The name of the webhook. Format: `webhooks/{webhook_id}`""" + + state: Literal["enabled", "disabled", "disabled_due_to_failed_deliveries"] + """The state of the webhook.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_live_converters.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_live_converters.py new file mode 100644 index 0000000000000000000000000000000000000000..f625c56b263757abe06f0ef8ec8050faf84f7504 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_live_converters.py @@ -0,0 +1,1970 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# Code generated by the Google Gen AI SDK generator DO NOT EDIT. + +from typing import Any, Optional, Union + +from . import _transformers as t +from ._api_client import BaseApiClient +from ._common import get_value_by_path as getv +from ._common import set_value_by_path as setv + + +def _AudioTranscriptionConfig_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['language_codes']) is not None: + raise ValueError('language_codes parameter is not supported in Gemini API.') + + return to_object + + +def _AuthConfig_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['api_key']) is not None: + setv(to_object, ['apiKey'], getv(from_object, ['api_key'])) + + if getv(from_object, ['api_key_config']) is not None: + raise ValueError('api_key_config parameter is not supported in Gemini API.') + + if getv(from_object, ['auth_type']) is not None: + raise ValueError('auth_type parameter is not supported in Gemini API.') + + if getv(from_object, ['google_service_account_config']) is not None: + raise ValueError( + 'google_service_account_config parameter is not supported in Gemini' + ' API.' + ) + + if getv(from_object, ['http_basic_auth_config']) is not None: + raise ValueError( + 'http_basic_auth_config parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['oauth_config']) is not None: + raise ValueError('oauth_config parameter is not supported in Gemini API.') + + if getv(from_object, ['oidc_config']) is not None: + raise ValueError('oidc_config parameter is not supported in Gemini API.') + + return to_object + + +def _Blob_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['data']) is not None: + setv(to_object, ['data'], getv(from_object, ['data'])) + + if getv(from_object, ['display_name']) is not None: + raise ValueError('display_name parameter is not supported in Gemini API.') + + if getv(from_object, ['mime_type']) is not None: + setv(to_object, ['mimeType'], getv(from_object, ['mime_type'])) + + return to_object + + +def _Content_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['parts']) is not None: + setv( + to_object, + ['parts'], + [ + _Part_to_mldev(item, to_object) + for item in getv(from_object, ['parts']) + ], + ) + + if getv(from_object, ['role']) is not None: + setv(to_object, ['role'], getv(from_object, ['role'])) + + return to_object + + +def _Content_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['parts']) is not None: + setv( + to_object, + ['parts'], + [ + _Part_to_vertex(item, to_object) + for item in getv(from_object, ['parts']) + ], + ) + + if getv(from_object, ['role']) is not None: + setv(to_object, ['role'], getv(from_object, ['role'])) + + return to_object + + +def _FileData_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['display_name']) is not None: + raise ValueError('display_name parameter is not supported in Gemini API.') + + if getv(from_object, ['file_uri']) is not None: + setv(to_object, ['fileUri'], getv(from_object, ['file_uri'])) + + if getv(from_object, ['mime_type']) is not None: + setv(to_object, ['mimeType'], getv(from_object, ['mime_type'])) + + return to_object + + +def _FunctionCall_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['id']) is not None: + setv(to_object, ['id'], getv(from_object, ['id'])) + + if getv(from_object, ['args']) is not None: + setv(to_object, ['args'], getv(from_object, ['args'])) + + if getv(from_object, ['name']) is not None: + setv(to_object, ['name'], getv(from_object, ['name'])) + + if getv(from_object, ['partial_args']) is not None: + raise ValueError('partial_args parameter is not supported in Gemini API.') + + if getv(from_object, ['will_continue']) is not None: + raise ValueError('will_continue parameter is not supported in Gemini API.') + + return to_object + + +def _FunctionDeclaration_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['description']) is not None: + setv(to_object, ['description'], getv(from_object, ['description'])) + + if getv(from_object, ['name']) is not None: + setv(to_object, ['name'], getv(from_object, ['name'])) + + if getv(from_object, ['parameters']) is not None: + setv(to_object, ['parameters'], getv(from_object, ['parameters'])) + + if getv(from_object, ['parameters_json_schema']) is not None: + setv( + to_object, + ['parametersJsonSchema'], + getv(from_object, ['parameters_json_schema']), + ) + + if getv(from_object, ['response']) is not None: + setv(to_object, ['response'], getv(from_object, ['response'])) + + if getv(from_object, ['response_json_schema']) is not None: + setv( + to_object, + ['responseJsonSchema'], + getv(from_object, ['response_json_schema']), + ) + + if getv(from_object, ['behavior']) is not None: + raise ValueError('behavior parameter is not supported in Vertex AI.') + + return to_object + + +def _GenerationConfig_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['model_selection_config']) is not None: + setv( + to_object, + ['modelConfig'], + getv(from_object, ['model_selection_config']), + ) + + if getv(from_object, ['response_json_schema']) is not None: + setv( + to_object, + ['responseJsonSchema'], + getv(from_object, ['response_json_schema']), + ) + + if getv(from_object, ['audio_timestamp']) is not None: + setv(to_object, ['audioTimestamp'], getv(from_object, ['audio_timestamp'])) + + if getv(from_object, ['candidate_count']) is not None: + setv(to_object, ['candidateCount'], getv(from_object, ['candidate_count'])) + + if getv(from_object, ['enable_affective_dialog']) is not None: + setv( + to_object, + ['enableAffectiveDialog'], + getv(from_object, ['enable_affective_dialog']), + ) + + if getv(from_object, ['frequency_penalty']) is not None: + setv( + to_object, + ['frequencyPenalty'], + getv(from_object, ['frequency_penalty']), + ) + + if getv(from_object, ['logprobs']) is not None: + setv(to_object, ['logprobs'], getv(from_object, ['logprobs'])) + + if getv(from_object, ['max_output_tokens']) is not None: + setv( + to_object, ['maxOutputTokens'], getv(from_object, ['max_output_tokens']) + ) + + if getv(from_object, ['media_resolution']) is not None: + setv( + to_object, ['mediaResolution'], getv(from_object, ['media_resolution']) + ) + + if getv(from_object, ['presence_penalty']) is not None: + setv( + to_object, ['presencePenalty'], getv(from_object, ['presence_penalty']) + ) + + if getv(from_object, ['response_logprobs']) is not None: + setv( + to_object, + ['responseLogprobs'], + getv(from_object, ['response_logprobs']), + ) + + if getv(from_object, ['response_mime_type']) is not None: + setv( + to_object, + ['responseMimeType'], + getv(from_object, ['response_mime_type']), + ) + + if getv(from_object, ['response_modalities']) is not None: + setv( + to_object, + ['responseModalities'], + getv(from_object, ['response_modalities']), + ) + + if getv(from_object, ['response_schema']) is not None: + setv(to_object, ['responseSchema'], getv(from_object, ['response_schema'])) + + if getv(from_object, ['routing_config']) is not None: + setv(to_object, ['routingConfig'], getv(from_object, ['routing_config'])) + + if getv(from_object, ['seed']) is not None: + setv(to_object, ['seed'], getv(from_object, ['seed'])) + + if getv(from_object, ['speech_config']) is not None: + setv( + to_object, + ['speechConfig'], + _SpeechConfig_to_vertex( + getv(from_object, ['speech_config']), to_object + ), + ) + + if getv(from_object, ['stop_sequences']) is not None: + setv(to_object, ['stopSequences'], getv(from_object, ['stop_sequences'])) + + if getv(from_object, ['temperature']) is not None: + setv(to_object, ['temperature'], getv(from_object, ['temperature'])) + + if getv(from_object, ['thinking_config']) is not None: + setv(to_object, ['thinkingConfig'], getv(from_object, ['thinking_config'])) + + if getv(from_object, ['top_k']) is not None: + setv(to_object, ['topK'], getv(from_object, ['top_k'])) + + if getv(from_object, ['top_p']) is not None: + setv(to_object, ['topP'], getv(from_object, ['top_p'])) + + if getv(from_object, ['enable_enhanced_civic_answers']) is not None: + raise ValueError( + 'enable_enhanced_civic_answers parameter is not supported in Vertex AI.' + ) + + return to_object + + +def _GoogleMaps_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['auth_config']) is not None: + setv( + to_object, + ['authConfig'], + _AuthConfig_to_mldev(getv(from_object, ['auth_config']), to_object), + ) + + if getv(from_object, ['enable_widget']) is not None: + setv(to_object, ['enableWidget'], getv(from_object, ['enable_widget'])) + + return to_object + + +def _GoogleSearch_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['search_types']) is not None: + setv(to_object, ['searchTypes'], getv(from_object, ['search_types'])) + + if getv(from_object, ['blocking_confidence']) is not None: + raise ValueError( + 'blocking_confidence parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['exclude_domains']) is not None: + raise ValueError( + 'exclude_domains parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['time_range_filter']) is not None: + setv( + to_object, ['timeRangeFilter'], getv(from_object, ['time_range_filter']) + ) + + return to_object + + +def _LiveClientContent_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['turns']) is not None: + setv( + to_object, + ['turns'], + [ + _Content_to_mldev(item, to_object) + for item in getv(from_object, ['turns']) + ], + ) + + if getv(from_object, ['turn_complete']) is not None: + setv(to_object, ['turnComplete'], getv(from_object, ['turn_complete'])) + + return to_object + + +def _LiveClientContent_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['turns']) is not None: + setv( + to_object, + ['turns'], + [ + _Content_to_vertex(item, to_object) + for item in getv(from_object, ['turns']) + ], + ) + + if getv(from_object, ['turn_complete']) is not None: + setv(to_object, ['turnComplete'], getv(from_object, ['turn_complete'])) + + return to_object + + +def _LiveClientMessage_to_mldev( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['setup']) is not None: + setv( + to_object, + ['setup'], + _LiveClientSetup_to_mldev( + api_client, getv(from_object, ['setup']), to_object + ), + ) + + if getv(from_object, ['client_content']) is not None: + setv( + to_object, + ['clientContent'], + _LiveClientContent_to_mldev( + getv(from_object, ['client_content']), to_object + ), + ) + + if getv(from_object, ['realtime_input']) is not None: + setv( + to_object, + ['realtimeInput'], + _LiveClientRealtimeInput_to_mldev( + getv(from_object, ['realtime_input']), to_object + ), + ) + + if getv(from_object, ['tool_response']) is not None: + setv(to_object, ['toolResponse'], getv(from_object, ['tool_response'])) + + return to_object + + +def _LiveClientMessage_to_vertex( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['setup']) is not None: + setv( + to_object, + ['setup'], + _LiveClientSetup_to_vertex( + api_client, getv(from_object, ['setup']), to_object + ), + ) + + if getv(from_object, ['client_content']) is not None: + setv( + to_object, + ['clientContent'], + _LiveClientContent_to_vertex( + getv(from_object, ['client_content']), to_object + ), + ) + + if getv(from_object, ['realtime_input']) is not None: + setv( + to_object, + ['realtimeInput'], + _LiveClientRealtimeInput_to_vertex( + getv(from_object, ['realtime_input']), to_object + ), + ) + + if getv(from_object, ['tool_response']) is not None: + setv(to_object, ['toolResponse'], getv(from_object, ['tool_response'])) + + return to_object + + +def _LiveClientRealtimeInput_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['media_chunks']) is not None: + setv( + to_object, + ['mediaChunks'], + [ + _Blob_to_mldev(item, to_object) + for item in getv(from_object, ['media_chunks']) + ], + ) + + if getv(from_object, ['audio']) is not None: + setv( + to_object, + ['audio'], + _Blob_to_mldev(getv(from_object, ['audio']), to_object), + ) + + if getv(from_object, ['audio_stream_end']) is not None: + setv(to_object, ['audioStreamEnd'], getv(from_object, ['audio_stream_end'])) + + if getv(from_object, ['video']) is not None: + setv( + to_object, + ['video'], + _Blob_to_mldev(getv(from_object, ['video']), to_object), + ) + + if getv(from_object, ['text']) is not None: + setv(to_object, ['text'], getv(from_object, ['text'])) + + if getv(from_object, ['activity_start']) is not None: + setv(to_object, ['activityStart'], getv(from_object, ['activity_start'])) + + if getv(from_object, ['activity_end']) is not None: + setv(to_object, ['activityEnd'], getv(from_object, ['activity_end'])) + + return to_object + + +def _LiveClientRealtimeInput_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['media_chunks']) is not None: + setv( + to_object, + ['mediaChunks'], + [item for item in getv(from_object, ['media_chunks'])], + ) + + if getv(from_object, ['audio']) is not None: + setv(to_object, ['audio'], getv(from_object, ['audio'])) + + if getv(from_object, ['audio_stream_end']) is not None: + raise ValueError( + 'audio_stream_end parameter is not supported in Vertex AI.' + ) + + if getv(from_object, ['video']) is not None: + setv(to_object, ['video'], getv(from_object, ['video'])) + + if getv(from_object, ['text']) is not None: + setv(to_object, ['text'], getv(from_object, ['text'])) + + if getv(from_object, ['activity_start']) is not None: + setv(to_object, ['activityStart'], getv(from_object, ['activity_start'])) + + if getv(from_object, ['activity_end']) is not None: + setv(to_object, ['activityEnd'], getv(from_object, ['activity_end'])) + + return to_object + + +def _LiveClientSetup_to_mldev( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['model']) is not None: + setv(to_object, ['model'], getv(from_object, ['model'])) + + if getv(from_object, ['generation_config']) is not None: + setv( + to_object, + ['generationConfig'], + getv(from_object, ['generation_config']), + ) + + if getv(from_object, ['system_instruction']) is not None: + setv( + to_object, + ['systemInstruction'], + _Content_to_mldev( + t.t_content(getv(from_object, ['system_instruction'])), to_object + ), + ) + + if getv(from_object, ['tools']) is not None: + setv( + to_object, + ['tools'], + [ + _Tool_to_mldev(t.t_tool(api_client, item), to_object) + for item in t.t_tools(api_client, getv(from_object, ['tools'])) + ], + ) + + if getv(from_object, ['session_resumption']) is not None: + setv( + to_object, + ['sessionResumption'], + _SessionResumptionConfig_to_mldev( + getv(from_object, ['session_resumption']), to_object + ), + ) + + if getv(from_object, ['context_window_compression']) is not None: + setv( + to_object, + ['contextWindowCompression'], + getv(from_object, ['context_window_compression']), + ) + + if getv(from_object, ['input_audio_transcription']) is not None: + setv( + to_object, + ['inputAudioTranscription'], + _AudioTranscriptionConfig_to_mldev( + getv(from_object, ['input_audio_transcription']), to_object + ), + ) + + if getv(from_object, ['output_audio_transcription']) is not None: + setv( + to_object, + ['outputAudioTranscription'], + _AudioTranscriptionConfig_to_mldev( + getv(from_object, ['output_audio_transcription']), to_object + ), + ) + + if getv(from_object, ['proactivity']) is not None: + setv(to_object, ['proactivity'], getv(from_object, ['proactivity'])) + + if getv(from_object, ['explicit_vad_signal']) is not None: + raise ValueError( + 'explicit_vad_signal parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['history_config']) is not None: + setv(to_object, ['historyConfig'], getv(from_object, ['history_config'])) + + if getv(from_object, ['avatar_config']) is not None: + setv(to_object, ['avatarConfig'], getv(from_object, ['avatar_config'])) + + if getv(from_object, ['safety_settings']) is not None: + setv( + to_object, + ['safetySettings'], + [ + _SafetySetting_to_mldev(item, to_object) + for item in getv(from_object, ['safety_settings']) + ], + ) + + return to_object + + +def _LiveClientSetup_to_vertex( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['model']) is not None: + setv(to_object, ['model'], getv(from_object, ['model'])) + + if getv(from_object, ['generation_config']) is not None: + setv( + to_object, + ['generationConfig'], + _GenerationConfig_to_vertex( + getv(from_object, ['generation_config']), to_object + ), + ) + + if getv(from_object, ['system_instruction']) is not None: + setv( + to_object, + ['systemInstruction'], + _Content_to_vertex( + t.t_content(getv(from_object, ['system_instruction'])), to_object + ), + ) + + if getv(from_object, ['tools']) is not None: + setv( + to_object, + ['tools'], + [ + _Tool_to_vertex(t.t_tool(api_client, item), to_object) + for item in t.t_tools(api_client, getv(from_object, ['tools'])) + ], + ) + + if getv(from_object, ['session_resumption']) is not None: + setv( + to_object, + ['sessionResumption'], + getv(from_object, ['session_resumption']), + ) + + if getv(from_object, ['context_window_compression']) is not None: + setv( + to_object, + ['contextWindowCompression'], + getv(from_object, ['context_window_compression']), + ) + + if getv(from_object, ['input_audio_transcription']) is not None: + setv( + to_object, + ['inputAudioTranscription'], + getv(from_object, ['input_audio_transcription']), + ) + + if getv(from_object, ['output_audio_transcription']) is not None: + setv( + to_object, + ['outputAudioTranscription'], + getv(from_object, ['output_audio_transcription']), + ) + + if getv(from_object, ['proactivity']) is not None: + setv(to_object, ['proactivity'], getv(from_object, ['proactivity'])) + + if getv(from_object, ['explicit_vad_signal']) is not None: + setv( + to_object, + ['explicitVadSignal'], + getv(from_object, ['explicit_vad_signal']), + ) + + if getv(from_object, ['history_config']) is not None: + raise ValueError('history_config parameter is not supported in Vertex AI.') + + if getv(from_object, ['avatar_config']) is not None: + setv(to_object, ['avatarConfig'], getv(from_object, ['avatar_config'])) + + if getv(from_object, ['safety_settings']) is not None: + setv( + to_object, + ['safetySettings'], + [item for item in getv(from_object, ['safety_settings'])], + ) + + return to_object + + +def _LiveConnectConfig_to_mldev( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['generation_config']) is not None: + setv( + parent_object, + ['setup', 'generationConfig'], + getv(from_object, ['generation_config']), + ) + + if getv(from_object, ['response_modalities']) is not None: + setv( + parent_object, + ['setup', 'generationConfig', 'responseModalities'], + getv(from_object, ['response_modalities']), + ) + + if getv(from_object, ['temperature']) is not None: + setv( + parent_object, + ['setup', 'generationConfig', 'temperature'], + getv(from_object, ['temperature']), + ) + + if getv(from_object, ['top_p']) is not None: + setv( + parent_object, + ['setup', 'generationConfig', 'topP'], + getv(from_object, ['top_p']), + ) + + if getv(from_object, ['top_k']) is not None: + setv( + parent_object, + ['setup', 'generationConfig', 'topK'], + getv(from_object, ['top_k']), + ) + + if getv(from_object, ['max_output_tokens']) is not None: + setv( + parent_object, + ['setup', 'generationConfig', 'maxOutputTokens'], + getv(from_object, ['max_output_tokens']), + ) + + if getv(from_object, ['media_resolution']) is not None: + setv( + parent_object, + ['setup', 'generationConfig', 'mediaResolution'], + getv(from_object, ['media_resolution']), + ) + + if getv(from_object, ['seed']) is not None: + setv( + parent_object, + ['setup', 'generationConfig', 'seed'], + getv(from_object, ['seed']), + ) + + if getv(from_object, ['speech_config']) is not None: + setv( + parent_object, + ['setup', 'generationConfig', 'speechConfig'], + t.t_live_speech_config(getv(from_object, ['speech_config'])), + ) + + if getv(from_object, ['thinking_config']) is not None: + setv( + parent_object, + ['setup', 'generationConfig', 'thinkingConfig'], + getv(from_object, ['thinking_config']), + ) + + if getv(from_object, ['enable_affective_dialog']) is not None: + setv( + parent_object, + ['setup', 'generationConfig', 'enableAffectiveDialog'], + getv(from_object, ['enable_affective_dialog']), + ) + + if getv(from_object, ['system_instruction']) is not None: + setv( + parent_object, + ['setup', 'systemInstruction'], + _Content_to_mldev( + t.t_content(getv(from_object, ['system_instruction'])), to_object + ), + ) + + if getv(from_object, ['tools']) is not None: + setv( + parent_object, + ['setup', 'tools'], + [ + _Tool_to_mldev(t.t_tool(api_client, item), to_object) + for item in t.t_tools(api_client, getv(from_object, ['tools'])) + ], + ) + + if getv(from_object, ['session_resumption']) is not None: + setv( + parent_object, + ['setup', 'sessionResumption'], + _SessionResumptionConfig_to_mldev( + getv(from_object, ['session_resumption']), to_object + ), + ) + + if getv(from_object, ['input_audio_transcription']) is not None: + setv( + parent_object, + ['setup', 'inputAudioTranscription'], + _AudioTranscriptionConfig_to_mldev( + getv(from_object, ['input_audio_transcription']), to_object + ), + ) + + if getv(from_object, ['output_audio_transcription']) is not None: + setv( + parent_object, + ['setup', 'outputAudioTranscription'], + _AudioTranscriptionConfig_to_mldev( + getv(from_object, ['output_audio_transcription']), to_object + ), + ) + + if getv(from_object, ['realtime_input_config']) is not None: + setv( + parent_object, + ['setup', 'realtimeInputConfig'], + getv(from_object, ['realtime_input_config']), + ) + + if getv(from_object, ['context_window_compression']) is not None: + setv( + parent_object, + ['setup', 'contextWindowCompression'], + getv(from_object, ['context_window_compression']), + ) + + if getv(from_object, ['proactivity']) is not None: + setv( + parent_object, + ['setup', 'proactivity'], + getv(from_object, ['proactivity']), + ) + + if getv(from_object, ['explicit_vad_signal']) is not None: + raise ValueError( + 'explicit_vad_signal parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['history_config']) is not None: + setv( + parent_object, + ['setup', 'historyConfig'], + getv(from_object, ['history_config']), + ) + + if getv(from_object, ['avatar_config']) is not None: + setv( + parent_object, + ['setup', 'avatarConfig'], + getv(from_object, ['avatar_config']), + ) + + if getv(from_object, ['safety_settings']) is not None: + setv( + parent_object, + ['setup', 'safetySettings'], + [ + _SafetySetting_to_mldev(item, to_object) + for item in getv(from_object, ['safety_settings']) + ], + ) + + return to_object + + +def _LiveConnectConfig_to_vertex( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['generation_config']) is not None: + setv( + parent_object, + ['setup', 'generationConfig'], + _GenerationConfig_to_vertex( + getv(from_object, ['generation_config']), to_object + ), + ) + + if getv(from_object, ['response_modalities']) is not None: + setv( + parent_object, + ['setup', 'generationConfig', 'responseModalities'], + getv(from_object, ['response_modalities']), + ) + + if getv(from_object, ['temperature']) is not None: + setv( + parent_object, + ['setup', 'generationConfig', 'temperature'], + getv(from_object, ['temperature']), + ) + + if getv(from_object, ['top_p']) is not None: + setv( + parent_object, + ['setup', 'generationConfig', 'topP'], + getv(from_object, ['top_p']), + ) + + if getv(from_object, ['top_k']) is not None: + setv( + parent_object, + ['setup', 'generationConfig', 'topK'], + getv(from_object, ['top_k']), + ) + + if getv(from_object, ['max_output_tokens']) is not None: + setv( + parent_object, + ['setup', 'generationConfig', 'maxOutputTokens'], + getv(from_object, ['max_output_tokens']), + ) + + if getv(from_object, ['media_resolution']) is not None: + setv( + parent_object, + ['setup', 'generationConfig', 'mediaResolution'], + getv(from_object, ['media_resolution']), + ) + + if getv(from_object, ['seed']) is not None: + setv( + parent_object, + ['setup', 'generationConfig', 'seed'], + getv(from_object, ['seed']), + ) + + if getv(from_object, ['speech_config']) is not None: + setv( + parent_object, + ['setup', 'generationConfig', 'speechConfig'], + _SpeechConfig_to_vertex( + t.t_live_speech_config(getv(from_object, ['speech_config'])), + to_object, + ), + ) + + if getv(from_object, ['thinking_config']) is not None: + setv( + parent_object, + ['setup', 'generationConfig', 'thinkingConfig'], + getv(from_object, ['thinking_config']), + ) + + if getv(from_object, ['enable_affective_dialog']) is not None: + setv( + parent_object, + ['setup', 'generationConfig', 'enableAffectiveDialog'], + getv(from_object, ['enable_affective_dialog']), + ) + + if getv(from_object, ['system_instruction']) is not None: + setv( + parent_object, + ['setup', 'systemInstruction'], + _Content_to_vertex( + t.t_content(getv(from_object, ['system_instruction'])), to_object + ), + ) + + if getv(from_object, ['tools']) is not None: + setv( + parent_object, + ['setup', 'tools'], + [ + _Tool_to_vertex(t.t_tool(api_client, item), to_object) + for item in t.t_tools(api_client, getv(from_object, ['tools'])) + ], + ) + + if getv(from_object, ['session_resumption']) is not None: + setv( + parent_object, + ['setup', 'sessionResumption'], + getv(from_object, ['session_resumption']), + ) + + if getv(from_object, ['input_audio_transcription']) is not None: + setv( + parent_object, + ['setup', 'inputAudioTranscription'], + getv(from_object, ['input_audio_transcription']), + ) + + if getv(from_object, ['output_audio_transcription']) is not None: + setv( + parent_object, + ['setup', 'outputAudioTranscription'], + getv(from_object, ['output_audio_transcription']), + ) + + if getv(from_object, ['realtime_input_config']) is not None: + setv( + parent_object, + ['setup', 'realtimeInputConfig'], + getv(from_object, ['realtime_input_config']), + ) + + if getv(from_object, ['context_window_compression']) is not None: + setv( + parent_object, + ['setup', 'contextWindowCompression'], + getv(from_object, ['context_window_compression']), + ) + + if getv(from_object, ['proactivity']) is not None: + setv( + parent_object, + ['setup', 'proactivity'], + getv(from_object, ['proactivity']), + ) + + if getv(from_object, ['explicit_vad_signal']) is not None: + setv( + parent_object, + ['setup', 'explicitVadSignal'], + getv(from_object, ['explicit_vad_signal']), + ) + + if getv(from_object, ['history_config']) is not None: + raise ValueError('history_config parameter is not supported in Vertex AI.') + + if getv(from_object, ['avatar_config']) is not None: + setv( + parent_object, + ['setup', 'avatarConfig'], + getv(from_object, ['avatar_config']), + ) + + if getv(from_object, ['safety_settings']) is not None: + setv( + parent_object, + ['setup', 'safetySettings'], + [item for item in getv(from_object, ['safety_settings'])], + ) + + return to_object + + +def _LiveConnectParameters_to_mldev( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['model']) is not None: + setv( + to_object, + ['setup', 'model'], + t.t_model(api_client, getv(from_object, ['model'])), + ) + + if getv(from_object, ['config']) is not None: + setv( + to_object, + ['config'], + _LiveConnectConfig_to_mldev( + api_client, getv(from_object, ['config']), to_object + ), + ) + + return to_object + + +def _LiveConnectParameters_to_vertex( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['model']) is not None: + setv( + to_object, + ['setup', 'model'], + t.t_model(api_client, getv(from_object, ['model'])), + ) + + if getv(from_object, ['config']) is not None: + setv( + to_object, + ['config'], + _LiveConnectConfig_to_vertex( + api_client, getv(from_object, ['config']), to_object + ), + ) + + return to_object + + +def _LiveMusicClientMessage_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['setup']) is not None: + raise ValueError('setup parameter is not supported in Vertex AI.') + + if getv(from_object, ['client_content']) is not None: + raise ValueError('client_content parameter is not supported in Vertex AI.') + + if getv(from_object, ['music_generation_config']) is not None: + raise ValueError( + 'music_generation_config parameter is not supported in Vertex AI.' + ) + + if getv(from_object, ['playback_control']) is not None: + raise ValueError( + 'playback_control parameter is not supported in Vertex AI.' + ) + + return to_object + + +def _LiveMusicConnectParameters_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['model']) is not None: + setv(to_object, ['setup', 'model'], getv(from_object, ['model'])) + + return to_object + + +def _LiveMusicConnectParameters_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['model']) is not None: + raise ValueError('model parameter is not supported in Vertex AI.') + + return to_object + + +def _LiveMusicSetConfigParameters_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['music_generation_config']) is not None: + setv( + to_object, + ['musicGenerationConfig'], + getv(from_object, ['music_generation_config']), + ) + + return to_object + + +def _LiveMusicSetConfigParameters_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['music_generation_config']) is not None: + raise ValueError( + 'music_generation_config parameter is not supported in Vertex AI.' + ) + + return to_object + + +def _LiveMusicSetWeightedPromptsParameters_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['weighted_prompts']) is not None: + setv( + to_object, + ['weightedPrompts'], + [item for item in getv(from_object, ['weighted_prompts'])], + ) + + return to_object + + +def _LiveMusicSetWeightedPromptsParameters_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['weighted_prompts']) is not None: + raise ValueError( + 'weighted_prompts parameter is not supported in Vertex AI.' + ) + + return to_object + + +def _LiveSendRealtimeInputParameters_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['media']) is not None: + setv( + to_object, + ['mediaChunks'], + [ + _Blob_to_mldev(item, to_object) + for item in t.t_blobs(getv(from_object, ['media'])) + ], + ) + + if getv(from_object, ['audio']) is not None: + setv( + to_object, + ['audio'], + _Blob_to_mldev(t.t_audio_blob(getv(from_object, ['audio'])), to_object), + ) + + if getv(from_object, ['audio_stream_end']) is not None: + setv(to_object, ['audioStreamEnd'], getv(from_object, ['audio_stream_end'])) + + if getv(from_object, ['video']) is not None: + setv( + to_object, + ['video'], + _Blob_to_mldev(t.t_image_blob(getv(from_object, ['video'])), to_object), + ) + + if getv(from_object, ['text']) is not None: + setv(to_object, ['text'], getv(from_object, ['text'])) + + if getv(from_object, ['activity_start']) is not None: + setv(to_object, ['activityStart'], getv(from_object, ['activity_start'])) + + if getv(from_object, ['activity_end']) is not None: + setv(to_object, ['activityEnd'], getv(from_object, ['activity_end'])) + + return to_object + + +def _LiveSendRealtimeInputParameters_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['media']) is not None: + setv( + to_object, + ['mediaChunks'], + [item for item in t.t_blobs(getv(from_object, ['media']))], + ) + + if getv(from_object, ['audio']) is not None: + setv(to_object, ['audio'], t.t_audio_blob(getv(from_object, ['audio']))) + + if getv(from_object, ['audio_stream_end']) is not None: + setv(to_object, ['audioStreamEnd'], getv(from_object, ['audio_stream_end'])) + + if getv(from_object, ['video']) is not None: + setv(to_object, ['video'], t.t_image_blob(getv(from_object, ['video']))) + + if getv(from_object, ['text']) is not None: + setv(to_object, ['text'], getv(from_object, ['text'])) + + if getv(from_object, ['activity_start']) is not None: + setv(to_object, ['activityStart'], getv(from_object, ['activity_start'])) + + if getv(from_object, ['activity_end']) is not None: + setv(to_object, ['activityEnd'], getv(from_object, ['activity_end'])) + + return to_object + + +def _LiveServerMessage_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['setupComplete']) is not None: + setv(to_object, ['setup_complete'], getv(from_object, ['setupComplete'])) + + if getv(from_object, ['serverContent']) is not None: + setv(to_object, ['server_content'], getv(from_object, ['serverContent'])) + + if getv(from_object, ['toolCall']) is not None: + setv(to_object, ['tool_call'], getv(from_object, ['toolCall'])) + + if getv(from_object, ['toolCallCancellation']) is not None: + setv( + to_object, + ['tool_call_cancellation'], + getv(from_object, ['toolCallCancellation']), + ) + + if getv(from_object, ['usageMetadata']) is not None: + setv(to_object, ['usage_metadata'], getv(from_object, ['usageMetadata'])) + + if getv(from_object, ['goAway']) is not None: + setv(to_object, ['go_away'], getv(from_object, ['goAway'])) + + if getv(from_object, ['sessionResumptionUpdate']) is not None: + setv( + to_object, + ['session_resumption_update'], + getv(from_object, ['sessionResumptionUpdate']), + ) + + if getv(from_object, ['voiceActivityDetectionSignal']) is not None: + setv( + to_object, + ['voice_activity_detection_signal'], + getv(from_object, ['voiceActivityDetectionSignal']), + ) + + if getv(from_object, ['voiceActivity']) is not None: + setv( + to_object, + ['voice_activity'], + _VoiceActivity_from_mldev( + getv(from_object, ['voiceActivity']), to_object + ), + ) + + return to_object + + +def _LiveServerMessage_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['setupComplete']) is not None: + setv(to_object, ['setup_complete'], getv(from_object, ['setupComplete'])) + + if getv(from_object, ['serverContent']) is not None: + setv(to_object, ['server_content'], getv(from_object, ['serverContent'])) + + if getv(from_object, ['toolCall']) is not None: + setv(to_object, ['tool_call'], getv(from_object, ['toolCall'])) + + if getv(from_object, ['toolCallCancellation']) is not None: + setv( + to_object, + ['tool_call_cancellation'], + getv(from_object, ['toolCallCancellation']), + ) + + if getv(from_object, ['usageMetadata']) is not None: + setv( + to_object, + ['usage_metadata'], + _UsageMetadata_from_vertex( + getv(from_object, ['usageMetadata']), to_object + ), + ) + + if getv(from_object, ['goAway']) is not None: + setv(to_object, ['go_away'], getv(from_object, ['goAway'])) + + if getv(from_object, ['sessionResumptionUpdate']) is not None: + setv( + to_object, + ['session_resumption_update'], + getv(from_object, ['sessionResumptionUpdate']), + ) + + if getv(from_object, ['voiceActivityDetectionSignal']) is not None: + setv( + to_object, + ['voice_activity_detection_signal'], + getv(from_object, ['voiceActivityDetectionSignal']), + ) + + if getv(from_object, ['voiceActivity']) is not None: + setv( + to_object, + ['voice_activity'], + _VoiceActivity_from_vertex( + getv(from_object, ['voiceActivity']), to_object + ), + ) + + return to_object + + +def _MultiSpeakerVoiceConfig_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['speaker_voice_configs']) is not None: + setv( + to_object, + ['speakerVoiceConfigs'], + [ + _SpeakerVoiceConfig_to_vertex(item, to_object) + for item in getv(from_object, ['speaker_voice_configs']) + ], + ) + + return to_object + + +def _Part_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['media_resolution']) is not None: + setv( + to_object, ['mediaResolution'], getv(from_object, ['media_resolution']) + ) + + if getv(from_object, ['code_execution_result']) is not None: + setv( + to_object, + ['codeExecutionResult'], + getv(from_object, ['code_execution_result']), + ) + + if getv(from_object, ['executable_code']) is not None: + setv(to_object, ['executableCode'], getv(from_object, ['executable_code'])) + + if getv(from_object, ['file_data']) is not None: + setv( + to_object, + ['fileData'], + _FileData_to_mldev(getv(from_object, ['file_data']), to_object), + ) + + if getv(from_object, ['function_call']) is not None: + setv( + to_object, + ['functionCall'], + _FunctionCall_to_mldev(getv(from_object, ['function_call']), to_object), + ) + + if getv(from_object, ['function_response']) is not None: + setv( + to_object, + ['functionResponse'], + getv(from_object, ['function_response']), + ) + + if getv(from_object, ['inline_data']) is not None: + setv( + to_object, + ['inlineData'], + _Blob_to_mldev(getv(from_object, ['inline_data']), to_object), + ) + + if getv(from_object, ['text']) is not None: + setv(to_object, ['text'], getv(from_object, ['text'])) + + if getv(from_object, ['thought']) is not None: + setv(to_object, ['thought'], getv(from_object, ['thought'])) + + if getv(from_object, ['thought_signature']) is not None: + setv( + to_object, + ['thoughtSignature'], + getv(from_object, ['thought_signature']), + ) + + if getv(from_object, ['video_metadata']) is not None: + setv(to_object, ['videoMetadata'], getv(from_object, ['video_metadata'])) + + if getv(from_object, ['tool_call']) is not None: + setv(to_object, ['toolCall'], getv(from_object, ['tool_call'])) + + if getv(from_object, ['tool_response']) is not None: + setv(to_object, ['toolResponse'], getv(from_object, ['tool_response'])) + + if getv(from_object, ['part_metadata']) is not None: + setv(to_object, ['partMetadata'], getv(from_object, ['part_metadata'])) + + return to_object + + +def _Part_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['media_resolution']) is not None: + setv( + to_object, ['mediaResolution'], getv(from_object, ['media_resolution']) + ) + + if getv(from_object, ['code_execution_result']) is not None: + setv( + to_object, + ['codeExecutionResult'], + getv(from_object, ['code_execution_result']), + ) + + if getv(from_object, ['executable_code']) is not None: + setv(to_object, ['executableCode'], getv(from_object, ['executable_code'])) + + if getv(from_object, ['file_data']) is not None: + setv(to_object, ['fileData'], getv(from_object, ['file_data'])) + + if getv(from_object, ['function_call']) is not None: + setv(to_object, ['functionCall'], getv(from_object, ['function_call'])) + + if getv(from_object, ['function_response']) is not None: + setv( + to_object, + ['functionResponse'], + getv(from_object, ['function_response']), + ) + + if getv(from_object, ['inline_data']) is not None: + setv(to_object, ['inlineData'], getv(from_object, ['inline_data'])) + + if getv(from_object, ['text']) is not None: + setv(to_object, ['text'], getv(from_object, ['text'])) + + if getv(from_object, ['thought']) is not None: + setv(to_object, ['thought'], getv(from_object, ['thought'])) + + if getv(from_object, ['thought_signature']) is not None: + setv( + to_object, + ['thoughtSignature'], + getv(from_object, ['thought_signature']), + ) + + if getv(from_object, ['video_metadata']) is not None: + setv(to_object, ['videoMetadata'], getv(from_object, ['video_metadata'])) + + if getv(from_object, ['tool_call']) is not None: + raise ValueError('tool_call parameter is not supported in Vertex AI.') + + if getv(from_object, ['tool_response']) is not None: + raise ValueError('tool_response parameter is not supported in Vertex AI.') + + if getv(from_object, ['part_metadata']) is not None: + raise ValueError('part_metadata parameter is not supported in Vertex AI.') + + return to_object + + +def _ReplicatedVoiceConfig_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['mime_type']) is not None: + setv(to_object, ['mimeType'], getv(from_object, ['mime_type'])) + + if getv(from_object, ['voice_sample_audio']) is not None: + setv( + to_object, + ['voiceSampleAudio'], + getv(from_object, ['voice_sample_audio']), + ) + + if getv(from_object, ['consent_audio']) is not None: + raise ValueError('consent_audio parameter is not supported in Vertex AI.') + + if getv(from_object, ['voice_consent_signature']) is not None: + raise ValueError( + 'voice_consent_signature parameter is not supported in Vertex AI.' + ) + + return to_object + + +def _SafetySetting_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['category']) is not None: + setv(to_object, ['category'], getv(from_object, ['category'])) + + if getv(from_object, ['method']) is not None: + raise ValueError('method parameter is not supported in Gemini API.') + + if getv(from_object, ['threshold']) is not None: + setv(to_object, ['threshold'], getv(from_object, ['threshold'])) + + return to_object + + +def _SessionResumptionConfig_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['handle']) is not None: + setv(to_object, ['handle'], getv(from_object, ['handle'])) + + if getv(from_object, ['transparent']) is not None: + raise ValueError('transparent parameter is not supported in Gemini API.') + + return to_object + + +def _SpeakerVoiceConfig_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['speaker']) is not None: + setv(to_object, ['speaker'], getv(from_object, ['speaker'])) + + if getv(from_object, ['voice_config']) is not None: + setv( + to_object, + ['voiceConfig'], + _VoiceConfig_to_vertex(getv(from_object, ['voice_config']), to_object), + ) + + return to_object + + +def _SpeechConfig_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['voice_config']) is not None: + setv( + to_object, + ['voiceConfig'], + _VoiceConfig_to_vertex(getv(from_object, ['voice_config']), to_object), + ) + + if getv(from_object, ['language_code']) is not None: + setv(to_object, ['languageCode'], getv(from_object, ['language_code'])) + + if getv(from_object, ['multi_speaker_voice_config']) is not None: + setv( + to_object, + ['multiSpeakerVoiceConfig'], + _MultiSpeakerVoiceConfig_to_vertex( + getv(from_object, ['multi_speaker_voice_config']), to_object + ), + ) + + return to_object + + +def _Tool_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['retrieval']) is not None: + raise ValueError('retrieval parameter is not supported in Gemini API.') + + if getv(from_object, ['computer_use']) is not None: + setv(to_object, ['computerUse'], getv(from_object, ['computer_use'])) + + if getv(from_object, ['file_search']) is not None: + setv(to_object, ['fileSearch'], getv(from_object, ['file_search'])) + + if getv(from_object, ['google_search']) is not None: + setv( + to_object, + ['googleSearch'], + _GoogleSearch_to_mldev(getv(from_object, ['google_search']), to_object), + ) + + if getv(from_object, ['google_maps']) is not None: + setv( + to_object, + ['googleMaps'], + _GoogleMaps_to_mldev(getv(from_object, ['google_maps']), to_object), + ) + + if getv(from_object, ['code_execution']) is not None: + setv(to_object, ['codeExecution'], getv(from_object, ['code_execution'])) + + if getv(from_object, ['enterprise_web_search']) is not None: + raise ValueError( + 'enterprise_web_search parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['function_declarations']) is not None: + setv( + to_object, + ['functionDeclarations'], + [item for item in getv(from_object, ['function_declarations'])], + ) + + if getv(from_object, ['google_search_retrieval']) is not None: + setv( + to_object, + ['googleSearchRetrieval'], + getv(from_object, ['google_search_retrieval']), + ) + + if getv(from_object, ['parallel_ai_search']) is not None: + raise ValueError( + 'parallel_ai_search parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['url_context']) is not None: + setv(to_object, ['urlContext'], getv(from_object, ['url_context'])) + + if getv(from_object, ['mcp_servers']) is not None: + setv( + to_object, + ['mcpServers'], + [item for item in getv(from_object, ['mcp_servers'])], + ) + + return to_object + + +def _Tool_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['retrieval']) is not None: + setv(to_object, ['retrieval'], getv(from_object, ['retrieval'])) + + if getv(from_object, ['computer_use']) is not None: + setv(to_object, ['computerUse'], getv(from_object, ['computer_use'])) + + if getv(from_object, ['file_search']) is not None: + raise ValueError('file_search parameter is not supported in Vertex AI.') + + if getv(from_object, ['google_search']) is not None: + setv(to_object, ['googleSearch'], getv(from_object, ['google_search'])) + + if getv(from_object, ['google_maps']) is not None: + setv(to_object, ['googleMaps'], getv(from_object, ['google_maps'])) + + if getv(from_object, ['code_execution']) is not None: + setv(to_object, ['codeExecution'], getv(from_object, ['code_execution'])) + + if getv(from_object, ['enterprise_web_search']) is not None: + setv( + to_object, + ['enterpriseWebSearch'], + getv(from_object, ['enterprise_web_search']), + ) + + if getv(from_object, ['function_declarations']) is not None: + setv( + to_object, + ['functionDeclarations'], + [ + _FunctionDeclaration_to_vertex(item, to_object) + for item in getv(from_object, ['function_declarations']) + ], + ) + + if getv(from_object, ['google_search_retrieval']) is not None: + setv( + to_object, + ['googleSearchRetrieval'], + getv(from_object, ['google_search_retrieval']), + ) + + if getv(from_object, ['parallel_ai_search']) is not None: + setv( + to_object, + ['parallelAiSearch'], + getv(from_object, ['parallel_ai_search']), + ) + + if getv(from_object, ['url_context']) is not None: + setv(to_object, ['urlContext'], getv(from_object, ['url_context'])) + + if getv(from_object, ['mcp_servers']) is not None: + raise ValueError('mcp_servers parameter is not supported in Vertex AI.') + + return to_object + + +def _UsageMetadata_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['promptTokenCount']) is not None: + setv( + to_object, + ['prompt_token_count'], + getv(from_object, ['promptTokenCount']), + ) + + if getv(from_object, ['cachedContentTokenCount']) is not None: + setv( + to_object, + ['cached_content_token_count'], + getv(from_object, ['cachedContentTokenCount']), + ) + + if getv(from_object, ['candidatesTokenCount']) is not None: + setv( + to_object, + ['response_token_count'], + getv(from_object, ['candidatesTokenCount']), + ) + + if getv(from_object, ['toolUsePromptTokenCount']) is not None: + setv( + to_object, + ['tool_use_prompt_token_count'], + getv(from_object, ['toolUsePromptTokenCount']), + ) + + if getv(from_object, ['thoughtsTokenCount']) is not None: + setv( + to_object, + ['thoughts_token_count'], + getv(from_object, ['thoughtsTokenCount']), + ) + + if getv(from_object, ['totalTokenCount']) is not None: + setv( + to_object, ['total_token_count'], getv(from_object, ['totalTokenCount']) + ) + + if getv(from_object, ['promptTokensDetails']) is not None: + setv( + to_object, + ['prompt_tokens_details'], + [item for item in getv(from_object, ['promptTokensDetails'])], + ) + + if getv(from_object, ['cacheTokensDetails']) is not None: + setv( + to_object, + ['cache_tokens_details'], + [item for item in getv(from_object, ['cacheTokensDetails'])], + ) + + if getv(from_object, ['candidatesTokensDetails']) is not None: + setv( + to_object, + ['response_tokens_details'], + [item for item in getv(from_object, ['candidatesTokensDetails'])], + ) + + if getv(from_object, ['toolUsePromptTokensDetails']) is not None: + setv( + to_object, + ['tool_use_prompt_tokens_details'], + [item for item in getv(from_object, ['toolUsePromptTokensDetails'])], + ) + + if getv(from_object, ['trafficType']) is not None: + setv(to_object, ['traffic_type'], getv(from_object, ['trafficType'])) + + return to_object + + +def _VoiceActivity_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['type']) is not None: + setv(to_object, ['voice_activity_type'], getv(from_object, ['type'])) + + return to_object + + +def _VoiceActivity_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['type']) is not None: + setv(to_object, ['voice_activity_type'], getv(from_object, ['type'])) + + return to_object + + +def _VoiceConfig_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['replicated_voice_config']) is not None: + setv( + to_object, + ['replicatedVoiceConfig'], + _ReplicatedVoiceConfig_to_vertex( + getv(from_object, ['replicated_voice_config']), to_object + ), + ) + + if getv(from_object, ['prebuilt_voice_config']) is not None: + setv( + to_object, + ['prebuiltVoiceConfig'], + getv(from_object, ['prebuilt_voice_config']), + ) + + return to_object diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_local_tokenizer_loader.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_local_tokenizer_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..0f6edc3adb1b09998c47c17164862d7ca2031861 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_local_tokenizer_loader.py @@ -0,0 +1,215 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +import dataclasses +import functools +import hashlib +import os +import tempfile +from typing import Optional, cast +import uuid + +import requests # type: ignore +import sentencepiece as spm +from sentencepiece import sentencepiece_model_pb2 + + +# Source of truth: https://cloud.google.com/vertex-ai/generative-ai/docs/learn/models +_GEMINI_MODELS_TO_TOKENIZER_NAMES = { + "gemini-2.5-pro": "gemma3", + "gemini-2.5-flash": "gemma3", + "gemini-2.5-flash-lite": "gemma3", + "gemini-2.0-flash": "gemma3", + "gemini-2.0-flash-lite": "gemma3", +} +_GEMINI_STABLE_MODELS_TO_TOKENIZER_NAMES = { + "gemini-2.5-pro-preview-06-05": "gemma3", + "gemini-2.5-pro-preview-05-06": "gemma3", + "gemini-2.5-pro-exp-03-25": "gemma3", + "gemini-live-2.5-flash": "gemma3", + "gemini-2.5-flash-preview-05-20": "gemma3", + "gemini-2.5-flash-preview-04-17": "gemma3", + "gemini-2.5-flash-lite-preview-06-17": "gemma3", + "gemini-2.0-flash-001": "gemma3", + "gemini-2.0-flash-lite-001": "gemma3", + "gemini-3-pro-preview": "gemma3", +} + + +@dataclasses.dataclass(frozen=True) +class _TokenizerConfig: + model_url: str + model_hash: str + + +# TODO: update gemma3 tokenizer +_TOKENIZERS = { + "gemma2": _TokenizerConfig( + model_url="https://raw.githubusercontent.com/google/gemma_pytorch/33b652c465537c6158f9a472ea5700e5e770ad3f/tokenizer/tokenizer.model", + model_hash=( + "61a7b147390c64585d6c3543dd6fc636906c9af3865a5548f27f31aee1d4c8e2" + ), + ), + "gemma3": _TokenizerConfig( + model_url="https://raw.githubusercontent.com/google/gemma_pytorch/014acb7ac4563a5f77c76d7ff98f31b568c16508/tokenizer/gemma3_cleaned_262144_v2.spiece.model", + model_hash=( + "1299c11d7cf632ef3b4e11937501358ada021bbdf7c47638d13c0ee982f2e79c" + ), + ), +} + + +def _load_file(file_url_path: str) -> bytes: + """Loads file bytes from the given file url path.""" + resp = requests.get(file_url_path) + resp.raise_for_status() + return cast(bytes, resp.content) + + +def _is_valid_model(*, model_data: bytes, expected_hash: str) -> bool: + """Returns true if the content is valid by checking the hash.""" + if not expected_hash: + raise ValueError("expected_hash is required") + return hashlib.sha256(model_data).hexdigest() == expected_hash + + +def _maybe_remove_file(file_path: str) -> None: + """Removes the file if exists.""" + if not os.path.exists(file_path): + return + try: + os.remove(file_path) + except OSError: + # Don't raise if we cannot remove file. + pass + + +def _maybe_load_from_cache( + *, file_path: str, expected_hash: str +) -> Optional[bytes]: + """Loads the content from the cache path.""" + if not os.path.exists(file_path): + return None + with open(file_path, "rb") as f: + content = f.read() + if _is_valid_model(model_data=content, expected_hash=expected_hash): + return content + + # Cached file corrupted. + _maybe_remove_file(file_path) + return None + + +def _maybe_save_to_cache( + *, cache_dir: str, cache_path: str, content: bytes +) -> None: + """Saves the content to the cache path.""" + try: + os.makedirs(cache_dir, exist_ok=True) + tmp_path = cache_dir + "." + str(uuid.uuid4()) + ".tmp" + with open(tmp_path, "wb") as f: + f.write(content) + os.rename(tmp_path, cache_path) + except OSError: + # Don't raise if we cannot write file. + pass + + +def _load_from_url(*, file_url: str, expected_hash: str) -> bytes: + """Loads model bytes from the given file url.""" + content = _load_file(file_url) + if not _is_valid_model(model_data=content, expected_hash=expected_hash): + actual_hash = hashlib.sha256(content).hexdigest() + raise ValueError( + "Downloaded model file is corrupted." + f" Expected hash {expected_hash}. Got file hash {actual_hash}." + ) + return content + + +def _load(*, file_url: str, expected_hash: str) -> bytes: + """Loads model bytes from the given file url. + + 1. If the find local cached file for the given url and the cached file hash + matches the expected hash, the cached file is returned. + 2. If local cached file is not found or the hash does not match, the file is + downloaded from the given url. And write to local cache and return the + file bytes. + 3. If the file downloaded from the given url does not match the expected + hash, raise ValueError. + + Args: + file_url: The url of the file to load. + expected_hash: The expected hash of the file. + + Returns: + The file bytes. + """ + model_dir = os.path.join(tempfile.gettempdir(), "vertexai_tokenizer_model") + filename = hashlib.sha1(file_url.encode()).hexdigest() + model_path = os.path.join(model_dir, filename) + + model_data = _maybe_load_from_cache( + file_path=model_path, expected_hash=expected_hash + ) + if not model_data: + model_data = _load_from_url(file_url=file_url, expected_hash=expected_hash) + + _maybe_save_to_cache( + cache_dir=model_dir, cache_path=model_path, content=model_data + ) + return model_data + + +def _load_model_proto_bytes(tokenizer_name: str) -> bytes: + """Loads model proto bytes from the given tokenizer name.""" + if tokenizer_name not in _TOKENIZERS: + raise ValueError( + f"Tokenizer {tokenizer_name} is not supported." + f"Supported tokenizers: {list(_TOKENIZERS.keys())}" + ) + return _load( + file_url=_TOKENIZERS[tokenizer_name].model_url, + expected_hash=_TOKENIZERS[tokenizer_name].model_hash, + ) + + +@functools.lru_cache() +def load_model_proto( + tokenizer_name: str, +) -> sentencepiece_model_pb2.ModelProto: + """Loads model proto from the given tokenizer name.""" + model_proto = sentencepiece_model_pb2.ModelProto() + model_proto.ParseFromString(_load_model_proto_bytes(tokenizer_name)) + return model_proto + + +def get_tokenizer_name(model_name: str) -> str: + """Gets the tokenizer name for the given model name.""" + if model_name in _GEMINI_MODELS_TO_TOKENIZER_NAMES.keys(): + return _GEMINI_MODELS_TO_TOKENIZER_NAMES[model_name] + if model_name in _GEMINI_STABLE_MODELS_TO_TOKENIZER_NAMES.keys(): + return _GEMINI_STABLE_MODELS_TO_TOKENIZER_NAMES[model_name] + raise ValueError( + f"Model {model_name} is not supported. Supported models: {', '.join(_GEMINI_MODELS_TO_TOKENIZER_NAMES.keys())}, {', '.join(_GEMINI_STABLE_MODELS_TO_TOKENIZER_NAMES.keys())}.\n" # pylint: disable=line-too-long + ) + + +@functools.lru_cache() +def get_sentencepiece(tokenizer_name: str) -> spm.SentencePieceProcessor: + """Loads sentencepiece tokenizer from the given tokenizer name.""" + processor = spm.SentencePieceProcessor() + processor.LoadFromSerializedProto(_load_model_proto_bytes(tokenizer_name)) + return processor diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_mcp_utils.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_mcp_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..6cd632252d9056cc98192701cb884a820f8253a4 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_mcp_utils.py @@ -0,0 +1,117 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +"""Utils for working with MCP tools.""" + +from importlib.metadata import PackageNotFoundError, version +import typing +from typing import Any + +from . import _common +from . import types + +if typing.TYPE_CHECKING: + from mcp.types import Tool as McpTool + from mcp import ClientSession as McpClientSession +else: + McpClientSession: typing.Type = Any + McpTool: typing.Type = Any + try: + from mcp.types import Tool as McpTool + from mcp import ClientSession as McpClientSession + except ImportError: + McpTool = None + McpClientSession = None + + +def mcp_to_gemini_tool(tool: McpTool) -> types.Tool: + """Translates an MCP tool to a Google GenAI tool.""" + return types.Tool( + function_declarations=[{ + "name": tool.name, + "description": tool.description, + "parameters": types.Schema.from_json_schema( + json_schema=types.JSONSchema( + **_filter_to_supported_schema(tool.inputSchema) + ) + ), + }] + ) + + +def mcp_to_gemini_tools(tools: list[McpTool]) -> list[types.Tool]: + """Translates a list of MCP tools to a list of Google GenAI tools.""" + return [mcp_to_gemini_tool(tool) for tool in tools] + + +def has_mcp_tool_usage(tools: types.ToolListUnion) -> bool: + """Checks whether the list of tools contains any MCP tools or sessions.""" + if McpClientSession is None: + return False + for tool in tools: + if isinstance(tool, McpTool) or isinstance(tool, McpClientSession): + return True + return False + + +def has_mcp_session_usage(tools: types.ToolListUnion) -> bool: + """Checks whether the list of tools contains any MCP sessions.""" + if McpClientSession is None: + return False + for tool in tools: + if isinstance(tool, McpClientSession): + return True + return False + + +def set_mcp_usage_header(headers: dict[str, str]) -> None: + """Sets the MCP version label in the Google API client header.""" + if McpClientSession is None: + return + try: + version_label = version("mcp") + except PackageNotFoundError: + version_label = "0.0.0" + existing_header = headers.get("x-goog-api-client", "") + headers["x-goog-api-client"] = ( + existing_header + f" mcp_used/{version_label}" + ).lstrip() + + +def _filter_to_supported_schema( + schema: _common.StringDict, +) -> _common.StringDict: + """Filters the schema to only include fields that are supported by JSONSchema.""" + supported_fields: set[str] = set(types.JSONSchema.model_fields.keys()) + schema_field_names: tuple[str] = ("items",) # 'additional_properties' to come + list_schema_field_names: tuple[str] = ( + "any_of", # 'one_of', 'all_of', 'not' to come + ) + dict_schema_field_names: tuple[str] = ("properties",) # 'defs' to come + for field_name, field_value in schema.items(): + if field_name in schema_field_names: + schema[field_name] = _filter_to_supported_schema(field_value) + elif field_name in list_schema_field_names: + schema[field_name] = [ + _filter_to_supported_schema(value) for value in field_value + ] + elif field_name in dict_schema_field_names: + schema[field_name] = { + key: _filter_to_supported_schema(value) + for key, value in field_value.items() + } + return { + key: value for key, value in schema.items() if key in supported_fields + } diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_operations_converters.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_operations_converters.py new file mode 100644 index 0000000000000000000000000000000000000000..eb840baab9702a9912a6241265c0161bc54784e2 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_operations_converters.py @@ -0,0 +1,394 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# Code generated by the Google Gen AI SDK generator DO NOT EDIT. + +from typing import Any, Optional, Union +from . import _base_transformers as base_t +from ._common import get_value_by_path as getv +from ._common import set_value_by_path as setv + + +def _FetchPredictOperationParameters_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['operation_name']) is not None: + raise ValueError('operation_name parameter is not supported in Gemini API.') + + if getv(from_object, ['resource_name']) is not None: + raise ValueError('resource_name parameter is not supported in Gemini API.') + + if getv(from_object, ['config']) is not None: + raise ValueError('config parameter is not supported in Gemini API.') + + return to_object + + +def _FetchPredictOperationParameters_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['operation_name']) is not None: + setv(to_object, ['operationName'], getv(from_object, ['operation_name'])) + + if getv(from_object, ['resource_name']) is not None: + setv( + to_object, + ['_url', 'resourceName'], + getv(from_object, ['resource_name']), + ) + + return to_object + + +def _GenerateVideosOperation_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['name']) is not None: + setv(to_object, ['name'], getv(from_object, ['name'])) + + if getv(from_object, ['metadata']) is not None: + setv(to_object, ['metadata'], getv(from_object, ['metadata'])) + + if getv(from_object, ['done']) is not None: + setv(to_object, ['done'], getv(from_object, ['done'])) + + if getv(from_object, ['error']) is not None: + setv(to_object, ['error'], getv(from_object, ['error'])) + + if getv(from_object, ['response', 'generateVideoResponse']) is not None: + setv( + to_object, + ['response'], + _GenerateVideosResponse_from_mldev( + getv(from_object, ['response', 'generateVideoResponse']), to_object + ), + ) + + if getv(from_object, ['response', 'generateVideoResponse']) is not None: + setv( + to_object, + ['result'], + _GenerateVideosResponse_from_mldev( + getv(from_object, ['response', 'generateVideoResponse']), to_object + ), + ) + + return to_object + + +def _GenerateVideosOperation_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['name']) is not None: + setv(to_object, ['name'], getv(from_object, ['name'])) + + if getv(from_object, ['metadata']) is not None: + setv(to_object, ['metadata'], getv(from_object, ['metadata'])) + + if getv(from_object, ['done']) is not None: + setv(to_object, ['done'], getv(from_object, ['done'])) + + if getv(from_object, ['error']) is not None: + setv(to_object, ['error'], getv(from_object, ['error'])) + + if getv(from_object, ['response']) is not None: + setv( + to_object, + ['response'], + _GenerateVideosResponse_from_vertex( + getv(from_object, ['response']), to_object + ), + ) + + if getv(from_object, ['response']) is not None: + setv( + to_object, + ['result'], + _GenerateVideosResponse_from_vertex( + getv(from_object, ['response']), to_object + ), + ) + + return to_object + + +def _GenerateVideosResponse_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['generatedSamples']) is not None: + setv( + to_object, + ['generated_videos'], + [ + _GeneratedVideo_from_mldev(item, to_object) + for item in getv(from_object, ['generatedSamples']) + ], + ) + + if getv(from_object, ['raiMediaFilteredCount']) is not None: + setv( + to_object, + ['rai_media_filtered_count'], + getv(from_object, ['raiMediaFilteredCount']), + ) + + if getv(from_object, ['raiMediaFilteredReasons']) is not None: + setv( + to_object, + ['rai_media_filtered_reasons'], + getv(from_object, ['raiMediaFilteredReasons']), + ) + + return to_object + + +def _GenerateVideosResponse_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['videos']) is not None: + setv( + to_object, + ['generated_videos'], + [ + _GeneratedVideo_from_vertex(item, to_object) + for item in getv(from_object, ['videos']) + ], + ) + + if getv(from_object, ['raiMediaFilteredCount']) is not None: + setv( + to_object, + ['rai_media_filtered_count'], + getv(from_object, ['raiMediaFilteredCount']), + ) + + if getv(from_object, ['raiMediaFilteredReasons']) is not None: + setv( + to_object, + ['rai_media_filtered_reasons'], + getv(from_object, ['raiMediaFilteredReasons']), + ) + + return to_object + + +def _GeneratedVideo_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['video']) is not None: + setv( + to_object, + ['video'], + _Video_from_mldev(getv(from_object, ['video']), to_object), + ) + + return to_object + + +def _GeneratedVideo_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['_self']) is not None: + setv( + to_object, + ['video'], + _Video_from_vertex(getv(from_object, ['_self']), to_object), + ) + + return to_object + + +def _GetOperationParameters_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['operation_name']) is not None: + setv( + to_object, + ['_url', 'operationName'], + getv(from_object, ['operation_name']), + ) + + return to_object + + +def _GetOperationParameters_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['operation_name']) is not None: + setv( + to_object, + ['_url', 'operationName'], + getv(from_object, ['operation_name']), + ) + + return to_object + + +def _ImportFileOperation_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['name']) is not None: + setv(to_object, ['name'], getv(from_object, ['name'])) + + if getv(from_object, ['metadata']) is not None: + setv(to_object, ['metadata'], getv(from_object, ['metadata'])) + + if getv(from_object, ['done']) is not None: + setv(to_object, ['done'], getv(from_object, ['done'])) + + if getv(from_object, ['error']) is not None: + setv(to_object, ['error'], getv(from_object, ['error'])) + + if getv(from_object, ['response']) is not None: + setv( + to_object, + ['response'], + _ImportFileResponse_from_mldev( + getv(from_object, ['response']), to_object + ), + ) + + return to_object + + +def _ImportFileResponse_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['sdkHttpResponse']) is not None: + setv( + to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse']) + ) + + if getv(from_object, ['parent']) is not None: + setv(to_object, ['parent'], getv(from_object, ['parent'])) + + if getv(from_object, ['documentName']) is not None: + setv(to_object, ['document_name'], getv(from_object, ['documentName'])) + + return to_object + + +def _UploadToFileSearchStoreOperation_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['name']) is not None: + setv(to_object, ['name'], getv(from_object, ['name'])) + + if getv(from_object, ['metadata']) is not None: + setv(to_object, ['metadata'], getv(from_object, ['metadata'])) + + if getv(from_object, ['done']) is not None: + setv(to_object, ['done'], getv(from_object, ['done'])) + + if getv(from_object, ['error']) is not None: + setv(to_object, ['error'], getv(from_object, ['error'])) + + if getv(from_object, ['response']) is not None: + setv( + to_object, + ['response'], + _UploadToFileSearchStoreResponse_from_mldev( + getv(from_object, ['response']), to_object + ), + ) + + return to_object + + +def _UploadToFileSearchStoreResponse_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['sdkHttpResponse']) is not None: + setv( + to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse']) + ) + + if getv(from_object, ['parent']) is not None: + setv(to_object, ['parent'], getv(from_object, ['parent'])) + + if getv(from_object, ['documentName']) is not None: + setv(to_object, ['document_name'], getv(from_object, ['documentName'])) + + return to_object + + +def _Video_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['uri']) is not None: + setv(to_object, ['uri'], getv(from_object, ['uri'])) + + if getv(from_object, ['encodedVideo']) is not None: + setv( + to_object, + ['video_bytes'], + base_t.t_bytes(getv(from_object, ['encodedVideo'])), + ) + + if getv(from_object, ['encoding']) is not None: + setv(to_object, ['mime_type'], getv(from_object, ['encoding'])) + + return to_object + + +def _Video_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['gcsUri']) is not None: + setv(to_object, ['uri'], getv(from_object, ['gcsUri'])) + + if getv(from_object, ['bytesBase64Encoded']) is not None: + setv( + to_object, + ['video_bytes'], + base_t.t_bytes(getv(from_object, ['bytesBase64Encoded'])), + ) + + if getv(from_object, ['mimeType']) is not None: + setv(to_object, ['mime_type'], getv(from_object, ['mimeType'])) + + return to_object diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_replay_api_client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_replay_api_client.py new file mode 100644 index 0000000000000000000000000000000000000000..263cf2ac8ed1427a4a4e477509db60983f7949b3 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_replay_api_client.py @@ -0,0 +1,695 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +"""Replay API client.""" + +import base64 +import copy +import contextlib +import enum +import inspect +import io +import json +import os +import re +from typing import Any, Literal, Optional, Union, Iterator, AsyncIterator + +import google.auth + +from . import errors +from ._api_client import BaseApiClient +from ._api_client import HttpRequest +from ._api_client import HttpResponse +from ._common import BaseModel +from .types import HttpOptions, HttpOptionsOrDict + + +def to_snake_case(name: str) -> str: + """Converts a string from camelCase or PascalCase to snake_case.""" + + if not isinstance(name, str): + name = str(name) + s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) + return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() + + +def _normalize_json_case(obj: Any) -> Any: + if isinstance(obj, dict): + return { + to_snake_case(k): _normalize_json_case(v) + for k, v in obj.items() + } + elif isinstance(obj, list): + return [_normalize_json_case(item) for item in obj] + elif isinstance(obj, enum.Enum): + return obj.value + elif isinstance(obj, str): + # Python >= 3.14 has a new division by zero error message. + if 'division by zero' in obj: + return obj.replace( + 'division by zero', 'integer division or modulo by zero' + ) + return obj + + +def _equals_ignore_key_case(obj1: Any, obj2: Any) -> bool: + """Compares two Python objects for equality ignoring key casing. + + Returns: + bool: True if the two objects are equal regardless of key casing + (camelCase vs. snake_case). For example, the following are considered equal: + + {'my_key': 'my_value'} + {'myKey': 'my_value'} + + This also considers enums and strings with the same value as equal. + For example, the following are considered equal: + + {'type': }} + {'type': 'STRING'} + """ + + normalized_obj_1 = _normalize_json_case(obj1) + normalized_obj_2 = _normalize_json_case(obj2) + + if normalized_obj_1 == normalized_obj_2: + return True + else: + return False + + +def _redact_version_numbers(version_string: str) -> str: + """Redacts version numbers in the form x.y.z from a string.""" + return re.sub(r'\d+\.\d+\.\d+[a-zA-Z0-9]*', '{VERSION_NUMBER}', version_string) + + +def _redact_language_label(language_label: str) -> str: + """Removed because replay requests are used for all languages.""" + return re.sub(r'gl-python/', '{LANGUAGE_LABEL}/', language_label) + + +def _redact_request_headers(headers: dict[str, str]) -> dict[str, str]: + """Redacts headers that should not be recorded.""" + redacted_headers = {} + for header_name, header_value in headers.items(): + if header_name.lower() == 'x-goog-api-key': + redacted_headers[header_name] = '{REDACTED}' + elif header_name.lower() == 'user-agent': + redacted_headers[header_name] = _redact_language_label( + _redact_version_numbers(header_value) + ) + elif header_name.lower() == 'x-goog-api-client': + redacted_headers[header_name] = _redact_language_label( + _redact_version_numbers(header_value) + ) + elif header_name.lower() == 'x-goog-user-project': + continue + elif header_name.lower() == 'authorization': + continue + else: + redacted_headers[header_name] = header_value + return redacted_headers + + +def _redact_request_url(url: str) -> str: + # Redact all the url parts before the resource name, so the test can work + # against any project, location, version, or whether it's EasyGCP. + result = re.sub( + r'.*/projects/[^/]+/locations/[^/]+/', + '{VERTEX_URL_PREFIX}/', + url, + ) + result = re.sub( + r'.*-aiplatform.googleapis.com/[^/]+/', + '{VERTEX_URL_PREFIX}/', + result, + ) + result = re.sub( + r'.*aiplatform.googleapis.com/[^/]+/', + '{VERTEX_URL_PREFIX}/', + result, + ) + result = re.sub( + r'.*generativelanguage.*.googleapis.com/[^/]+', + '{MLDEV_URL_PREFIX}', + result, + ) + return result + + +def _redact_project_location_path(path: str) -> str: + # Redact a field in the request that is known to vary based on project and + # location. + if 'projects/' in path and 'locations/' in path: + result = re.sub( + r'projects/[^/]+/locations/[^/]+/', + '{PROJECT_AND_LOCATION_PATH}/', + path, + ) + return result + else: + return path + + +def _redact_request_body(body: Any) -> None: + """Redacts fields in the request body in place.""" + if isinstance(body, dict): + for key, value in body.items(): + if isinstance(value, str): + value = _redact_project_location_path(value) + value = re.sub( + r'[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}', + '{UUID}', + value, + ) + body[key] = value + elif isinstance(value, (dict, list)): + _redact_request_body(value) + elif isinstance(body, list): + for i, value in enumerate(body): + if isinstance(value, str): + value = _redact_project_location_path(value) + value = re.sub( + r'[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}', + '{UUID}', + value, + ) + body[i] = value + elif isinstance(value, (dict, list)): + _redact_request_body(value) + + +def redact_http_request(http_request: HttpRequest) -> None: + http_request.headers = _redact_request_headers(http_request.headers) + http_request.url = _redact_request_url(http_request.url) + if not isinstance(http_request.data, bytes): + _redact_request_body(http_request.data) + + +def _current_file_path_and_line() -> str: + """Prints the current file path and line number.""" + current_frame = inspect.currentframe() + if ( + current_frame is not None + and current_frame.f_back is not None + and current_frame.f_back.f_back is not None + ): + frame = current_frame.f_back.f_back + filepath = inspect.getfile(frame) + lineno = frame.f_lineno + return f'File: {filepath}, Line: {lineno}' + return '' + + +def _debug_print(message: str) -> None: + print( + 'DEBUG (test', + os.environ.get('PYTEST_CURRENT_TEST'), + ')', + _current_file_path_and_line(), + ':\n ', + message, + ) + + +def pop_undeterministic_headers(headers: dict[str, str]) -> None: + """Remove headers that are not deterministic.""" + headers.pop('Date', None) # pytype: disable=attribute-error + headers.pop('Server-Timing', None) # pytype: disable=attribute-error + + +@contextlib.contextmanager +def _record_on_api_error(client: 'ReplayApiClient', http_request: HttpRequest) -> Iterator[None]: + try: + yield + except errors.APIError as e: + client._record_interaction(http_request, e) + raise e + +@contextlib.asynccontextmanager +async def _async_record_on_api_error(client: 'ReplayApiClient', http_request: HttpRequest) -> AsyncIterator[None]: + try: + yield + except errors.APIError as e: + client._record_interaction(http_request, e) + raise e + +class ReplayRequest(BaseModel): + """Represents a single request in a replay.""" + + method: str + url: str + headers: dict[str, str] + body_segments: list[dict[str, object]] + + +class ReplayResponse(BaseModel): + """Represents a single response in a replay.""" + + status_code: int = 200 + headers: dict[str, str] + body_segments: list[dict[str, object]] + byte_segments: Optional[list[bytes]] = None + sdk_response_segments: list[dict[str, object]] + + def model_post_init(self, __context: Any) -> None: + pop_undeterministic_headers(self.headers) + + +class ReplayInteraction(BaseModel): + """Represents a single interaction, request and response in a replay.""" + + request: ReplayRequest + response: ReplayResponse + + +class ReplayFile(BaseModel): + """Represents a recorded session.""" + + replay_id: str + interactions: list[ReplayInteraction] + + +class ReplayApiClient(BaseApiClient): + """For integration testing, send recorded response or records a response.""" + + def __init__( + self, + mode: Literal['record', 'replay', 'auto', 'api'], + replay_id: str, + replays_directory: Optional[str] = None, + vertexai: bool = False, + api_key: Optional[str] = None, + credentials: Optional[google.auth.credentials.Credentials] = None, + project: Optional[str] = None, + location: Optional[str] = None, + http_options: Optional[HttpOptions] = None, + private: bool = False, + ): + super().__init__( + vertexai=vertexai, + api_key=api_key, + credentials=credentials, + project=project, + location=location, + http_options=http_options, + ) + self.replays_directory = replays_directory + if not self.replays_directory: + self.replays_directory = os.environ.get( + 'GOOGLE_GENAI_REPLAYS_DIRECTORY', None + ) + # Valid replay modes are replay-only or record-and-replay. + self.replay_session: Union[ReplayFile, None] = None + self._mode = mode + self._replay_id = replay_id + self._private = private + + def initialize_replay_session(self, replay_id: str) -> None: + self._replay_id = replay_id + self._initialize_replay_session() + + def _get_replay_file_path(self) -> str: + return self._generate_file_path_from_replay_id( + self.replays_directory, self._replay_id + ) + + def _should_call_api(self) -> bool: + return self._mode in ['record', 'api'] or ( + self._mode == 'auto' + and not os.path.isfile(self._get_replay_file_path()) + ) + + def _should_update_replay(self) -> bool: + return self._should_call_api() and self._mode != 'api' + + def _initialize_replay_session_if_not_loaded(self) -> None: + if not self.replay_session: + self._initialize_replay_session() + + def _initialize_replay_session(self) -> None: + _debug_print('Test is using replay id: ' + self._replay_id) + self._replay_index = 0 + self._sdk_response_index = 0 + replay_file_path = self._get_replay_file_path() + # This should not be triggered from the constructor. + replay_file_exists = os.path.isfile(replay_file_path) + if self._mode == 'replay' and not replay_file_exists: + raise ValueError( + 'Replay files do not exist for replay id: ' + self._replay_id + ) + + if self._mode in ['replay', 'auto'] and replay_file_exists: + with open(replay_file_path, 'r') as f: + self.replay_session = ReplayFile.model_validate(json.loads(f.read())) + + if self._should_update_replay(): + self.replay_session = ReplayFile( + replay_id=self._replay_id, interactions=[] + ) + + def _generate_file_path_from_replay_id(self, replay_directory: Optional[str], replay_id: str) -> str: + session_parts = replay_id.split('/') + if len(session_parts) < 3: + raise ValueError( + f'{replay_id}: Session ID must be in the format of' + ' module/function/[vertex|mldev]' + ) + if replay_directory is None: + path_parts = [] + else: + path_parts = [replay_directory] + path_parts.extend(session_parts) + return os.path.join(*path_parts) + '.json' + + def close(self) -> None: + if not self._should_update_replay() or not self.replay_session: + return + replay_file_path = self._get_replay_file_path() + os.makedirs(os.path.dirname(replay_file_path), exist_ok=True) + with open(replay_file_path, 'w') as f: + f.write(self.replay_session.model_dump_json(exclude_unset=True, indent=2)) + self.replay_session = None + + def _record_interaction( + self, + http_request: HttpRequest, + http_response: Union[HttpResponse, errors.APIError, bytes], + ) -> None: + if not self._should_update_replay(): + return + redact_http_request(http_request) + request = ReplayRequest( + method=http_request.method, + url=http_request.url, + headers=http_request.headers, + body_segments=[http_request.data], + ) + if isinstance(http_response, HttpResponse): + response = ReplayResponse( + headers=dict(http_response.headers), + body_segments=list(http_response.segments()), + byte_segments=[ + seg[:100] + b'...' for seg in http_response.byte_segments() + ], + status_code=http_response.status_code, + sdk_response_segments=[], + ) + elif isinstance(http_response, errors.APIError): + response = ReplayResponse( + headers=dict(http_response.response.headers), + body_segments=[http_response._to_replay_record()], + status_code=http_response.code, + sdk_response_segments=[], + ) + elif isinstance(http_response, bytes): + response = ReplayResponse( + headers={}, + body_segments=[], + byte_segments=[http_response], + sdk_response_segments=[], + ) + else: + raise ValueError( + 'Unsupported http_response type: ' + str(type(http_response)) + ) + if self.replay_session is None: + raise ValueError('No replay session found.') + self.replay_session.interactions.append( + ReplayInteraction(request=request, response=response) + ) + + def _match_request( + self, + http_request: HttpRequest, + interaction: ReplayInteraction, + ) -> None: + _debug_print(f'http_request.url: {http_request.url}') + _debug_print(f'interaction.request.url: {interaction.request.url}') + assert http_request.url == interaction.request.url + assert http_request.headers == interaction.request.headers, ( + 'Request headers mismatch:\n' + f'Actual: {http_request.headers}\n' + f'Expected: {interaction.request.headers}' + ) + assert http_request.method == interaction.request.method + + # Sanitize the request body, rewrite any fields that vary. + request_data_copy = copy.deepcopy(http_request.data) + # Both the request and recorded request must be redacted before comparing + # so that the comparison is fair. + if not isinstance(request_data_copy, bytes): + _redact_request_body(request_data_copy) + + actual_request_body = [request_data_copy] + expected_request_body = copy.deepcopy(interaction.request.body_segments) + for segment in expected_request_body: + if not isinstance(segment, bytes): + _redact_request_body(segment) + assert _equals_ignore_key_case(actual_request_body, expected_request_body), ( + 'Request body mismatch:\n' + f'Actual: {actual_request_body}\n' + f'Expected: {expected_request_body}' + ) + + def _build_response_from_replay(self, http_request: HttpRequest) -> HttpResponse: + redact_http_request(http_request) + + if self.replay_session is None: + raise ValueError('No replay session found.') + interaction = self.replay_session.interactions[self._replay_index] + # Replay is on the right side of the assert so the diff makes more sense. + self._match_request(http_request, interaction) + self._replay_index += 1 + self._sdk_response_index = 0 + errors.APIError.raise_for_response(interaction.response) + http_response = HttpResponse( + headers=interaction.response.headers, + response_stream=[ + json.dumps(segment) + for segment in interaction.response.body_segments + ], + byte_stream=interaction.response.byte_segments, + ) + if http_response.response_stream == ['{}']: + http_response.response_stream = [""] + return http_response + + def _verify_response(self, response_model: BaseModel) -> None: + if self._mode == 'api': + return + if not self.replay_session: + raise ValueError('No replay session found.') + # replay_index is advanced in _build_response_from_replay, so we need to -1. + interaction = self.replay_session.interactions[self._replay_index - 1] + if self._should_update_replay(): + if isinstance(response_model, list): + response_model = response_model[0] + sdk_response_response = getattr(response_model, 'sdk_http_response', None) + if response_model and ( + sdk_response_response is not None + ): + headers = getattr( + sdk_response_response, 'headers', None + ) + if headers: + pop_undeterministic_headers(headers) + interaction.response.sdk_response_segments.append( + response_model.model_dump(exclude_none=True) + ) + return + + if isinstance(response_model, list): + response_model = response_model[0] + _debug_print( + f'response_model: {response_model.model_dump(exclude_none=True)}' + ) + actual = response_model.model_dump(exclude_none=True, mode='json') + expected = interaction.response.sdk_response_segments[ + self._sdk_response_index + ] + # The sdk_http_response.body has format in the string, need to get rid of + # the format information before comparing. + if isinstance(expected, dict): + if 'sdk_http_response' in expected and isinstance( + expected['sdk_http_response'], dict + ): + if 'body' in expected['sdk_http_response']: + raw_body = expected['sdk_http_response']['body'] + _debug_print(f'raw_body length: {len(raw_body)}') + _debug_print(f'raw_body: {raw_body}') + if isinstance(raw_body, str) and raw_body != '': + raw_body = json.loads(raw_body) + raw_body = json.dumps(raw_body) + expected['sdk_http_response']['body'] = raw_body + if not self._private: + assert ( + actual == expected + ), f'SDK response mismatch:\nActual: {actual}\nExpected: {expected}' + else: + _debug_print(f'Expected SDK response mismatch:\nActual: {actual}\nExpected: {expected}') + self._sdk_response_index += 1 + + def _request( + self, + http_request: HttpRequest, + http_options: Optional[HttpOptionsOrDict] = None, + stream: bool = False, + ) -> HttpResponse: + self._initialize_replay_session_if_not_loaded() + if self._should_call_api(): + _debug_print('api mode request: %s' % http_request) + with _record_on_api_error(self, http_request): + result = super()._request(http_request, http_options, stream) + if stream: + result_segments = [] + for segment in result.segments(): + result_segments.append(json.dumps(segment)) + result = HttpResponse(result.headers, result_segments) + self._record_interaction(http_request, result) + # Need to return a RecordedResponse that rebuilds the response + # segments since the stream has been consumed. + else: + self._record_interaction(http_request, result) + _debug_print('api mode result: %s' % result.json) + return result + else: + return self._build_response_from_replay(http_request) + + async def _async_request( + self, + http_request: HttpRequest, + http_options: Optional[HttpOptionsOrDict] = None, + stream: bool = False, + ) -> HttpResponse: + self._initialize_replay_session_if_not_loaded() + if self._should_call_api(): + _debug_print('api mode request: %s' % http_request) + async with _async_record_on_api_error(self, http_request): + result = await super()._async_request( + http_request, http_options, stream + ) + if stream: + result_segments = [] + async for segment in result.async_segments(): + result_segments.append(json.dumps(segment)) + result = HttpResponse(result.headers, result_segments) + self._record_interaction(http_request, result) + # Need to return a RecordedResponse that rebuilds the response + # segments since the stream has been consumed. + else: + self._record_interaction(http_request, result) + _debug_print('api mode result: %s' % result.json) + return result + else: + return self._build_response_from_replay(http_request) + + def upload_file( + self, + file_path: Union[str, io.IOBase], + upload_url: str, + upload_size: int, + *, + http_options: Optional[HttpOptionsOrDict] = None, + ) -> HttpResponse: + if isinstance(file_path, io.IOBase): + offset = file_path.tell() + content = file_path.read() + file_path.seek(offset, os.SEEK_SET) + request = HttpRequest( + method='POST', + url='', + data={'bytes': base64.b64encode(content).decode('utf-8')}, + headers={} + ) + else: + request = HttpRequest( + method='POST', url='', data={'file_path': file_path}, headers={} + ) + if self._should_call_api(): + result: Union[str, HttpResponse] + with _record_on_api_error(self, request): + result = super().upload_file( + file_path, upload_url, upload_size, http_options=http_options + ) + self._record_interaction(request, result) + return result + else: + return self._build_response_from_replay(request) + + async def async_upload_file( + self, + file_path: Union[str, io.IOBase], + upload_url: str, + upload_size: int, + *, + http_options: Optional[HttpOptionsOrDict] = None, + ) -> HttpResponse: + if isinstance(file_path, io.IOBase): + offset = file_path.tell() + content = file_path.read() + file_path.seek(offset, os.SEEK_SET) + request = HttpRequest( + method='POST', + url='', + data={'bytes': base64.b64encode(content).decode('utf-8')}, + headers={}, + ) + else: + request = HttpRequest( + method='POST', url='', data={'file_path': file_path}, headers={} + ) + if self._should_call_api(): + result: HttpResponse + async with _async_record_on_api_error(self, request): + result = await super().async_upload_file( + file_path, upload_url, upload_size, http_options=http_options + ) + self._record_interaction(request, result) + return result + else: + return self._build_response_from_replay(request) + + def download_file( + self, path: str, *, http_options: Optional[HttpOptionsOrDict] = None + ) -> Union[HttpResponse, bytes, Any]: + self._initialize_replay_session_if_not_loaded() + request = self._build_request( + 'get', path=path, request_dict={}, http_options=http_options + ) + if self._should_call_api(): + with _record_on_api_error(self, request): + result = super().download_file(path, http_options=http_options) + self._record_interaction(request, result) + return result + else: + return self._build_response_from_replay(request).byte_stream[0] + + async def async_download_file( + self, path: str, *, http_options: Optional[HttpOptionsOrDict] = None + ) -> Any: + self._initialize_replay_session_if_not_loaded() + request = self._build_request( + 'get', path=path, request_dict={}, http_options=http_options + ) + if self._should_call_api(): + async with _async_record_on_api_error(self, request): + result = await super().async_download_file( + path, http_options=http_options + ) + self._record_interaction(request, result) + return result + else: + return self._build_response_from_replay(request).byte_stream[0] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_test_api_client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_test_api_client.py new file mode 100644 index 0000000000000000000000000000000000000000..accc4ff579a04aad3b7be0a60d543802f38935cc --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_test_api_client.py @@ -0,0 +1,149 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +import asyncio +import time +from unittest.mock import MagicMock, patch +import pytest +from .api_client import BaseApiClient + + +@patch('genai.api_client.BaseApiClient._build_request') +@patch('genai.api_client.BaseApiClient._request') +def test_request_streamed_non_blocking(mock_request, mock_build_request): + api_client = BaseApiClient(api_key='test_api_key') + http_method = 'GET' + path = 'test/path' + request_dict = {'key': 'value'} + + mock_http_request = MagicMock() + mock_build_request.return_value = mock_http_request + + def delayed_segments(): + chunks = ['{"chunk": 1}', '{"chunk": 2}', '{"chunk": 3}'] + for chunk in chunks: + time.sleep(0.1) # 100ms delay + yield chunk + + mock_response = MagicMock() + mock_response.segments.side_effect = delayed_segments + mock_request.return_value = mock_response + + chunks = [] + start_time = time.time() + for chunk in api_client.request_streamed(http_method, path, request_dict): + chunks.append(chunk) + assert len(chunks) <= 3 + end_time = time.time() + + mock_build_request.assert_called_once_with( + http_method, path, request_dict, None + ) + mock_request.assert_called_once_with(mock_http_request, stream=True) + assert chunks == ['{"chunk": 1}', '{"chunk": 2}', '{"chunk": 3}'] + assert end_time - start_time > 0.3 + + +@patch('genai.api_client.BaseApiClient._build_request') +@patch('genai.api_client.BaseApiClient._async_request') +@pytest.mark.asyncio +async def test_async_request(mock_async_request, mock_build_request): + api_client = ApiClient(api_key='test_api_key') + http_method = 'GET' + path = 'test/path' + request_dict = {'key': 'value'} + + mock_http_request = MagicMock() + mock_build_request.return_value = mock_http_request + + class MockResponse: + + def __init__(self, text): + self.text = text + + async def delayed_response(http_request, stream): + await asyncio.sleep(0.1) # 100ms delay + return MockResponse('value') + + mock_async_request.side_effect = delayed_response + + async_coroutine1 = api_client.async_request(http_method, path, request_dict) + async_coroutine2 = api_client.async_request(http_method, path, request_dict) + async_coroutine3 = api_client.async_request(http_method, path, request_dict) + + start_time = time.time() + results = await asyncio.gather( + async_coroutine1, async_coroutine2, async_coroutine3 + ) + end_time = time.time() + + mock_build_request.assert_called_with(http_method, path, request_dict, None) + assert mock_build_request.call_count == 3 + mock_async_request.assert_called_with( + http_request=mock_http_request, stream=False + ) + assert mock_async_request.call_count == 3 + assert results == ['value', 'value', 'value'] + assert 0.1 <= end_time - start_time < 0.15 + + +@patch('genai.api_client.BaseApiClient._build_request') +@patch('genai.api_client.BaseApiClient._async_request') +@pytest.mark.asyncio +async def test_async_request_streamed_non_blocking( + mock_async_request, mock_build_request +): + api_client = ApiClient(api_key='test_api_key') + http_method = 'GET' + path = 'test/path' + request_dict = {'key': 'value'} + + mock_http_request = MagicMock() + mock_build_request.return_value = mock_http_request + + class MockResponse: + + def __init__(self, segments): + self._segments = segments + + # should mock async generator here but source code combines sync and async streaming in one segment method. + # TODO: fix the above + def segments(self): + for segment in self._segments: + time.sleep(0.1) # 100ms delay + yield segment + + async def delayed_response(http_request, stream): + return MockResponse(['{"chunk": 1}', '{"chunk": 2}', '{"chunk": 3}']) + + mock_async_request.side_effect = delayed_response + + chunks = [] + start_time = time.time() + async for chunk in await api_client.async_request_streamed( + http_method, path, request_dict + ): + chunks.append(chunk) + assert len(chunks) <= 3 + end_time = time.time() + + mock_build_request.assert_called_once_with( + http_method, path, request_dict, None + ) + mock_async_request.assert_called_once_with( + http_request=mock_http_request, stream=True + ) + assert chunks == ['{"chunk": 1}', '{"chunk": 2}', '{"chunk": 3}'] + assert end_time - start_time > 0.3 diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_tokens_converters.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_tokens_converters.py new file mode 100644 index 0000000000000000000000000000000000000000..aeea70d204e951d6fb71e0d059ca119ef58641fe --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_tokens_converters.py @@ -0,0 +1,643 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# Code generated by the Google Gen AI SDK generator DO NOT EDIT. + +from typing import Any, Optional, Union + +from . import _transformers as t +from ._api_client import BaseApiClient +from ._common import get_value_by_path as getv +from ._common import set_value_by_path as setv + + +def _AudioTranscriptionConfig_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['language_codes']) is not None: + raise ValueError('language_codes parameter is not supported in Gemini API.') + + return to_object + + +def _AuthConfig_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['api_key']) is not None: + setv(to_object, ['apiKey'], getv(from_object, ['api_key'])) + + if getv(from_object, ['api_key_config']) is not None: + raise ValueError('api_key_config parameter is not supported in Gemini API.') + + if getv(from_object, ['auth_type']) is not None: + raise ValueError('auth_type parameter is not supported in Gemini API.') + + if getv(from_object, ['google_service_account_config']) is not None: + raise ValueError( + 'google_service_account_config parameter is not supported in Gemini' + ' API.' + ) + + if getv(from_object, ['http_basic_auth_config']) is not None: + raise ValueError( + 'http_basic_auth_config parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['oauth_config']) is not None: + raise ValueError('oauth_config parameter is not supported in Gemini API.') + + if getv(from_object, ['oidc_config']) is not None: + raise ValueError('oidc_config parameter is not supported in Gemini API.') + + return to_object + + +def _Blob_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['data']) is not None: + setv(to_object, ['data'], getv(from_object, ['data'])) + + if getv(from_object, ['display_name']) is not None: + raise ValueError('display_name parameter is not supported in Gemini API.') + + if getv(from_object, ['mime_type']) is not None: + setv(to_object, ['mimeType'], getv(from_object, ['mime_type'])) + + return to_object + + +def _Content_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['parts']) is not None: + setv( + to_object, + ['parts'], + [ + _Part_to_mldev(item, to_object) + for item in getv(from_object, ['parts']) + ], + ) + + if getv(from_object, ['role']) is not None: + setv(to_object, ['role'], getv(from_object, ['role'])) + + return to_object + + +def _CreateAuthTokenConfig_to_mldev( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['expire_time']) is not None: + setv(parent_object, ['expireTime'], getv(from_object, ['expire_time'])) + + if getv(from_object, ['new_session_expire_time']) is not None: + setv( + parent_object, + ['newSessionExpireTime'], + getv(from_object, ['new_session_expire_time']), + ) + + if getv(from_object, ['uses']) is not None: + setv(parent_object, ['uses'], getv(from_object, ['uses'])) + + if getv(from_object, ['live_connect_constraints']) is not None: + setv( + parent_object, + ['bidiGenerateContentSetup'], + _LiveConnectConstraints_to_mldev( + api_client, + getv(from_object, ['live_connect_constraints']), + to_object, + ), + ) + + if getv(from_object, ['lock_additional_fields']) is not None: + setv( + parent_object, + ['fieldMask'], + getv(from_object, ['lock_additional_fields']), + ) + + return to_object + + +def _CreateAuthTokenParameters_to_mldev( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['config']) is not None: + setv( + to_object, + ['config'], + _CreateAuthTokenConfig_to_mldev( + api_client, getv(from_object, ['config']), to_object + ), + ) + + return to_object + + +def _CreateAuthTokenParameters_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['config']) is not None: + raise ValueError('config parameter is not supported in Vertex AI.') + + return to_object + + +def _FileData_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['display_name']) is not None: + raise ValueError('display_name parameter is not supported in Gemini API.') + + if getv(from_object, ['file_uri']) is not None: + setv(to_object, ['fileUri'], getv(from_object, ['file_uri'])) + + if getv(from_object, ['mime_type']) is not None: + setv(to_object, ['mimeType'], getv(from_object, ['mime_type'])) + + return to_object + + +def _FunctionCall_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['id']) is not None: + setv(to_object, ['id'], getv(from_object, ['id'])) + + if getv(from_object, ['args']) is not None: + setv(to_object, ['args'], getv(from_object, ['args'])) + + if getv(from_object, ['name']) is not None: + setv(to_object, ['name'], getv(from_object, ['name'])) + + if getv(from_object, ['partial_args']) is not None: + raise ValueError('partial_args parameter is not supported in Gemini API.') + + if getv(from_object, ['will_continue']) is not None: + raise ValueError('will_continue parameter is not supported in Gemini API.') + + return to_object + + +def _GoogleMaps_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['auth_config']) is not None: + setv( + to_object, + ['authConfig'], + _AuthConfig_to_mldev(getv(from_object, ['auth_config']), to_object), + ) + + if getv(from_object, ['enable_widget']) is not None: + setv(to_object, ['enableWidget'], getv(from_object, ['enable_widget'])) + + return to_object + + +def _GoogleSearch_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['search_types']) is not None: + setv(to_object, ['searchTypes'], getv(from_object, ['search_types'])) + + if getv(from_object, ['blocking_confidence']) is not None: + raise ValueError( + 'blocking_confidence parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['exclude_domains']) is not None: + raise ValueError( + 'exclude_domains parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['time_range_filter']) is not None: + setv( + to_object, ['timeRangeFilter'], getv(from_object, ['time_range_filter']) + ) + + return to_object + + +def _LiveConnectConfig_to_mldev( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['generation_config']) is not None: + setv( + parent_object, + ['setup', 'generationConfig'], + getv(from_object, ['generation_config']), + ) + + if getv(from_object, ['response_modalities']) is not None: + setv( + parent_object, + ['setup', 'generationConfig', 'responseModalities'], + getv(from_object, ['response_modalities']), + ) + + if getv(from_object, ['temperature']) is not None: + setv( + parent_object, + ['setup', 'generationConfig', 'temperature'], + getv(from_object, ['temperature']), + ) + + if getv(from_object, ['top_p']) is not None: + setv( + parent_object, + ['setup', 'generationConfig', 'topP'], + getv(from_object, ['top_p']), + ) + + if getv(from_object, ['top_k']) is not None: + setv( + parent_object, + ['setup', 'generationConfig', 'topK'], + getv(from_object, ['top_k']), + ) + + if getv(from_object, ['max_output_tokens']) is not None: + setv( + parent_object, + ['setup', 'generationConfig', 'maxOutputTokens'], + getv(from_object, ['max_output_tokens']), + ) + + if getv(from_object, ['media_resolution']) is not None: + setv( + parent_object, + ['setup', 'generationConfig', 'mediaResolution'], + getv(from_object, ['media_resolution']), + ) + + if getv(from_object, ['seed']) is not None: + setv( + parent_object, + ['setup', 'generationConfig', 'seed'], + getv(from_object, ['seed']), + ) + + if getv(from_object, ['speech_config']) is not None: + setv( + parent_object, + ['setup', 'generationConfig', 'speechConfig'], + t.t_live_speech_config(getv(from_object, ['speech_config'])), + ) + + if getv(from_object, ['thinking_config']) is not None: + setv( + parent_object, + ['setup', 'generationConfig', 'thinkingConfig'], + getv(from_object, ['thinking_config']), + ) + + if getv(from_object, ['enable_affective_dialog']) is not None: + setv( + parent_object, + ['setup', 'generationConfig', 'enableAffectiveDialog'], + getv(from_object, ['enable_affective_dialog']), + ) + + if getv(from_object, ['system_instruction']) is not None: + setv( + parent_object, + ['setup', 'systemInstruction'], + _Content_to_mldev( + t.t_content(getv(from_object, ['system_instruction'])), to_object + ), + ) + + if getv(from_object, ['tools']) is not None: + setv( + parent_object, + ['setup', 'tools'], + [ + _Tool_to_mldev(t.t_tool(api_client, item), to_object) + for item in t.t_tools(api_client, getv(from_object, ['tools'])) + ], + ) + + if getv(from_object, ['session_resumption']) is not None: + setv( + parent_object, + ['setup', 'sessionResumption'], + _SessionResumptionConfig_to_mldev( + getv(from_object, ['session_resumption']), to_object + ), + ) + + if getv(from_object, ['input_audio_transcription']) is not None: + setv( + parent_object, + ['setup', 'inputAudioTranscription'], + _AudioTranscriptionConfig_to_mldev( + getv(from_object, ['input_audio_transcription']), to_object + ), + ) + + if getv(from_object, ['output_audio_transcription']) is not None: + setv( + parent_object, + ['setup', 'outputAudioTranscription'], + _AudioTranscriptionConfig_to_mldev( + getv(from_object, ['output_audio_transcription']), to_object + ), + ) + + if getv(from_object, ['realtime_input_config']) is not None: + setv( + parent_object, + ['setup', 'realtimeInputConfig'], + getv(from_object, ['realtime_input_config']), + ) + + if getv(from_object, ['context_window_compression']) is not None: + setv( + parent_object, + ['setup', 'contextWindowCompression'], + getv(from_object, ['context_window_compression']), + ) + + if getv(from_object, ['proactivity']) is not None: + setv( + parent_object, + ['setup', 'proactivity'], + getv(from_object, ['proactivity']), + ) + + if getv(from_object, ['explicit_vad_signal']) is not None: + raise ValueError( + 'explicit_vad_signal parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['history_config']) is not None: + setv( + parent_object, + ['setup', 'historyConfig'], + getv(from_object, ['history_config']), + ) + + if getv(from_object, ['avatar_config']) is not None: + setv( + parent_object, + ['setup', 'avatarConfig'], + getv(from_object, ['avatar_config']), + ) + + if getv(from_object, ['safety_settings']) is not None: + setv( + parent_object, + ['setup', 'safetySettings'], + [ + _SafetySetting_to_mldev(item, to_object) + for item in getv(from_object, ['safety_settings']) + ], + ) + + return to_object + + +def _LiveConnectConstraints_to_mldev( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['model']) is not None: + setv( + to_object, + ['setup', 'model'], + t.t_model(api_client, getv(from_object, ['model'])), + ) + + if getv(from_object, ['config']) is not None: + setv( + to_object, + ['config'], + _LiveConnectConfig_to_mldev( + api_client, getv(from_object, ['config']), to_object + ), + ) + + return to_object + + +def _Part_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['media_resolution']) is not None: + setv( + to_object, ['mediaResolution'], getv(from_object, ['media_resolution']) + ) + + if getv(from_object, ['code_execution_result']) is not None: + setv( + to_object, + ['codeExecutionResult'], + getv(from_object, ['code_execution_result']), + ) + + if getv(from_object, ['executable_code']) is not None: + setv(to_object, ['executableCode'], getv(from_object, ['executable_code'])) + + if getv(from_object, ['file_data']) is not None: + setv( + to_object, + ['fileData'], + _FileData_to_mldev(getv(from_object, ['file_data']), to_object), + ) + + if getv(from_object, ['function_call']) is not None: + setv( + to_object, + ['functionCall'], + _FunctionCall_to_mldev(getv(from_object, ['function_call']), to_object), + ) + + if getv(from_object, ['function_response']) is not None: + setv( + to_object, + ['functionResponse'], + getv(from_object, ['function_response']), + ) + + if getv(from_object, ['inline_data']) is not None: + setv( + to_object, + ['inlineData'], + _Blob_to_mldev(getv(from_object, ['inline_data']), to_object), + ) + + if getv(from_object, ['text']) is not None: + setv(to_object, ['text'], getv(from_object, ['text'])) + + if getv(from_object, ['thought']) is not None: + setv(to_object, ['thought'], getv(from_object, ['thought'])) + + if getv(from_object, ['thought_signature']) is not None: + setv( + to_object, + ['thoughtSignature'], + getv(from_object, ['thought_signature']), + ) + + if getv(from_object, ['video_metadata']) is not None: + setv(to_object, ['videoMetadata'], getv(from_object, ['video_metadata'])) + + if getv(from_object, ['tool_call']) is not None: + setv(to_object, ['toolCall'], getv(from_object, ['tool_call'])) + + if getv(from_object, ['tool_response']) is not None: + setv(to_object, ['toolResponse'], getv(from_object, ['tool_response'])) + + if getv(from_object, ['part_metadata']) is not None: + setv(to_object, ['partMetadata'], getv(from_object, ['part_metadata'])) + + return to_object + + +def _SafetySetting_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['category']) is not None: + setv(to_object, ['category'], getv(from_object, ['category'])) + + if getv(from_object, ['method']) is not None: + raise ValueError('method parameter is not supported in Gemini API.') + + if getv(from_object, ['threshold']) is not None: + setv(to_object, ['threshold'], getv(from_object, ['threshold'])) + + return to_object + + +def _SessionResumptionConfig_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['handle']) is not None: + setv(to_object, ['handle'], getv(from_object, ['handle'])) + + if getv(from_object, ['transparent']) is not None: + raise ValueError('transparent parameter is not supported in Gemini API.') + + return to_object + + +def _Tool_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['retrieval']) is not None: + raise ValueError('retrieval parameter is not supported in Gemini API.') + + if getv(from_object, ['computer_use']) is not None: + setv(to_object, ['computerUse'], getv(from_object, ['computer_use'])) + + if getv(from_object, ['file_search']) is not None: + setv(to_object, ['fileSearch'], getv(from_object, ['file_search'])) + + if getv(from_object, ['google_search']) is not None: + setv( + to_object, + ['googleSearch'], + _GoogleSearch_to_mldev(getv(from_object, ['google_search']), to_object), + ) + + if getv(from_object, ['google_maps']) is not None: + setv( + to_object, + ['googleMaps'], + _GoogleMaps_to_mldev(getv(from_object, ['google_maps']), to_object), + ) + + if getv(from_object, ['code_execution']) is not None: + setv(to_object, ['codeExecution'], getv(from_object, ['code_execution'])) + + if getv(from_object, ['enterprise_web_search']) is not None: + raise ValueError( + 'enterprise_web_search parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['function_declarations']) is not None: + setv( + to_object, + ['functionDeclarations'], + [item for item in getv(from_object, ['function_declarations'])], + ) + + if getv(from_object, ['google_search_retrieval']) is not None: + setv( + to_object, + ['googleSearchRetrieval'], + getv(from_object, ['google_search_retrieval']), + ) + + if getv(from_object, ['parallel_ai_search']) is not None: + raise ValueError( + 'parallel_ai_search parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['url_context']) is not None: + setv(to_object, ['urlContext'], getv(from_object, ['url_context'])) + + if getv(from_object, ['mcp_servers']) is not None: + setv( + to_object, + ['mcpServers'], + [item for item in getv(from_object, ['mcp_servers'])], + ) + + return to_object diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_transformers.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_transformers.py new file mode 100644 index 0000000000000000000000000000000000000000..b9867d3e6969d6f98bd92c09d87f081a6fde8800 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/_transformers.py @@ -0,0 +1,1382 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +"""Transformers for Google GenAI SDK.""" + +import base64 +from collections.abc import Iterable, Mapping +from enum import Enum, EnumMeta +import inspect +import io +import logging +import re +import sys +import time +import types as builtin_types +import typing +from typing import Any, GenericAlias, List, Optional, Sequence, Union # type: ignore[attr-defined] +from ._mcp_utils import mcp_to_gemini_tool +from ._common import get_value_by_path as getv +from ._common import is_duck_type_of + +if typing.TYPE_CHECKING: + import PIL.Image + +import pydantic + +from . import _api_client +from . import _common +from . import types + +logger = logging.getLogger('google_genai._transformers') + +if sys.version_info >= (3, 10): + VersionedUnionType = builtin_types.UnionType + _UNION_TYPES = (typing.Union, builtin_types.UnionType) + from typing import TypeGuard +else: + VersionedUnionType = typing._UnionGenericAlias # type: ignore[attr-defined] + _UNION_TYPES = (typing.Union,) + from typing_extensions import TypeGuard + +if typing.TYPE_CHECKING: + from mcp import ClientSession as McpClientSession + from mcp.types import Tool as McpTool +else: + McpClientSession: typing.Type = Any + McpTool: typing.Type = Any + try: + from mcp import ClientSession as McpClientSession + from mcp.types import Tool as McpTool + except ImportError: + McpClientSession = None + McpTool = None + + +metric_name_sdk_api_map = { + 'exact_match': 'exactMatchSpec', + 'bleu': 'bleuSpec', + 'rouge_spec': 'rougeSpec', +} +metric_name_api_sdk_map = {v: k for k, v in metric_name_sdk_api_map.items()} + + +def _resource_name( + client: _api_client.BaseApiClient, + resource_name: str, + *, + collection_identifier: str, + collection_hierarchy_depth: int = 2, +) -> str: + # pylint: disable=line-too-long + """Prepends resource name with project, location, collection_identifier if needed. + + The collection_identifier will only be prepended if it's not present + and the prepending won't violate the collection hierarchy depth. + When the prepending condition doesn't meet, returns the input + resource_name. + + Args: + client: The API client. + resource_name: The user input resource name to be completed. + collection_identifier: The collection identifier to be prepended. See + collection identifiers in https://google.aip.dev/122. + collection_hierarchy_depth: The collection hierarchy depth. Only set this + field when the resource has nested collections. For example, + `users/vhugo1802/events/birthday-dinner-226`, the collection_identifier is + `users` and collection_hierarchy_depth is 4. See nested collections in + https://google.aip.dev/122. + + Example: + + resource_name = 'cachedContents/123' + client.vertexai = True + client.project = 'bar' + client.location = 'us-west1' + _resource_name(client, 'cachedContents/123', + collection_identifier='cachedContents') + returns: 'projects/bar/locations/us-west1/cachedContents/123' + + Example: + + resource_name = 'projects/foo/locations/us-central1/cachedContents/123' + # resource_name = 'locations/us-central1/cachedContents/123' + client.vertexai = True + client.project = 'bar' + client.location = 'us-west1' + _resource_name(client, resource_name, + collection_identifier='cachedContents') + returns: 'projects/foo/locations/us-central1/cachedContents/123' + + Example: + + resource_name = '123' + # resource_name = 'cachedContents/123' + client.vertexai = False + _resource_name(client, resource_name, + collection_identifier='cachedContents') + returns 'cachedContents/123' + + Example: + resource_name = 'some/wrong/cachedContents/resource/name/123' + resource_prefix = 'cachedContents' + client.vertexai = False + # client.vertexai = True + _resource_name(client, resource_name, + collection_identifier='cachedContents') + returns: 'some/wrong/cachedContents/resource/name/123' + + Returns: + The completed resource name. + """ + should_prepend_collection_identifier = ( + not resource_name.startswith(f'{collection_identifier}/') + # Check if prepending the collection identifier won't violate the + # collection hierarchy depth. + and f'{collection_identifier}/{resource_name}'.count('/') + 1 + == collection_hierarchy_depth + ) + if client.vertexai: + if resource_name.startswith('projects/'): + return resource_name + elif resource_name.startswith('locations/'): + return f'projects/{client.project}/{resource_name}' + elif resource_name.startswith(f'{collection_identifier}/'): + return f'projects/{client.project}/locations/{client.location}/{resource_name}' + elif should_prepend_collection_identifier: + return f'projects/{client.project}/locations/{client.location}/{collection_identifier}/{resource_name}' + else: + return resource_name + else: + if should_prepend_collection_identifier: + return f'{collection_identifier}/{resource_name}' + else: + return resource_name + + +def t_model(client: _api_client.BaseApiClient, model: str) -> str: + if not model: + raise ValueError('model is required.') + if '..' in model or '?' in model or '&' in model: + raise ValueError('invalid model parameter.') + if client.vertexai: + if ( + model.startswith('projects/') + or model.startswith('models/') + or model.startswith('publishers/') + ): + return model + elif '/' in model: + publisher, model_id = model.split('/', 1) + return f'publishers/{publisher}/models/{model_id}' + else: + return f'publishers/google/models/{model}' + else: + if model.startswith('models/'): + return model + elif model.startswith('tunedModels/'): + return model + else: + return f'models/{model}' + + +def t_models_url( + api_client: _api_client.BaseApiClient, base_models: bool +) -> str: + if api_client.vertexai: + if base_models: + return 'publishers/google/models' + else: + return 'models' + else: + if base_models: + return 'models' + else: + return 'tunedModels' + + +def t_extract_models( + response: _common.StringDict, +) -> list[_common.StringDict]: + if not response: + return [] + + models: Optional[list[_common.StringDict]] = response.get('models') + if models is not None: + return models + + tuned_models: Optional[list[_common.StringDict]] = response.get('tunedModels') + if tuned_models is not None: + return tuned_models + + publisher_models: Optional[list[_common.StringDict]] = response.get( + 'publisherModels' + ) + if publisher_models is not None: + return publisher_models + + if ( + response.get('httpHeaders') is not None + and response.get('jsonPayload') is None + ): + return [] + else: + logger.warning('Cannot determine the models type.') + logger.debug('Cannot determine the models type for response: %s', response) + return [] + + +def t_caches_model( + api_client: _api_client.BaseApiClient, model: str +) -> Optional[str]: + model = t_model(api_client, model) + if not model: + return None + if model.startswith('publishers/') and api_client.vertexai: + # vertex caches only support model name start with projects. + return ( + f'projects/{api_client.project}/locations/{api_client.location}/{model}' + ) + elif model.startswith('models/') and api_client.vertexai: + return f'projects/{api_client.project}/locations/{api_client.location}/publishers/google/{model}' + else: + return model + + +def pil_to_blob(image: Any) -> types.Blob: + image_format = 'PNG' + save_params: dict[str, Any] = dict() + if ( + image.format == 'JPEG' + and getattr(image, 'filename', '') + and image.mode in ['1', 'L', 'RGB', 'RGBX', 'CMYK'] + ): + image_format = 'JPEG' + save_params.update(quality='keep') + + image_io = io.BytesIO() + image.save(image_io, image_format, **save_params) + image_bytes = image_io.getvalue() + mime_type = f'image/{image_format.lower()}' + + return types.Blob(data=image_bytes, mime_type=mime_type) + + +def t_function_response( + function_response: types.FunctionResponseOrDict, +) -> types.FunctionResponse: + if not function_response: + raise ValueError('function_response is required.') + if isinstance(function_response, dict): + return types.FunctionResponse.model_validate(function_response) + elif is_duck_type_of(function_response, types.FunctionResponse): + return function_response + else: + raise TypeError( + 'Could not parse input as FunctionResponse. Unsupported' + f' function_response type: {type(function_response)}' + ) + + +def t_function_responses( + function_responses: Union[ + types.FunctionResponseOrDict, + Sequence[types.FunctionResponseOrDict], + ], +) -> list[types.FunctionResponse]: + if not function_responses: + raise ValueError('function_responses are required.') + if isinstance(function_responses, Sequence): + return [t_function_response(response) for response in function_responses] + else: + return [t_function_response(function_responses)] + + +def t_blobs( + blobs: Union[types.BlobImageUnionDict, list[types.BlobImageUnionDict]], +) -> list[types.Blob]: + if isinstance(blobs, list): + return [t_blob(blob) for blob in blobs] + else: + return [t_blob(blobs)] + + +def t_blob(blob: types.BlobImageUnionDict) -> types.Blob: + if not blob: + raise ValueError('blob is required.') + + if is_duck_type_of(blob, types.Blob): + return blob # type: ignore[return-value] + + if isinstance(blob, dict): + return types.Blob.model_validate(blob) + + if 'image' in blob.__class__.__name__.lower(): + try: + import PIL.Image + + PIL_Image = PIL.Image.Image + except ImportError: + PIL_Image = None + + if PIL_Image is not None and isinstance(blob, PIL_Image): + return pil_to_blob(blob) + + raise TypeError( + f'Could not parse input as Blob. Unsupported blob type: {type(blob)}' + ) + + +def t_image_blob(blob: types.BlobImageUnionDict) -> types.Blob: + blob = t_blob(blob) + if blob.mime_type and blob.mime_type.startswith('image/'): + return blob + raise ValueError(f'Unsupported mime type: {blob.mime_type!r}') + + +def t_audio_blob(blob: types.BlobOrDict) -> types.Blob: + blob = t_blob(blob) + if blob.mime_type and blob.mime_type.startswith('audio/'): + return blob + raise ValueError(f'Unsupported mime type: {blob.mime_type!r}') + + +def t_part(part: Optional[types.PartUnionDict]) -> types.Part: + if part is None: + raise ValueError('content part is required.') + if isinstance(part, str): + return types.Part(text=part) + if is_duck_type_of(part, types.File): + if not part.uri or not part.mime_type: # type: ignore[union-attr] + raise ValueError('file uri and mime_type are required.') + return types.Part.from_uri(file_uri=part.uri, mime_type=part.mime_type) # type: ignore[union-attr] + if isinstance(part, dict): + try: + return types.Part.model_validate(part) + except pydantic.ValidationError: + return types.Part(file_data=types.FileData.model_validate(part)) + if is_duck_type_of(part, types.Part): + return part # type: ignore[return-value] + + if 'image' in part.__class__.__name__.lower(): + try: + import PIL.Image + + PIL_Image = PIL.Image.Image + except ImportError: + PIL_Image = None + + if PIL_Image is not None and isinstance(part, PIL_Image): + return types.Part(inline_data=pil_to_blob(part)) + raise ValueError(f'Unsupported content part type: {type(part)}') + + +def t_parts( + parts: Optional[ + Union[list[types.PartUnionDict], types.PartUnionDict, list[types.Part]] + ], +) -> list[types.Part]: + # + if parts is None or (isinstance(parts, list) and not parts): + raise ValueError('content parts are required.') + if isinstance(parts, list): + return [t_part(part) for part in parts] + else: + return [t_part(parts)] + + +def t_image_predictions( + predictions: Optional[Iterable[Mapping[str, Any]]], +) -> Optional[list[types.GeneratedImage]]: + if not predictions: + return None + images = [] + for prediction in predictions: + if prediction.get('image'): + images.append( + types.GeneratedImage( + image=types.Image( + gcs_uri=prediction['image']['gcsUri'], + image_bytes=prediction['image']['imageBytes'], + ) + ) + ) + return images + + +ContentType = Union[types.Content, types.ContentDict, types.PartUnionDict] + + +def t_content( + content: Union[ContentType, types.ContentDict, None], +) -> types.Content: + if content is None: + raise ValueError('content is required.') + if is_duck_type_of(content, types.Content): + return content # type: ignore[return-value] + if isinstance(content, dict): + try: + return types.Content.model_validate(content) + except pydantic.ValidationError: + possible_part = t_part(content) # type: ignore[arg-type] + return ( + types.ModelContent(parts=[possible_part]) + if possible_part.function_call + else types.UserContent(parts=[possible_part]) + ) + if is_duck_type_of(content, types.File): + return types.UserContent(parts=[t_part(content)]) # type: ignore[arg-type] + if is_duck_type_of(content, types.Part): + return ( + types.ModelContent(parts=[content]) # type: ignore[arg-type] + if content.function_call # type: ignore[union-attr] + else types.UserContent(parts=[content]) # type: ignore[arg-type] + ) + return types.UserContent(parts=content) # type: ignore[arg-type] + + +def t_contents_for_embed( + client: _api_client.BaseApiClient, + contents: Union[list[types.Content], list[types.ContentDict], ContentType], +) -> Union[list[str], list[types.Content]]: + if isinstance(contents, list): + transformed_contents = [t_content(content) for content in contents] + else: + transformed_contents = [t_content(contents)] + + if client.vertexai: + text_parts = [] + for content in transformed_contents: + if content is not None: + if isinstance(content, dict): + content = types.Content.model_validate(content) + if content.parts is not None: + for part in content.parts: + if part.text: + text_parts.append(part.text) + else: + logger.warning(f'Non-text part found, only returning text parts.') + return text_parts + else: + return transformed_contents + + +def t_contents( + contents: Optional[ + Union[types.ContentListUnion, types.ContentListUnionDict, types.Content] + ], +) -> list[types.Content]: + if contents is None or (isinstance(contents, list) and not contents): + raise ValueError('contents are required.') + if not isinstance(contents, list): + return [t_content(contents)] + + result: list[types.Content] = [] + accumulated_parts: list[types.Part] = [] + + def _is_part( + part: Union[types.PartUnionDict, Any], + ) -> TypeGuard[types.PartUnionDict]: + if ( + isinstance(part, str) + or is_duck_type_of(part, types.File) + or is_duck_type_of(part, types.Part) + ): + return True + + if isinstance(part, dict): + if not part: + # Empty dict should be considered as Content, not Part. + return False + try: + types.Part.model_validate(part) + return True + except pydantic.ValidationError: + try: + types.FileData.model_validate(part) + return True + except pydantic.ValidationError: + return False + + if 'image' in part.__class__.__name__.lower(): + try: + import PIL.Image + + PIL_Image = PIL.Image.Image + except ImportError: + PIL_Image = None + + if PIL_Image is not None and isinstance(part, PIL_Image): + return True + + return False + + def _is_user_part(part: types.Part) -> bool: + return not part.function_call + + def _are_user_parts(parts: list[types.Part]) -> bool: + return all(_is_user_part(part) for part in parts) + + def _append_accumulated_parts_as_content( + result: list[types.Content], + accumulated_parts: list[types.Part], + ) -> None: + if not accumulated_parts: + return + result.append( + types.UserContent(parts=accumulated_parts) + if _are_user_parts(accumulated_parts) + else types.ModelContent(parts=accumulated_parts) + ) + accumulated_parts[:] = [] + + def _handle_current_part( + result: list[types.Content], + accumulated_parts: list[types.Part], + current_part: types.PartUnionDict, + ) -> None: + current_part = t_part(current_part) + if _is_user_part(current_part) == _are_user_parts(accumulated_parts): + accumulated_parts.append(current_part) + else: + _append_accumulated_parts_as_content(result, accumulated_parts) + accumulated_parts[:] = [current_part] + + # iterator over contents + # if content type or content dict, append to result + # if consecutive part(s), + # group consecutive user part(s) to a UserContent + # group consecutive model part(s) to a ModelContent + # append to result + # if list, we only accept a list of types.PartUnion + for content in contents: + if is_duck_type_of(content, types.Content) or isinstance(content, list): + _append_accumulated_parts_as_content(result, accumulated_parts) + if isinstance(content, list): + result.append(types.UserContent(parts=content)) # type: ignore[arg-type] + else: + result.append(content) # type: ignore[arg-type] + elif _is_part(content): + _handle_current_part(result, accumulated_parts, content) + elif isinstance(content, dict): + # PactDict is already handled in _is_part + result.append(types.Content.model_validate(content)) + else: + raise ValueError(f'Unsupported content type: {type(content)}') + + _append_accumulated_parts_as_content(result, accumulated_parts) + + return result + + +def handle_null_fields(schema: _common.StringDict) -> None: + """Process null fields in the schema so it is compatible with OpenAPI. + + The OpenAPI spec does not support 'type: 'null' in the schema. This function + handles this case by adding 'nullable: True' to the null field and removing + the {'type': 'null'} entry. + + https://swagger.io/docs/specification/v3_0/data-models/data-types/#null + + Example of schema properties before and after handling null fields: + Before: + { + "name": { + "title": "Name", + "type": "string" + }, + "total_area_sq_mi": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "default": None, + "title": "Total Area Sq Mi" + } + } + + After: + { + "name": { + "title": "Name", + "type": "string" + }, + "total_area_sq_mi": { + "type": "integer", + "nullable": true, + "default": None, + "title": "Total Area Sq Mi" + } + } + """ + if schema.get('type', None) == 'null': + schema['nullable'] = True + del schema['type'] + elif 'anyOf' in schema: + for item in schema['anyOf']: + if 'type' in item and item['type'] == 'null': + schema['nullable'] = True + schema['anyOf'].remove({'type': 'null'}) + if len(schema['anyOf']) == 1: + # If there is only one type left after removing null, remove the anyOf field. + for key, val in schema['anyOf'][0].items(): + schema[key] = val + del schema['anyOf'] + + +def _raise_for_unsupported_schema_type(origin: Any) -> None: + """Raises an error if the schema type is unsupported.""" + raise ValueError(f'Unsupported schema type: {origin}') + + +def _raise_for_unsupported_mldev_properties( + schema: Any, client: Optional[_api_client.BaseApiClient] +) -> None: + if ( + client + and not client.vertexai + and ( + schema.get('additionalProperties') + or schema.get('additional_properties') + ) + ): + raise ValueError('additionalProperties is not supported in the Gemini API.') + + +def process_schema( + schema: _common.StringDict, + client: Optional[_api_client.BaseApiClient], + defs: Optional[_common.StringDict] = None, + *, + order_properties: bool = True, + visited_dicts_path: Optional[set[int]] = None, +) -> None: + """Updates the schema and each sub-schema inplace to be API-compatible. + + - Inlines the $defs. + + Example of a schema before and after (with mldev): + Before: + + `schema` + + { + 'items': { + '$ref': '#/$defs/CountryInfo' + }, + 'title': 'Placeholder', + 'type': 'array' + } + + + `defs` + + { + 'CountryInfo': { + 'properties': { + 'continent': { + 'title': 'Continent', + 'type': 'string' + }, + 'gdp': { + 'title': 'Gdp', + 'type': 'integer'} + }, + } + 'required':['continent', 'gdp'], + 'title': 'CountryInfo', + 'type': 'object' + } + } + + After: + + `schema` + { + 'items': { + 'properties': { + 'continent': { + 'title': 'Continent', + 'type': 'string' + }, + 'gdp': { + 'title': 'Gdp', + 'type': 'integer' + }, + } + 'required':['continent', 'gdp'], + 'title': 'CountryInfo', + 'type': 'object' + }, + 'type': 'array' + } + """ + if visited_dicts_path is None: + visited_dicts_path = set() + + if id(schema) in visited_dicts_path: + return + visited_dicts_path.add(id(schema)) + + if schema.get('title') == 'PlaceholderLiteralEnum': + del schema['title'] + + _raise_for_unsupported_mldev_properties(schema, client) + + # Standardize spelling for relevant schema fields. For example, if a dict is + # provided directly to response_schema, it may use `any_of` instead of `anyOf. + # Otherwise, model_json_schema() uses `anyOf`. + for from_name, to_name in [ + ('additional_properties', 'additionalProperties'), + ('any_of', 'anyOf'), + ('prefix_items', 'prefixItems'), + ('property_ordering', 'propertyOrdering'), + ]: + if (value := schema.pop(from_name, None)) is not None: + schema[to_name] = value + + if defs is None: + defs = schema.pop('$defs', {}) + for _, sub_schema in defs.items(): + # We can skip the '$ref' check, because JSON schema forbids a '$ref' from + # directly referencing another '$ref': + # https://json-schema.org/understanding-json-schema/structuring#recursion + process_schema( + sub_schema, + client, + defs, + order_properties=order_properties, + visited_dicts_path=visited_dicts_path, + ) + + handle_null_fields(schema) + + # After removing null fields, Optional fields with only one possible type + # will have a $ref key that needs to be flattened + # For example: {'default': None, 'description': 'Name of the person', 'nullable': True, '$ref': '#/$defs/TestPerson'} + if (ref := schema.pop('$ref', None)) is not None: + schema.update(defs[ref.split('defs/')[-1]]) + + def _recurse(sub_schema: _common.StringDict) -> _common.StringDict: + """Returns the processed `sub_schema`, resolving its '$ref' if any.""" + if (ref := sub_schema.pop('$ref', None)) is not None: + sub_schema = defs[ref.split('defs/')[-1]] + if id(sub_schema) in visited_dicts_path: + return {} + + process_schema( + sub_schema, + client, + defs, + order_properties=order_properties, + visited_dicts_path=visited_dicts_path, + ) + return sub_schema + + if (any_of := schema.get('anyOf')) is not None: + schema['anyOf'] = [_recurse(sub_schema) for sub_schema in any_of] + visited_dicts_path.remove(id(schema)) + return + + schema_type = schema.get('type') + if isinstance(schema_type, Enum): + schema_type = schema_type.value + if isinstance(schema_type, str): + schema_type = schema_type.upper() + + # model_json_schema() returns a schema with a 'const' field when a Literal with one value is provided as a pydantic field + # For example `genre: Literal['action']` becomes: {'const': 'action', 'title': 'Genre', 'type': 'string'} + const = schema.get('const') + if const is not None: + if schema_type == 'STRING': + schema['enum'] = [const] + del schema['const'] + else: + raise ValueError('Literal values must be strings.') + + if schema_type == 'OBJECT': + if (properties := schema.get('properties')) is not None: + for name, sub_schema in list(properties.items()): + properties[name] = _recurse(sub_schema) + if ( + len(properties.items()) > 1 + and order_properties + and 'propertyOrdering' not in schema + ): + schema['property_ordering'] = list(properties.keys()) + if (additional := schema.get('additionalProperties')) is not None: + # It is legal to set 'additionalProperties' to a bool: + # https://json-schema.org/understanding-json-schema/reference/object#additionalproperties + if isinstance(additional, dict): + schema['additionalProperties'] = _recurse(additional) + elif schema_type == 'ARRAY': + if (items := schema.get('items')) is not None: + schema['items'] = _recurse(items) + if (prefixes := schema.get('prefixItems')) is not None: + schema['prefixItems'] = [_recurse(prefix) for prefix in prefixes] + + visited_dicts_path.remove(id(schema)) + +def _process_enum( + enum: EnumMeta, client: Optional[_api_client.BaseApiClient] +) -> types.Schema: + is_integer_enum = False + + for member in enum: # type: ignore + if isinstance(member.value, int): + is_integer_enum = True + elif not isinstance(member.value, str): + raise TypeError( + f'Enum member {member.name} value must be a string or integer, got' + f' {type(member.value)}' + ) + + enum_to_process = enum + if is_integer_enum: + str_members = [str(member.value) for member in enum] # type: ignore + str_enum = Enum(enum.__name__, str_members, type=str) # type: ignore + enum_to_process = str_enum + + class Placeholder(pydantic.BaseModel): + placeholder: enum_to_process # type: ignore[valid-type] + + enum_schema = Placeholder.model_json_schema() + process_schema(enum_schema, client) + enum_schema = enum_schema['properties']['placeholder'] + return types.Schema.model_validate(enum_schema) + + +def _is_type_dict_str_any( + origin: Union[types.SchemaUnionDict, Any], +) -> TypeGuard[_common.StringDict]: + """Verifies the schema is of type dict[str, Any] for mypy type checking.""" + return isinstance(origin, dict) and all( + isinstance(key, str) for key in origin + ) + + +def t_schema( + client: Optional[_api_client.BaseApiClient], + origin: Union[types.SchemaUnionDict, Any], +) -> Optional[types.Schema]: + if not origin: + return None + if isinstance(origin, dict) and _is_type_dict_str_any(origin): + process_schema(origin, client) + return types.Schema.model_validate(origin) + if isinstance(origin, EnumMeta): + return _process_enum(origin, client) + if is_duck_type_of(origin, types.Schema): + if dict(origin) == dict(types.Schema()): # type: ignore [arg-type] + # response_schema value was coerced to an empty Schema instance because + # it did not adhere to the Schema field annotation + _raise_for_unsupported_schema_type(origin) + schema = origin.model_dump(exclude_unset=True) # type: ignore[union-attr] + process_schema(schema, client) + return types.Schema.model_validate(schema) + + if ( + # in Python 3.9 Generic alias list[int] counts as a type, + # and breaks issubclass because it's not a class. + not isinstance(origin, GenericAlias) + and isinstance(origin, type) + and issubclass(origin, pydantic.BaseModel) + ): + schema = origin.model_json_schema() + process_schema(schema, client) + return types.Schema.model_validate(schema) + elif ( + isinstance(origin, GenericAlias) + or isinstance(origin, type) + or isinstance(origin, VersionedUnionType) + or typing.get_origin(origin) in _UNION_TYPES + ): + + class Placeholder(pydantic.BaseModel): + placeholder: origin # type: ignore[valid-type] + + schema = Placeholder.model_json_schema() + process_schema(schema, client) + schema = schema['properties']['placeholder'] + return types.Schema.model_validate(schema) + + raise ValueError(f'Unsupported schema type: {origin}') + + +def t_speech_config( + origin: Union[types.SpeechConfigUnionDict, Any], +) -> Optional[types.SpeechConfig]: + if not origin: + return None + if is_duck_type_of(origin, types.SpeechConfig): + return origin # type: ignore[return-value] + if isinstance(origin, str): + return types.SpeechConfig( + voice_config=types.VoiceConfig( + prebuilt_voice_config=types.PrebuiltVoiceConfig(voice_name=origin) + ) + ) + if isinstance(origin, dict): + return types.SpeechConfig.model_validate(origin) + + raise ValueError(f'Unsupported speechConfig type: {type(origin)}') + + +def t_live_speech_config( + origin: types.SpeechConfigOrDict, +) -> Optional[types.SpeechConfig]: + if is_duck_type_of(origin, types.SpeechConfig): + speech_config = origin + if isinstance(origin, dict): + speech_config = types.SpeechConfig.model_validate(origin) + + if speech_config.multi_speaker_voice_config is not None: # type: ignore[union-attr] + raise ValueError( + 'multi_speaker_voice_config is not supported in the live API.' + ) + + return speech_config # type: ignore[return-value] + + +def t_tool( + client: _api_client.BaseApiClient, origin: Any +) -> Optional[Union[types.Tool, Any]]: + if not origin: + return None + if inspect.isfunction(origin) or inspect.ismethod(origin): + return types.Tool( + function_declarations=[ + types.FunctionDeclaration.from_callable( + client=client, callable=origin + ) + ] + ) + elif McpTool is not None and is_duck_type_of(origin, McpTool): + return mcp_to_gemini_tool(origin) + elif isinstance(origin, dict): + return types.Tool.model_validate(origin) + else: + return origin + + +def t_tools( + client: _api_client.BaseApiClient, origin: list[Any] +) -> list[types.Tool]: + if not origin: + return [] + function_tool = types.Tool(function_declarations=[]) + tools = [] + for tool in origin: + transformed_tool = t_tool(client, tool) + # All functions should be merged into one tool. + if transformed_tool is not None: + if ( + transformed_tool.function_declarations + and function_tool.function_declarations is not None + ): + function_tool.function_declarations += ( + transformed_tool.function_declarations + ) + else: + tools.append(transformed_tool) + if function_tool.function_declarations: + tools.append(function_tool) + return tools + + +def t_cached_content_name(client: _api_client.BaseApiClient, name: str) -> str: + return _resource_name(client, name, collection_identifier='cachedContents') + + +def t_batch_job_source( + client: _api_client.BaseApiClient, + src: types.BatchJobSourceUnionDict, +) -> types.BatchJobSource: + if isinstance(src, dict): + src = types.BatchJobSource(**src) + if is_duck_type_of(src, types.BatchJobSource): + vertex_sources = sum( + [src.gcs_uri is not None, src.bigquery_uri is not None] # type: ignore[union-attr] + ) + mldev_sources = sum([ + src.inlined_requests is not None, # type: ignore[union-attr] + src.file_name is not None, # type: ignore[union-attr] + ]) + if client.vertexai: + if mldev_sources or vertex_sources != 1: + raise ValueError( + 'Exactly one of `gcs_uri` or `bigquery_uri` must be set, other ' + 'sources are not supported in Vertex AI.' + ) + else: + if vertex_sources or mldev_sources != 1: + raise ValueError( + 'Exactly one of `inlined_requests`, `file_name`, ' + '`inlined_embed_content_requests`, or `embed_content_file_name` ' + 'must be set, other sources are not supported in Gemini API.' + ) + return src # type: ignore[return-value] + + elif isinstance(src, list): + return types.BatchJobSource(inlined_requests=src) + elif isinstance(src, str): + if src.startswith('gs://'): + return types.BatchJobSource( + format='jsonl', + gcs_uri=[src], + ) + elif src.startswith('bq://'): + return types.BatchJobSource( + format='bigquery', + bigquery_uri=src, + ) + elif src.startswith('files/'): + return types.BatchJobSource( + file_name=src, + ) + + raise ValueError(f'Unsupported source: {src}') + + +def t_embedding_batch_job_source( + client: _api_client.BaseApiClient, + src: types.EmbeddingsBatchJobSourceOrDict, +) -> types.EmbeddingsBatchJobSource: + if isinstance(src, dict): + src = types.EmbeddingsBatchJobSource(**src) + + if is_duck_type_of(src, types.EmbeddingsBatchJobSource): + mldev_sources = sum([ + src.inlined_requests is not None, + src.file_name is not None, + ]) + if mldev_sources != 1: + raise ValueError( + 'Exactly one of `inlined_requests`, `file_name`, ' + '`inlined_embed_content_requests`, or `embed_content_file_name` ' + 'must be set, other sources are not supported in Gemini API.' + ) + return src + else: + raise ValueError(f'Unsupported source type: {type(src)}') + + +def t_batch_job_destination( + dest: Union[str, types.BatchJobDestinationOrDict], +) -> types.BatchJobDestination: + if isinstance(dest, dict): + dest = types.BatchJobDestination(**dest) + return dest + elif isinstance(dest, str): + if dest.startswith('gs://'): + return types.BatchJobDestination( + format='jsonl', + gcs_uri=dest, + ) + elif dest.startswith('bq://'): + return types.BatchJobDestination( + format='bigquery', + bigquery_uri=dest, + ) + else: + raise ValueError(f'Unsupported destination: {dest}') + elif is_duck_type_of(dest, types.BatchJobDestination): + return dest + else: + raise ValueError(f'Unsupported destination: {dest}') + + +def t_recv_batch_job_destination(dest: dict[str, Any]) -> dict[str, Any]: + # Rename inlinedResponses if it looks like an embedding response. + inline_responses = dest.get('inlinedResponses', {}).get( + 'inlinedResponses', [] + ) + if not inline_responses: + return dest + for response in inline_responses: + inner_response = response.get('response', {}) + if not inner_response: + continue + if 'embedding' in inner_response: + dest['inlinedEmbedContentResponses'] = dest.pop('inlinedResponses') + break + return dest + + +def t_batch_job_name(client: _api_client.BaseApiClient, name: str) -> str: + if not client.vertexai: + mldev_pattern = r'batches/[^/]+$' + if re.match(mldev_pattern, name): + return name.split('/')[-1] + else: + raise ValueError(f'Invalid batch job name: {name}.') + + vertex_pattern = r'^projects/[^/]+/locations/[^/]+/batchPredictionJobs/[^/]+$' + + if re.match(vertex_pattern, name): + return name.split('/')[-1] + elif name.isdigit(): + return name + else: + raise ValueError(f'Invalid batch job name: {name}.') + + +def t_job_state(state: str) -> str: + if state == 'BATCH_STATE_UNSPECIFIED': + return 'JOB_STATE_UNSPECIFIED' + elif state == 'BATCH_STATE_PENDING': + return 'JOB_STATE_PENDING' + elif state == 'BATCH_STATE_RUNNING': + return 'JOB_STATE_RUNNING' + elif state == 'BATCH_STATE_SUCCEEDED': + return 'JOB_STATE_SUCCEEDED' + elif state == 'BATCH_STATE_FAILED': + return 'JOB_STATE_FAILED' + elif state == 'BATCH_STATE_CANCELLED': + return 'JOB_STATE_CANCELLED' + elif state == 'BATCH_STATE_EXPIRED': + return 'JOB_STATE_EXPIRED' + else: + return state + + +LRO_POLLING_INITIAL_DELAY_SECONDS = 1.0 +LRO_POLLING_MAXIMUM_DELAY_SECONDS = 20.0 +LRO_POLLING_TIMEOUT_SECONDS = 900.0 +LRO_POLLING_MULTIPLIER = 1.5 + + +def t_resolve_operation( + api_client: _api_client.BaseApiClient, struct: _common.StringDict +) -> Any: + if (name := struct.get('name')) and '/operations/' in name: + operation: _common.StringDict = struct + total_seconds = 0.0 + delay_seconds = LRO_POLLING_INITIAL_DELAY_SECONDS + while operation.get('done') != True: + if total_seconds > LRO_POLLING_TIMEOUT_SECONDS: + raise RuntimeError(f'Operation {name} timed out.\n{operation}') + # TODO(b/374433890): Replace with LRO module once it's available. + operation = api_client.request( # type: ignore[assignment] + http_method='GET', path=name, request_dict={} + ) + time.sleep(delay_seconds) + total_seconds += total_seconds + # Exponential backoff + delay_seconds = min( + delay_seconds * LRO_POLLING_MULTIPLIER, + LRO_POLLING_MAXIMUM_DELAY_SECONDS, + ) + if error := operation.get('error'): + raise RuntimeError( + f'Operation {name} failed with error: {error}.\n{operation}' + ) + return operation.get('response') + else: + return struct + + +def t_file_name( + name: Optional[Union[str, types.File, types.Video, types.GeneratedVideo]], +) -> str: + # Remove the files/ prefix since it's added to the url path. + if is_duck_type_of(name, types.File): + name = name.name # type: ignore[union-attr] + elif is_duck_type_of(name, types.Video): + name = name.uri # type: ignore[union-attr] + elif is_duck_type_of(name, types.GeneratedVideo): + if name.video is not None: # type: ignore[union-attr] + name = name.video.uri # type: ignore[union-attr] + else: + name = None + + if name is None: + raise ValueError('File name is required.') + + if not isinstance(name, str): + raise ValueError( + f'Could not convert object of type `{type(name)}` to a file name.' + ) + + if name.startswith('https://'): + suffix = name.split('files/')[1] + match = re.match('[a-z0-9]+', suffix) + if match is None: + raise ValueError(f'Could not extract file name from URI: {name}') + name = match.group(0) + elif name.startswith('files/'): + name = name.split('files/')[1] + + return name + + +def t_tuning_job_status(status: str) -> Union[types.JobState, str]: + if status == 'STATE_UNSPECIFIED': + return types.JobState.JOB_STATE_UNSPECIFIED + elif status == 'CREATING': + return types.JobState.JOB_STATE_RUNNING + elif status == 'ACTIVE': + return types.JobState.JOB_STATE_SUCCEEDED + elif status == 'FAILED': + return types.JobState.JOB_STATE_FAILED + else: + for state in types.JobState: + if str(state.value) == status: + return state + return status + + +def t_content_strict(content: types.ContentOrDict) -> types.Content: + if isinstance(content, dict): + return types.Content.model_validate(content) + elif is_duck_type_of(content, types.Content): + return content + else: + raise ValueError( + f'Could not convert input (type "{type(content)}") to `types.Content`' + ) + + +def t_contents_strict( + contents: Union[Sequence[types.ContentOrDict], types.ContentOrDict], +) -> list[types.Content]: + if isinstance(contents, Sequence): + return [t_content_strict(content) for content in contents] + else: + return [t_content_strict(contents)] + + +def t_client_content( + turns: Optional[ + Union[Sequence[types.ContentOrDict], types.ContentOrDict] + ] = None, + turn_complete: bool = True, +) -> types.LiveClientContent: + if turns is None: + return types.LiveClientContent(turn_complete=turn_complete) + + try: + return types.LiveClientContent( + turns=t_contents_strict(contents=turns), + turn_complete=turn_complete, + ) + except Exception as e: + raise ValueError( + f'Could not convert input (type "{type(turns)}") to ' + '`types.LiveClientContent`' + ) from e + + +def t_tool_response( + input: Union[ + types.FunctionResponseOrDict, + Sequence[types.FunctionResponseOrDict], + ], +) -> types.LiveClientToolResponse: + if not input: + raise ValueError(f'A tool response is required, got: \n{input}') + + try: + return types.LiveClientToolResponse( + function_responses=t_function_responses(function_responses=input) + ) + except Exception as e: + raise ValueError( + f'Could not convert input (type "{type(input)}") to ' + '`types.LiveClientToolResponse`' + ) from e + + +def t_metrics( + metrics: list[types.MetricSubclass] +) -> list[dict[str, Any]]: + """Prepares the metric payload for the evaluation request. + + Args: + request_dict: The dictionary containing the request details. + resolved_metrics: A list of resolved metric objects. + + Returns: + The updated request dictionary with the prepared metric payload. + """ + metrics_payload = [] + + for metric in metrics: + + if isinstance(metric, dict): + try: + metric = types.UnifiedMetric.model_validate(metric) + except pydantic.ValidationError: + pass + + if isinstance(metric, types.UnifiedMetric): + unified_metric_payload: dict[str, Any] = metric.model_dump() + unified_metric_payload['aggregation_metrics'] = [ + 'AVERAGE', + 'STANDARD_DEVIATION', + ] + metrics_payload.append(unified_metric_payload) + continue + + metric_payload_item: dict[str, Any] = {} + metric_payload_item['aggregation_metrics'] = [ + 'AVERAGE', + 'STANDARD_DEVIATION', + ] + + metric_name = getv(metric, ['name']).lower() + + if metric_name == 'exact_match': + metric_payload_item['exact_match_spec'] = {} + elif metric_name == 'bleu': + metric_payload_item['bleu_spec'] = {} + elif metric_name.startswith('rouge'): + rouge_type = metric_name.replace("_", "") + metric_payload_item['rouge_spec'] = {'rouge_type': rouge_type} + + elif hasattr(metric, 'prompt_template') and metric.prompt_template: + pointwise_spec = {'metric_prompt_template': metric.prompt_template} + system_instruction = getv( + metric, ['judge_model_system_instruction'] + ) + if system_instruction: + pointwise_spec['system_instruction'] = system_instruction + return_raw_output = getv( + metric, ['return_raw_output'] + ) + if return_raw_output: + pointwise_spec['custom_output_format_config'] = { # type: ignore[assignment] + 'return_raw_output': return_raw_output + } + metric_payload_item['pointwise_metric_spec'] = pointwise_spec + else: + raise ValueError( + 'Unsupported metric type or invalid metric name:' f' {metric_name}' + ) + metrics_payload.append(metric_payload_item) + return metrics_payload + + +def t_is_vertex_embed_content_model(model: str) -> bool: + return ( + # Gemini Embeddings except gemini-embedding-001. + 'gemini' in model and model != 'gemini-embedding-001' + # Open-source MaaS embedding models. + or 'maas' in model + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/batches.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/batches.py new file mode 100644 index 0000000000000000000000000000000000000000..9c82e5b1d56d954c31a2ff18512d3acd73487bb1 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/batches.py @@ -0,0 +1,2850 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# Code generated by the Google Gen AI SDK generator DO NOT EDIT. + +import json +import logging +from typing import Any, Optional, Union +from urllib.parse import urlencode + +from . import _api_module +from . import _common +from . import _extra_utils +from . import _transformers as t +from . import types +from ._api_client import BaseApiClient +from ._common import get_value_by_path as getv +from ._common import move_value_by_path as movev +from ._common import set_value_by_path as setv +from .pagers import AsyncPager, Pager + +logger = logging.getLogger('google_genai.batches') + + +def _AuthConfig_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['api_key']) is not None: + setv(to_object, ['apiKey'], getv(from_object, ['api_key'])) + + if getv(from_object, ['api_key_config']) is not None: + raise ValueError('api_key_config parameter is not supported in Gemini API.') + + if getv(from_object, ['auth_type']) is not None: + raise ValueError('auth_type parameter is not supported in Gemini API.') + + if getv(from_object, ['google_service_account_config']) is not None: + raise ValueError( + 'google_service_account_config parameter is not supported in Gemini' + ' API.' + ) + + if getv(from_object, ['http_basic_auth_config']) is not None: + raise ValueError( + 'http_basic_auth_config parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['oauth_config']) is not None: + raise ValueError('oauth_config parameter is not supported in Gemini API.') + + if getv(from_object, ['oidc_config']) is not None: + raise ValueError('oidc_config parameter is not supported in Gemini API.') + + return to_object + + +def _BatchJobDestination_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['responsesFile']) is not None: + setv(to_object, ['file_name'], getv(from_object, ['responsesFile'])) + + if getv(from_object, ['inlinedResponses', 'inlinedResponses']) is not None: + setv( + to_object, + ['inlined_responses'], + [ + _InlinedResponse_from_mldev(item, to_object) + for item in getv( + from_object, ['inlinedResponses', 'inlinedResponses'] + ) + ], + ) + + if ( + getv(from_object, ['inlinedEmbedContentResponses', 'inlinedResponses']) + is not None + ): + setv( + to_object, + ['inlined_embed_content_responses'], + [ + item + for item in getv( + from_object, + ['inlinedEmbedContentResponses', 'inlinedResponses'], + ) + ], + ) + + return to_object + + +def _BatchJobDestination_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['predictionsFormat']) is not None: + setv(to_object, ['format'], getv(from_object, ['predictionsFormat'])) + + if getv(from_object, ['gcsDestination', 'outputUriPrefix']) is not None: + setv( + to_object, + ['gcs_uri'], + getv(from_object, ['gcsDestination', 'outputUriPrefix']), + ) + + if getv(from_object, ['bigqueryDestination', 'outputUri']) is not None: + setv( + to_object, + ['bigquery_uri'], + getv(from_object, ['bigqueryDestination', 'outputUri']), + ) + + return to_object + + +def _BatchJobDestination_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['format']) is not None: + setv(to_object, ['predictionsFormat'], getv(from_object, ['format'])) + + if getv(from_object, ['gcs_uri']) is not None: + setv( + to_object, + ['gcsDestination', 'outputUriPrefix'], + getv(from_object, ['gcs_uri']), + ) + + if getv(from_object, ['bigquery_uri']) is not None: + setv( + to_object, + ['bigqueryDestination', 'outputUri'], + getv(from_object, ['bigquery_uri']), + ) + + if getv(from_object, ['file_name']) is not None: + raise ValueError('file_name parameter is not supported in Vertex AI.') + + if getv(from_object, ['inlined_responses']) is not None: + raise ValueError( + 'inlined_responses parameter is not supported in Vertex AI.' + ) + + if getv(from_object, ['inlined_embed_content_responses']) is not None: + raise ValueError( + 'inlined_embed_content_responses parameter is not supported in' + ' Vertex AI.' + ) + + return to_object + + +def _BatchJobSource_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['instancesFormat']) is not None: + setv(to_object, ['format'], getv(from_object, ['instancesFormat'])) + + if getv(from_object, ['gcsSource', 'uris']) is not None: + setv(to_object, ['gcs_uri'], getv(from_object, ['gcsSource', 'uris'])) + + if getv(from_object, ['bigquerySource', 'inputUri']) is not None: + setv( + to_object, + ['bigquery_uri'], + getv(from_object, ['bigquerySource', 'inputUri']), + ) + + return to_object + + +def _BatchJobSource_to_mldev( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['format']) is not None: + raise ValueError('format parameter is not supported in Gemini API.') + + if getv(from_object, ['gcs_uri']) is not None: + raise ValueError('gcs_uri parameter is not supported in Gemini API.') + + if getv(from_object, ['bigquery_uri']) is not None: + raise ValueError('bigquery_uri parameter is not supported in Gemini API.') + + if getv(from_object, ['file_name']) is not None: + setv(to_object, ['fileName'], getv(from_object, ['file_name'])) + + if getv(from_object, ['inlined_requests']) is not None: + setv( + to_object, + ['requests', 'requests'], + [ + _InlinedRequest_to_mldev(api_client, item, to_object) + for item in getv(from_object, ['inlined_requests']) + ], + ) + + return to_object + + +def _BatchJobSource_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['format']) is not None: + setv(to_object, ['instancesFormat'], getv(from_object, ['format'])) + + if getv(from_object, ['gcs_uri']) is not None: + setv(to_object, ['gcsSource', 'uris'], getv(from_object, ['gcs_uri'])) + + if getv(from_object, ['bigquery_uri']) is not None: + setv( + to_object, + ['bigquerySource', 'inputUri'], + getv(from_object, ['bigquery_uri']), + ) + + if getv(from_object, ['file_name']) is not None: + raise ValueError('file_name parameter is not supported in Vertex AI.') + + if getv(from_object, ['inlined_requests']) is not None: + raise ValueError( + 'inlined_requests parameter is not supported in Vertex AI.' + ) + + return to_object + + +def _BatchJob_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['name']) is not None: + setv(to_object, ['name'], getv(from_object, ['name'])) + + if getv(from_object, ['metadata', 'displayName']) is not None: + setv( + to_object, + ['display_name'], + getv(from_object, ['metadata', 'displayName']), + ) + + if getv(from_object, ['metadata', 'state']) is not None: + setv( + to_object, + ['state'], + t.t_job_state(getv(from_object, ['metadata', 'state'])), + ) + + if getv(from_object, ['metadata', 'createTime']) is not None: + setv( + to_object, + ['create_time'], + getv(from_object, ['metadata', 'createTime']), + ) + + if getv(from_object, ['metadata', 'endTime']) is not None: + setv(to_object, ['end_time'], getv(from_object, ['metadata', 'endTime'])) + + if getv(from_object, ['metadata', 'updateTime']) is not None: + setv( + to_object, + ['update_time'], + getv(from_object, ['metadata', 'updateTime']), + ) + + if getv(from_object, ['metadata', 'model']) is not None: + setv(to_object, ['model'], getv(from_object, ['metadata', 'model'])) + + if getv(from_object, ['metadata', 'output']) is not None: + setv( + to_object, + ['dest'], + _BatchJobDestination_from_mldev( + t.t_recv_batch_job_destination( + getv(from_object, ['metadata', 'output']) + ), + to_object, + ), + ) + + return to_object + + +def _BatchJob_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['name']) is not None: + setv(to_object, ['name'], getv(from_object, ['name'])) + + if getv(from_object, ['displayName']) is not None: + setv(to_object, ['display_name'], getv(from_object, ['displayName'])) + + if getv(from_object, ['state']) is not None: + setv(to_object, ['state'], t.t_job_state(getv(from_object, ['state']))) + + if getv(from_object, ['error']) is not None: + setv(to_object, ['error'], getv(from_object, ['error'])) + + if getv(from_object, ['createTime']) is not None: + setv(to_object, ['create_time'], getv(from_object, ['createTime'])) + + if getv(from_object, ['startTime']) is not None: + setv(to_object, ['start_time'], getv(from_object, ['startTime'])) + + if getv(from_object, ['endTime']) is not None: + setv(to_object, ['end_time'], getv(from_object, ['endTime'])) + + if getv(from_object, ['updateTime']) is not None: + setv(to_object, ['update_time'], getv(from_object, ['updateTime'])) + + if getv(from_object, ['model']) is not None: + setv(to_object, ['model'], getv(from_object, ['model'])) + + if getv(from_object, ['inputConfig']) is not None: + setv( + to_object, + ['src'], + _BatchJobSource_from_vertex( + getv(from_object, ['inputConfig']), to_object + ), + ) + + if getv(from_object, ['outputConfig']) is not None: + setv( + to_object, + ['dest'], + _BatchJobDestination_from_vertex( + t.t_recv_batch_job_destination(getv(from_object, ['outputConfig'])), + to_object, + ), + ) + + if getv(from_object, ['completionStats']) is not None: + setv( + to_object, ['completion_stats'], getv(from_object, ['completionStats']) + ) + + return to_object + + +def _Blob_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['data']) is not None: + setv(to_object, ['data'], getv(from_object, ['data'])) + + if getv(from_object, ['display_name']) is not None: + raise ValueError('display_name parameter is not supported in Gemini API.') + + if getv(from_object, ['mime_type']) is not None: + setv(to_object, ['mimeType'], getv(from_object, ['mime_type'])) + + return to_object + + +def _CancelBatchJobParameters_to_mldev( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['name']) is not None: + setv( + to_object, + ['_url', 'name'], + t.t_batch_job_name(api_client, getv(from_object, ['name'])), + ) + + return to_object + + +def _CancelBatchJobParameters_to_vertex( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['name']) is not None: + setv( + to_object, + ['_url', 'name'], + t.t_batch_job_name(api_client, getv(from_object, ['name'])), + ) + + return to_object + + +def _Candidate_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['content']) is not None: + setv(to_object, ['content'], getv(from_object, ['content'])) + + if getv(from_object, ['citationMetadata']) is not None: + setv( + to_object, + ['citation_metadata'], + _CitationMetadata_from_mldev( + getv(from_object, ['citationMetadata']), to_object + ), + ) + + if getv(from_object, ['tokenCount']) is not None: + setv(to_object, ['token_count'], getv(from_object, ['tokenCount'])) + + if getv(from_object, ['finishReason']) is not None: + setv(to_object, ['finish_reason'], getv(from_object, ['finishReason'])) + + if getv(from_object, ['groundingMetadata']) is not None: + setv( + to_object, + ['grounding_metadata'], + getv(from_object, ['groundingMetadata']), + ) + + if getv(from_object, ['avgLogprobs']) is not None: + setv(to_object, ['avg_logprobs'], getv(from_object, ['avgLogprobs'])) + + if getv(from_object, ['index']) is not None: + setv(to_object, ['index'], getv(from_object, ['index'])) + + if getv(from_object, ['logprobsResult']) is not None: + setv(to_object, ['logprobs_result'], getv(from_object, ['logprobsResult'])) + + if getv(from_object, ['safetyRatings']) is not None: + setv( + to_object, + ['safety_ratings'], + [item for item in getv(from_object, ['safetyRatings'])], + ) + + if getv(from_object, ['urlContextMetadata']) is not None: + setv( + to_object, + ['url_context_metadata'], + getv(from_object, ['urlContextMetadata']), + ) + + return to_object + + +def _CitationMetadata_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['citationSources']) is not None: + setv( + to_object, + ['citations'], + [item for item in getv(from_object, ['citationSources'])], + ) + + return to_object + + +def _Content_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['parts']) is not None: + setv( + to_object, + ['parts'], + [ + _Part_to_mldev(item, to_object) + for item in getv(from_object, ['parts']) + ], + ) + + if getv(from_object, ['role']) is not None: + setv(to_object, ['role'], getv(from_object, ['role'])) + + return to_object + + +def _CreateBatchJobConfig_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['display_name']) is not None: + setv( + parent_object, + ['batch', 'displayName'], + getv(from_object, ['display_name']), + ) + + if getv(from_object, ['dest']) is not None: + raise ValueError('dest parameter is not supported in Gemini API.') + + if getv(from_object, ['webhook_config']) is not None: + setv( + parent_object, + ['batch', 'webhookConfig'], + getv(from_object, ['webhook_config']), + ) + + return to_object + + +def _CreateBatchJobConfig_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['display_name']) is not None: + setv(parent_object, ['displayName'], getv(from_object, ['display_name'])) + + if getv(from_object, ['dest']) is not None: + setv( + parent_object, + ['outputConfig'], + _BatchJobDestination_to_vertex( + t.t_batch_job_destination(getv(from_object, ['dest'])), to_object + ), + ) + + if getv(from_object, ['webhook_config']) is not None: + raise ValueError('webhook_config parameter is not supported in Vertex AI.') + + return to_object + + +def _CreateBatchJobParameters_to_mldev( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['model']) is not None: + setv( + to_object, + ['_url', 'model'], + t.t_model(api_client, getv(from_object, ['model'])), + ) + + if getv(from_object, ['src']) is not None: + setv( + to_object, + ['batch', 'inputConfig'], + _BatchJobSource_to_mldev( + api_client, + t.t_batch_job_source(api_client, getv(from_object, ['src'])), + to_object, + ), + ) + + if getv(from_object, ['config']) is not None: + _CreateBatchJobConfig_to_mldev(getv(from_object, ['config']), to_object) + + return to_object + + +def _CreateBatchJobParameters_to_vertex( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['model']) is not None: + setv( + to_object, + ['model'], + t.t_model(api_client, getv(from_object, ['model'])), + ) + + if getv(from_object, ['src']) is not None: + setv( + to_object, + ['inputConfig'], + _BatchJobSource_to_vertex( + t.t_batch_job_source(api_client, getv(from_object, ['src'])), + to_object, + ), + ) + + if getv(from_object, ['config']) is not None: + _CreateBatchJobConfig_to_vertex(getv(from_object, ['config']), to_object) + + return to_object + + +def _CreateEmbeddingsBatchJobConfig_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['display_name']) is not None: + setv( + parent_object, + ['batch', 'displayName'], + getv(from_object, ['display_name']), + ) + + return to_object + + +def _CreateEmbeddingsBatchJobParameters_to_mldev( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['model']) is not None: + setv( + to_object, + ['_url', 'model'], + t.t_model(api_client, getv(from_object, ['model'])), + ) + + if getv(from_object, ['src']) is not None: + setv( + to_object, + ['batch', 'inputConfig'], + _EmbeddingsBatchJobSource_to_mldev( + api_client, getv(from_object, ['src']), to_object + ), + ) + + if getv(from_object, ['config']) is not None: + _CreateEmbeddingsBatchJobConfig_to_mldev( + getv(from_object, ['config']), to_object + ) + + return to_object + + +def _DeleteBatchJobParameters_to_mldev( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['name']) is not None: + setv( + to_object, + ['_url', 'name'], + t.t_batch_job_name(api_client, getv(from_object, ['name'])), + ) + + return to_object + + +def _DeleteBatchJobParameters_to_vertex( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['name']) is not None: + setv( + to_object, + ['_url', 'name'], + t.t_batch_job_name(api_client, getv(from_object, ['name'])), + ) + + return to_object + + +def _DeleteResourceJob_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['sdkHttpResponse']) is not None: + setv( + to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse']) + ) + + if getv(from_object, ['name']) is not None: + setv(to_object, ['name'], getv(from_object, ['name'])) + + if getv(from_object, ['done']) is not None: + setv(to_object, ['done'], getv(from_object, ['done'])) + + if getv(from_object, ['error']) is not None: + setv(to_object, ['error'], getv(from_object, ['error'])) + + return to_object + + +def _DeleteResourceJob_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['sdkHttpResponse']) is not None: + setv( + to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse']) + ) + + if getv(from_object, ['name']) is not None: + setv(to_object, ['name'], getv(from_object, ['name'])) + + if getv(from_object, ['done']) is not None: + setv(to_object, ['done'], getv(from_object, ['done'])) + + if getv(from_object, ['error']) is not None: + setv(to_object, ['error'], getv(from_object, ['error'])) + + return to_object + + +def _EmbedContentBatch_to_mldev( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['contents']) is not None: + setv( + to_object, + ['requests[]', 'request', 'content'], + [ + item + for item in t.t_contents_for_embed( + api_client, getv(from_object, ['contents']) + ) + ], + ) + + if getv(from_object, ['config']) is not None: + setv( + to_object, + ['_self'], + _EmbedContentConfig_to_mldev(getv(from_object, ['config']), to_object), + ) + movev(to_object, {'requests[].*': 'requests[].request.*'}) + return to_object + + +def _EmbedContentConfig_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['task_type']) is not None: + setv( + parent_object, + ['requests[]', 'taskType'], + getv(from_object, ['task_type']), + ) + + if getv(from_object, ['title']) is not None: + setv(parent_object, ['requests[]', 'title'], getv(from_object, ['title'])) + + if getv(from_object, ['output_dimensionality']) is not None: + setv( + parent_object, + ['requests[]', 'outputDimensionality'], + getv(from_object, ['output_dimensionality']), + ) + + if getv(from_object, ['mime_type']) is not None: + raise ValueError('mime_type parameter is not supported in Gemini API.') + + if getv(from_object, ['auto_truncate']) is not None: + raise ValueError('auto_truncate parameter is not supported in Gemini API.') + + if getv(from_object, ['document_ocr']) is not None: + raise ValueError('document_ocr parameter is not supported in Gemini API.') + + if getv(from_object, ['audio_track_extraction']) is not None: + raise ValueError( + 'audio_track_extraction parameter is not supported in Gemini API.' + ) + + return to_object + + +def _EmbeddingsBatchJobSource_to_mldev( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['file_name']) is not None: + setv(to_object, ['file_name'], getv(from_object, ['file_name'])) + + if getv(from_object, ['inlined_requests']) is not None: + setv( + to_object, + ['requests'], + _EmbedContentBatch_to_mldev( + api_client, getv(from_object, ['inlined_requests']), to_object + ), + ) + + return to_object + + +def _FileData_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['display_name']) is not None: + raise ValueError('display_name parameter is not supported in Gemini API.') + + if getv(from_object, ['file_uri']) is not None: + setv(to_object, ['fileUri'], getv(from_object, ['file_uri'])) + + if getv(from_object, ['mime_type']) is not None: + setv(to_object, ['mimeType'], getv(from_object, ['mime_type'])) + + return to_object + + +def _FunctionCall_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['id']) is not None: + setv(to_object, ['id'], getv(from_object, ['id'])) + + if getv(from_object, ['args']) is not None: + setv(to_object, ['args'], getv(from_object, ['args'])) + + if getv(from_object, ['name']) is not None: + setv(to_object, ['name'], getv(from_object, ['name'])) + + if getv(from_object, ['partial_args']) is not None: + raise ValueError('partial_args parameter is not supported in Gemini API.') + + if getv(from_object, ['will_continue']) is not None: + raise ValueError('will_continue parameter is not supported in Gemini API.') + + return to_object + + +def _FunctionCallingConfig_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['allowed_function_names']) is not None: + setv( + to_object, + ['allowedFunctionNames'], + getv(from_object, ['allowed_function_names']), + ) + + if getv(from_object, ['mode']) is not None: + setv(to_object, ['mode'], getv(from_object, ['mode'])) + + if getv(from_object, ['stream_function_call_arguments']) is not None: + raise ValueError( + 'stream_function_call_arguments parameter is not supported in Gemini' + ' API.' + ) + + return to_object + + +def _GenerateContentConfig_to_mldev( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['system_instruction']) is not None: + setv( + parent_object, + ['systemInstruction'], + _Content_to_mldev( + t.t_content(getv(from_object, ['system_instruction'])), to_object + ), + ) + + if getv(from_object, ['temperature']) is not None: + setv(to_object, ['temperature'], getv(from_object, ['temperature'])) + + if getv(from_object, ['top_p']) is not None: + setv(to_object, ['topP'], getv(from_object, ['top_p'])) + + if getv(from_object, ['top_k']) is not None: + setv(to_object, ['topK'], getv(from_object, ['top_k'])) + + if getv(from_object, ['candidate_count']) is not None: + setv(to_object, ['candidateCount'], getv(from_object, ['candidate_count'])) + + if getv(from_object, ['max_output_tokens']) is not None: + setv( + to_object, ['maxOutputTokens'], getv(from_object, ['max_output_tokens']) + ) + + if getv(from_object, ['stop_sequences']) is not None: + setv(to_object, ['stopSequences'], getv(from_object, ['stop_sequences'])) + + if getv(from_object, ['response_logprobs']) is not None: + setv( + to_object, + ['responseLogprobs'], + getv(from_object, ['response_logprobs']), + ) + + if getv(from_object, ['logprobs']) is not None: + setv(to_object, ['logprobs'], getv(from_object, ['logprobs'])) + + if getv(from_object, ['presence_penalty']) is not None: + setv( + to_object, ['presencePenalty'], getv(from_object, ['presence_penalty']) + ) + + if getv(from_object, ['frequency_penalty']) is not None: + setv( + to_object, + ['frequencyPenalty'], + getv(from_object, ['frequency_penalty']), + ) + + if getv(from_object, ['seed']) is not None: + setv(to_object, ['seed'], getv(from_object, ['seed'])) + + if getv(from_object, ['response_mime_type']) is not None: + setv( + to_object, + ['responseMimeType'], + getv(from_object, ['response_mime_type']), + ) + + if getv(from_object, ['response_schema']) is not None: + setv( + to_object, + ['responseSchema'], + t.t_schema(api_client, getv(from_object, ['response_schema'])), + ) + + if getv(from_object, ['response_json_schema']) is not None: + setv( + to_object, + ['responseJsonSchema'], + getv(from_object, ['response_json_schema']), + ) + + if getv(from_object, ['routing_config']) is not None: + raise ValueError('routing_config parameter is not supported in Gemini API.') + + if getv(from_object, ['model_selection_config']) is not None: + raise ValueError( + 'model_selection_config parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['safety_settings']) is not None: + setv( + parent_object, + ['safetySettings'], + [ + _SafetySetting_to_mldev(item, to_object) + for item in getv(from_object, ['safety_settings']) + ], + ) + + if getv(from_object, ['tools']) is not None: + setv( + parent_object, + ['tools'], + [ + _Tool_to_mldev(t.t_tool(api_client, item), to_object) + for item in t.t_tools(api_client, getv(from_object, ['tools'])) + ], + ) + + if getv(from_object, ['tool_config']) is not None: + setv( + parent_object, + ['toolConfig'], + _ToolConfig_to_mldev(getv(from_object, ['tool_config']), to_object), + ) + + if getv(from_object, ['labels']) is not None: + raise ValueError('labels parameter is not supported in Gemini API.') + + if getv(from_object, ['cached_content']) is not None: + setv( + parent_object, + ['cachedContent'], + t.t_cached_content_name( + api_client, getv(from_object, ['cached_content']) + ), + ) + + if getv(from_object, ['response_modalities']) is not None: + setv( + to_object, + ['responseModalities'], + getv(from_object, ['response_modalities']), + ) + + if getv(from_object, ['media_resolution']) is not None: + setv( + to_object, ['mediaResolution'], getv(from_object, ['media_resolution']) + ) + + if getv(from_object, ['speech_config']) is not None: + setv( + to_object, + ['speechConfig'], + t.t_speech_config(getv(from_object, ['speech_config'])), + ) + + if getv(from_object, ['audio_timestamp']) is not None: + raise ValueError( + 'audio_timestamp parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['thinking_config']) is not None: + setv(to_object, ['thinkingConfig'], getv(from_object, ['thinking_config'])) + + if getv(from_object, ['image_config']) is not None: + setv( + to_object, + ['imageConfig'], + _ImageConfig_to_mldev(getv(from_object, ['image_config']), to_object), + ) + + if getv(from_object, ['enable_enhanced_civic_answers']) is not None: + setv( + to_object, + ['enableEnhancedCivicAnswers'], + getv(from_object, ['enable_enhanced_civic_answers']), + ) + + if getv(from_object, ['model_armor_config']) is not None: + raise ValueError( + 'model_armor_config parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['service_tier']) is not None: + setv(parent_object, ['serviceTier'], getv(from_object, ['service_tier'])) + + return to_object + + +def _GenerateContentResponse_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['sdkHttpResponse']) is not None: + setv( + to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse']) + ) + + if getv(from_object, ['candidates']) is not None: + setv( + to_object, + ['candidates'], + [ + _Candidate_from_mldev(item, to_object) + for item in getv(from_object, ['candidates']) + ], + ) + + if getv(from_object, ['modelVersion']) is not None: + setv(to_object, ['model_version'], getv(from_object, ['modelVersion'])) + + if getv(from_object, ['promptFeedback']) is not None: + setv(to_object, ['prompt_feedback'], getv(from_object, ['promptFeedback'])) + + if getv(from_object, ['responseId']) is not None: + setv(to_object, ['response_id'], getv(from_object, ['responseId'])) + + if getv(from_object, ['usageMetadata']) is not None: + setv(to_object, ['usage_metadata'], getv(from_object, ['usageMetadata'])) + + if getv(from_object, ['modelStatus']) is not None: + setv(to_object, ['model_status'], getv(from_object, ['modelStatus'])) + + return to_object + + +def _GetBatchJobParameters_to_mldev( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['name']) is not None: + setv( + to_object, + ['_url', 'name'], + t.t_batch_job_name(api_client, getv(from_object, ['name'])), + ) + + return to_object + + +def _GetBatchJobParameters_to_vertex( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['name']) is not None: + setv( + to_object, + ['_url', 'name'], + t.t_batch_job_name(api_client, getv(from_object, ['name'])), + ) + + return to_object + + +def _GoogleMaps_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['auth_config']) is not None: + setv( + to_object, + ['authConfig'], + _AuthConfig_to_mldev(getv(from_object, ['auth_config']), to_object), + ) + + if getv(from_object, ['enable_widget']) is not None: + setv(to_object, ['enableWidget'], getv(from_object, ['enable_widget'])) + + return to_object + + +def _GoogleSearch_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['search_types']) is not None: + setv(to_object, ['searchTypes'], getv(from_object, ['search_types'])) + + if getv(from_object, ['blocking_confidence']) is not None: + raise ValueError( + 'blocking_confidence parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['exclude_domains']) is not None: + raise ValueError( + 'exclude_domains parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['time_range_filter']) is not None: + setv( + to_object, ['timeRangeFilter'], getv(from_object, ['time_range_filter']) + ) + + return to_object + + +def _ImageConfig_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['aspect_ratio']) is not None: + setv(to_object, ['aspectRatio'], getv(from_object, ['aspect_ratio'])) + + if getv(from_object, ['image_size']) is not None: + setv(to_object, ['imageSize'], getv(from_object, ['image_size'])) + + if getv(from_object, ['person_generation']) is not None: + raise ValueError( + 'person_generation parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['prominent_people']) is not None: + raise ValueError( + 'prominent_people parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['output_mime_type']) is not None: + raise ValueError( + 'output_mime_type parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['output_compression_quality']) is not None: + raise ValueError( + 'output_compression_quality parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['image_output_options']) is not None: + raise ValueError( + 'image_output_options parameter is not supported in Gemini API.' + ) + + return to_object + + +def _InlinedRequest_to_mldev( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['model']) is not None: + setv( + to_object, + ['request', 'model'], + t.t_model(api_client, getv(from_object, ['model'])), + ) + + if getv(from_object, ['contents']) is not None: + setv( + to_object, + ['request', 'contents'], + [ + _Content_to_mldev(item, to_object) + for item in t.t_contents(getv(from_object, ['contents'])) + ], + ) + + if getv(from_object, ['metadata']) is not None: + setv(to_object, ['metadata'], getv(from_object, ['metadata'])) + + if getv(from_object, ['config']) is not None: + setv( + to_object, + ['request', 'generationConfig'], + _GenerateContentConfig_to_mldev( + api_client, + getv(from_object, ['config']), + getv(to_object, ['request'], default_value={}), + ), + ) + + return to_object + + +def _InlinedResponse_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['response']) is not None: + setv( + to_object, + ['response'], + _GenerateContentResponse_from_mldev( + getv(from_object, ['response']), to_object + ), + ) + + if getv(from_object, ['metadata']) is not None: + setv(to_object, ['metadata'], getv(from_object, ['metadata'])) + + if getv(from_object, ['error']) is not None: + setv(to_object, ['error'], getv(from_object, ['error'])) + + return to_object + + +def _ListBatchJobsConfig_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['page_size']) is not None: + setv( + parent_object, ['_query', 'pageSize'], getv(from_object, ['page_size']) + ) + + if getv(from_object, ['page_token']) is not None: + setv( + parent_object, + ['_query', 'pageToken'], + getv(from_object, ['page_token']), + ) + + if getv(from_object, ['filter']) is not None: + raise ValueError('filter parameter is not supported in Gemini API.') + + return to_object + + +def _ListBatchJobsConfig_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['page_size']) is not None: + setv( + parent_object, ['_query', 'pageSize'], getv(from_object, ['page_size']) + ) + + if getv(from_object, ['page_token']) is not None: + setv( + parent_object, + ['_query', 'pageToken'], + getv(from_object, ['page_token']), + ) + + if getv(from_object, ['filter']) is not None: + setv(parent_object, ['_query', 'filter'], getv(from_object, ['filter'])) + + return to_object + + +def _ListBatchJobsParameters_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['config']) is not None: + _ListBatchJobsConfig_to_mldev(getv(from_object, ['config']), to_object) + + return to_object + + +def _ListBatchJobsParameters_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['config']) is not None: + _ListBatchJobsConfig_to_vertex(getv(from_object, ['config']), to_object) + + return to_object + + +def _ListBatchJobsResponse_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['sdkHttpResponse']) is not None: + setv( + to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse']) + ) + + if getv(from_object, ['nextPageToken']) is not None: + setv(to_object, ['next_page_token'], getv(from_object, ['nextPageToken'])) + + if getv(from_object, ['operations']) is not None: + setv( + to_object, + ['batch_jobs'], + [ + _BatchJob_from_mldev(item, to_object) + for item in getv(from_object, ['operations']) + ], + ) + + return to_object + + +def _ListBatchJobsResponse_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['sdkHttpResponse']) is not None: + setv( + to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse']) + ) + + if getv(from_object, ['nextPageToken']) is not None: + setv(to_object, ['next_page_token'], getv(from_object, ['nextPageToken'])) + + if getv(from_object, ['batchPredictionJobs']) is not None: + setv( + to_object, + ['batch_jobs'], + [ + _BatchJob_from_vertex(item, to_object) + for item in getv(from_object, ['batchPredictionJobs']) + ], + ) + + return to_object + + +def _Part_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['media_resolution']) is not None: + setv( + to_object, ['mediaResolution'], getv(from_object, ['media_resolution']) + ) + + if getv(from_object, ['code_execution_result']) is not None: + setv( + to_object, + ['codeExecutionResult'], + getv(from_object, ['code_execution_result']), + ) + + if getv(from_object, ['executable_code']) is not None: + setv(to_object, ['executableCode'], getv(from_object, ['executable_code'])) + + if getv(from_object, ['file_data']) is not None: + setv( + to_object, + ['fileData'], + _FileData_to_mldev(getv(from_object, ['file_data']), to_object), + ) + + if getv(from_object, ['function_call']) is not None: + setv( + to_object, + ['functionCall'], + _FunctionCall_to_mldev(getv(from_object, ['function_call']), to_object), + ) + + if getv(from_object, ['function_response']) is not None: + setv( + to_object, + ['functionResponse'], + getv(from_object, ['function_response']), + ) + + if getv(from_object, ['inline_data']) is not None: + setv( + to_object, + ['inlineData'], + _Blob_to_mldev(getv(from_object, ['inline_data']), to_object), + ) + + if getv(from_object, ['text']) is not None: + setv(to_object, ['text'], getv(from_object, ['text'])) + + if getv(from_object, ['thought']) is not None: + setv(to_object, ['thought'], getv(from_object, ['thought'])) + + if getv(from_object, ['thought_signature']) is not None: + setv( + to_object, + ['thoughtSignature'], + getv(from_object, ['thought_signature']), + ) + + if getv(from_object, ['video_metadata']) is not None: + setv(to_object, ['videoMetadata'], getv(from_object, ['video_metadata'])) + + if getv(from_object, ['tool_call']) is not None: + setv(to_object, ['toolCall'], getv(from_object, ['tool_call'])) + + if getv(from_object, ['tool_response']) is not None: + setv(to_object, ['toolResponse'], getv(from_object, ['tool_response'])) + + if getv(from_object, ['part_metadata']) is not None: + setv(to_object, ['partMetadata'], getv(from_object, ['part_metadata'])) + + return to_object + + +def _SafetySetting_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['category']) is not None: + setv(to_object, ['category'], getv(from_object, ['category'])) + + if getv(from_object, ['method']) is not None: + raise ValueError('method parameter is not supported in Gemini API.') + + if getv(from_object, ['threshold']) is not None: + setv(to_object, ['threshold'], getv(from_object, ['threshold'])) + + return to_object + + +def _ToolConfig_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['retrieval_config']) is not None: + setv( + to_object, ['retrievalConfig'], getv(from_object, ['retrieval_config']) + ) + + if getv(from_object, ['function_calling_config']) is not None: + setv( + to_object, + ['functionCallingConfig'], + _FunctionCallingConfig_to_mldev( + getv(from_object, ['function_calling_config']), to_object + ), + ) + + if getv(from_object, ['include_server_side_tool_invocations']) is not None: + setv( + to_object, + ['includeServerSideToolInvocations'], + getv(from_object, ['include_server_side_tool_invocations']), + ) + + return to_object + + +def _Tool_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['retrieval']) is not None: + raise ValueError('retrieval parameter is not supported in Gemini API.') + + if getv(from_object, ['computer_use']) is not None: + setv(to_object, ['computerUse'], getv(from_object, ['computer_use'])) + + if getv(from_object, ['file_search']) is not None: + setv(to_object, ['fileSearch'], getv(from_object, ['file_search'])) + + if getv(from_object, ['google_search']) is not None: + setv( + to_object, + ['googleSearch'], + _GoogleSearch_to_mldev(getv(from_object, ['google_search']), to_object), + ) + + if getv(from_object, ['google_maps']) is not None: + setv( + to_object, + ['googleMaps'], + _GoogleMaps_to_mldev(getv(from_object, ['google_maps']), to_object), + ) + + if getv(from_object, ['code_execution']) is not None: + setv(to_object, ['codeExecution'], getv(from_object, ['code_execution'])) + + if getv(from_object, ['enterprise_web_search']) is not None: + raise ValueError( + 'enterprise_web_search parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['function_declarations']) is not None: + setv( + to_object, + ['functionDeclarations'], + [item for item in getv(from_object, ['function_declarations'])], + ) + + if getv(from_object, ['google_search_retrieval']) is not None: + setv( + to_object, + ['googleSearchRetrieval'], + getv(from_object, ['google_search_retrieval']), + ) + + if getv(from_object, ['parallel_ai_search']) is not None: + raise ValueError( + 'parallel_ai_search parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['url_context']) is not None: + setv(to_object, ['urlContext'], getv(from_object, ['url_context'])) + + if getv(from_object, ['mcp_servers']) is not None: + setv( + to_object, + ['mcpServers'], + [item for item in getv(from_object, ['mcp_servers'])], + ) + + return to_object + + +class Batches(_api_module.BaseModule): + + def _create( + self, + *, + model: Optional[str] = None, + src: Union[types.BatchJobSourceUnion, types.BatchJobSourceUnionDict], + config: Optional[types.CreateBatchJobConfigOrDict] = None, + ) -> types.BatchJob: + parameter_model = types._CreateBatchJobParameters( + model=model, + src=src, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _CreateBatchJobParameters_to_vertex( + self._api_client, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'batchPredictionJobs'.format_map(request_url_dict) + else: + path = 'batchPredictionJobs' + else: + request_dict = _CreateBatchJobParameters_to_mldev( + self._api_client, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{model}:batchGenerateContent'.format_map(request_url_dict) + else: + path = '{model}:batchGenerateContent' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request( + 'post', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _BatchJob_from_vertex(response_dict) + + if not self._api_client.vertexai: + response_dict = _BatchJob_from_mldev(response_dict) + + return_value = types.BatchJob._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + + self._api_client._verify_response(return_value) + return return_value + + def _create_embeddings( + self, + *, + model: Optional[str] = None, + src: types.EmbeddingsBatchJobSourceOrDict, + config: Optional[types.CreateEmbeddingsBatchJobConfigOrDict] = None, + ) -> types.BatchJob: + parameter_model = types._CreateEmbeddingsBatchJobParameters( + model=model, + src=src, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if self._api_client.vertexai: + raise ValueError( + 'This method is only supported in the Gemini Developer client.' + ) + else: + request_dict = _CreateEmbeddingsBatchJobParameters_to_mldev( + self._api_client, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{model}:asyncBatchEmbedContent'.format_map(request_url_dict) + else: + path = '{model}:asyncBatchEmbedContent' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request( + 'post', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if not self._api_client.vertexai: + response_dict = _BatchJob_from_mldev(response_dict) + + return_value = types.BatchJob._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + + self._api_client._verify_response(return_value) + return return_value + + def get( + self, *, name: str, config: Optional[types.GetBatchJobConfigOrDict] = None + ) -> types.BatchJob: + """Gets a batch job. + + Args: + name (str): A fully-qualified BatchJob resource name or ID. + Example: "projects/.../locations/.../batchPredictionJobs/456" or "456" + when project and location are initialized in the Vertex AI client. Or + "batches/abc" using the Gemini Developer AI client. + + Returns: + A BatchJob object that contains details about the batch job. + + Usage: + + .. code-block:: python + + batch_job = client.batches.get(name='123456789') + print(f"Batch job: {batch_job.name}, state {batch_job.state}") + """ + + parameter_model = types._GetBatchJobParameters( + name=name, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _GetBatchJobParameters_to_vertex( + self._api_client, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'batchPredictionJobs/{name}'.format_map(request_url_dict) + else: + path = 'batchPredictionJobs/{name}' + else: + request_dict = _GetBatchJobParameters_to_mldev( + self._api_client, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'batches/{name}'.format_map(request_url_dict) + else: + path = 'batches/{name}' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request('get', path, request_dict, http_options) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _BatchJob_from_vertex(response_dict) + + if not self._api_client.vertexai: + response_dict = _BatchJob_from_mldev(response_dict) + + return_value = types.BatchJob._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + + self._api_client._verify_response(return_value) + return return_value + + def cancel( + self, + *, + name: str, + config: Optional[types.CancelBatchJobConfigOrDict] = None, + ) -> None: + """Cancels a batch job. + + Only available for batch jobs that are running or pending. + + Args: + name (str): A fully-qualified BatchJob resource name or ID. + Example: "projects/.../locations/.../batchPredictionJobs/456" or "456" + when project and location are initialized in the Vertex AI client. Or + "batches/abc" using the Gemini Developer AI client. + + Usage: + + .. code-block:: python + + client.batches.cancel(name='123456789') + """ + + parameter_model = types._CancelBatchJobParameters( + name=name, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _CancelBatchJobParameters_to_vertex( + self._api_client, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'batchPredictionJobs/{name}:cancel'.format_map(request_url_dict) + else: + path = 'batchPredictionJobs/{name}:cancel' + else: + request_dict = _CancelBatchJobParameters_to_mldev( + self._api_client, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'batches/{name}:cancel'.format_map(request_url_dict) + else: + path = 'batches/{name}:cancel' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + self._api_client.request('post', path, request_dict, http_options) + + def _list( + self, *, config: Optional[types.ListBatchJobsConfigOrDict] = None + ) -> types.ListBatchJobsResponse: + parameter_model = types._ListBatchJobsParameters( + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _ListBatchJobsParameters_to_vertex(parameter_model) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'batchPredictionJobs'.format_map(request_url_dict) + else: + path = 'batchPredictionJobs' + else: + request_dict = _ListBatchJobsParameters_to_mldev(parameter_model) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'batches'.format_map(request_url_dict) + else: + path = 'batches' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request('get', path, request_dict, http_options) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _ListBatchJobsResponse_from_vertex(response_dict) + + if not self._api_client.vertexai: + response_dict = _ListBatchJobsResponse_from_mldev(response_dict) + + return_value = types.ListBatchJobsResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + return_value.sdk_http_response = types.HttpResponse( + headers=response.headers + ) + self._api_client._verify_response(return_value) + return return_value + + def delete( + self, + *, + name: str, + config: Optional[types.DeleteBatchJobConfigOrDict] = None, + ) -> types.DeleteResourceJob: + """Deletes a batch job. + + Args: + name (str): A fully-qualified BatchJob resource name or ID. + Example: "projects/.../locations/.../batchPredictionJobs/456" or "456" + when project and location are initialized in the client. + + Returns: + A DeleteResourceJob object that shows the status of the deletion. + + Usage: + + .. code-block:: python + + client.batches.delete(name='123456789') + """ + + parameter_model = types._DeleteBatchJobParameters( + name=name, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _DeleteBatchJobParameters_to_vertex( + self._api_client, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'batchPredictionJobs/{name}'.format_map(request_url_dict) + else: + path = 'batchPredictionJobs/{name}' + else: + request_dict = _DeleteBatchJobParameters_to_mldev( + self._api_client, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'batches/{name}'.format_map(request_url_dict) + else: + path = 'batches/{name}' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request( + 'delete', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _DeleteResourceJob_from_vertex(response_dict) + + if not self._api_client.vertexai: + response_dict = _DeleteResourceJob_from_mldev(response_dict) + + return_value = types.DeleteResourceJob._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + return_value.sdk_http_response = types.HttpResponse( + headers=response.headers + ) + self._api_client._verify_response(return_value) + return return_value + + def create( + self, + *, + model: str, + src: types.BatchJobSourceUnionDict, + config: Optional[types.CreateBatchJobConfigOrDict] = None, + ) -> types.BatchJob: + """Creates a batch job. + + Args: + model (str): The model to use for the batch job. + src: The source of the batch job. Currently Vertex AI supports GCS URI(-s) + or BigQuery URI. Example: "gs://path/to/input/data" or + "bq://projectId.bqDatasetId.bqTableId". Gemini Developer API supports + List of inlined_request, or file name. Example: "files/file_name". + config (CreateBatchJobConfig): Optional configuration for the batch job. + + Returns: + A BatchJob object that contains details about the batch job. + + Usage: + + .. code-block:: python + + batch_job = client.batches.create( + model="gemini-2.0-flash-001", + src="gs://path/to/input/data", + ) + print(batch_job.state) + """ + src = t.t_batch_job_source(self._api_client, src) + + # Convert all dicts to Pydantic objects. + parameter_model = types._CreateBatchJobParameters( + model=model, + src=src, + config=config, + ) + + if self._api_client.vertexai: + config = _extra_utils.format_destination(src, parameter_model.config) + return self._create(model=model, src=src, config=config) + else: + return self._create(model=model, src=src, config=config) + + def create_embeddings( + self, + *, + model: str, + src: types.EmbeddingsBatchJobSourceOrDict, + config: Optional[types.CreateEmbeddingsBatchJobConfigOrDict] = None, + ) -> types.BatchJob: + """**Experimental** Creates an embedding batch job. + + Args: + model (str): The model to use for the batch job. + src: Gemini Developer API supports List of inlined_request, or file name. + Example: "files/file_name". + config (CreateBatchJobConfig): Optional configuration for the batch job. + + Returns: + A BatchJob object that contains details about the batch job. + + Usage: + + .. code-block:: python + + batch_job = client.batches.create_embeddings( + model="text-embedding-004", + src="files/my_embedding_input", + ) + print(batch_job.state) + """ + import warnings + + warnings.warn( + 'batches.create_embeddings() is experimental and may change without' + ' notice.', + category=_common.ExperimentalWarning, + stacklevel=2, # This is crucial! + ) + src = t.t_embedding_batch_job_source(self._api_client, src) + + # Convert all dicts to Pydantic objects. + parameter_model = types._CreateEmbeddingsBatchJobParameters( + model=model, + src=src, + config=config, + ) + + if self._api_client.vertexai: + raise ValueError('Vertex AI does not support batches.create_embeddings.') + else: + return self._create_embeddings(model=model, src=src, config=config) + + def list( + self, *, config: Optional[types.ListBatchJobsConfigOrDict] = None + ) -> Pager[types.BatchJob]: + """Lists batch jobs. + + Args: + config (ListBatchJobsConfig): Optional configuration for the list request. + + Returns: + A Pager object that contains one page of batch jobs. When iterating over + the pager, it automatically fetches the next page if there are more. + + Usage: + + .. code-block:: python + config = {'page_size': 10} + for batch_job in client.batches.list(config): + print(batch_job.name) + """ + + list_request = self._list + return Pager( + 'batch_jobs', + list_request, + self._list(config=config), + config, + ) + + +class AsyncBatches(_api_module.BaseModule): + + async def _create( + self, + *, + model: Optional[str] = None, + src: Union[types.BatchJobSourceUnion, types.BatchJobSourceUnionDict], + config: Optional[types.CreateBatchJobConfigOrDict] = None, + ) -> types.BatchJob: + parameter_model = types._CreateBatchJobParameters( + model=model, + src=src, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _CreateBatchJobParameters_to_vertex( + self._api_client, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'batchPredictionJobs'.format_map(request_url_dict) + else: + path = 'batchPredictionJobs' + else: + request_dict = _CreateBatchJobParameters_to_mldev( + self._api_client, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{model}:batchGenerateContent'.format_map(request_url_dict) + else: + path = '{model}:batchGenerateContent' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'post', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _BatchJob_from_vertex(response_dict) + + if not self._api_client.vertexai: + response_dict = _BatchJob_from_mldev(response_dict) + + return_value = types.BatchJob._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + + self._api_client._verify_response(return_value) + return return_value + + async def _create_embeddings( + self, + *, + model: Optional[str] = None, + src: types.EmbeddingsBatchJobSourceOrDict, + config: Optional[types.CreateEmbeddingsBatchJobConfigOrDict] = None, + ) -> types.BatchJob: + parameter_model = types._CreateEmbeddingsBatchJobParameters( + model=model, + src=src, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if self._api_client.vertexai: + raise ValueError( + 'This method is only supported in the Gemini Developer client.' + ) + else: + request_dict = _CreateEmbeddingsBatchJobParameters_to_mldev( + self._api_client, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{model}:asyncBatchEmbedContent'.format_map(request_url_dict) + else: + path = '{model}:asyncBatchEmbedContent' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'post', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if not self._api_client.vertexai: + response_dict = _BatchJob_from_mldev(response_dict) + + return_value = types.BatchJob._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + + self._api_client._verify_response(return_value) + return return_value + + async def get( + self, *, name: str, config: Optional[types.GetBatchJobConfigOrDict] = None + ) -> types.BatchJob: + """Gets a batch job. + + Args: + name (str): A fully-qualified BatchJob resource name or ID. + Example: "projects/.../locations/.../batchPredictionJobs/456" or "456" + when project and location are initialized in the Vertex AI client. Or + "batches/abc" using the Gemini Developer AI client. + + Returns: + A BatchJob object that contains details about the batch job. + + Usage: + + .. code-block:: python + + batch_job = await client.aio.batches.get(name='123456789') + print(f"Batch job: {batch_job.name}, state {batch_job.state}") + """ + + parameter_model = types._GetBatchJobParameters( + name=name, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _GetBatchJobParameters_to_vertex( + self._api_client, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'batchPredictionJobs/{name}'.format_map(request_url_dict) + else: + path = 'batchPredictionJobs/{name}' + else: + request_dict = _GetBatchJobParameters_to_mldev( + self._api_client, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'batches/{name}'.format_map(request_url_dict) + else: + path = 'batches/{name}' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'get', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _BatchJob_from_vertex(response_dict) + + if not self._api_client.vertexai: + response_dict = _BatchJob_from_mldev(response_dict) + + return_value = types.BatchJob._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + + self._api_client._verify_response(return_value) + return return_value + + async def cancel( + self, + *, + name: str, + config: Optional[types.CancelBatchJobConfigOrDict] = None, + ) -> None: + """Cancels a batch job. + + Only available for batch jobs that are running or pending. + + Args: + name (str): A fully-qualified BatchJob resource name or ID. + Example: "projects/.../locations/.../batchPredictionJobs/456" or "456" + when project and location are initialized in the Vertex AI client. Or + "batches/abc" using the Gemini Developer AI client. + + Usage: + + .. code-block:: python + + await client.aio.batches.cancel(name='123456789') + """ + + parameter_model = types._CancelBatchJobParameters( + name=name, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _CancelBatchJobParameters_to_vertex( + self._api_client, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'batchPredictionJobs/{name}:cancel'.format_map(request_url_dict) + else: + path = 'batchPredictionJobs/{name}:cancel' + else: + request_dict = _CancelBatchJobParameters_to_mldev( + self._api_client, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'batches/{name}:cancel'.format_map(request_url_dict) + else: + path = 'batches/{name}:cancel' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + await self._api_client.async_request( + 'post', path, request_dict, http_options + ) + + async def _list( + self, *, config: Optional[types.ListBatchJobsConfigOrDict] = None + ) -> types.ListBatchJobsResponse: + parameter_model = types._ListBatchJobsParameters( + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _ListBatchJobsParameters_to_vertex(parameter_model) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'batchPredictionJobs'.format_map(request_url_dict) + else: + path = 'batchPredictionJobs' + else: + request_dict = _ListBatchJobsParameters_to_mldev(parameter_model) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'batches'.format_map(request_url_dict) + else: + path = 'batches' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'get', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _ListBatchJobsResponse_from_vertex(response_dict) + + if not self._api_client.vertexai: + response_dict = _ListBatchJobsResponse_from_mldev(response_dict) + + return_value = types.ListBatchJobsResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + return_value.sdk_http_response = types.HttpResponse( + headers=response.headers + ) + self._api_client._verify_response(return_value) + return return_value + + async def delete( + self, + *, + name: str, + config: Optional[types.DeleteBatchJobConfigOrDict] = None, + ) -> types.DeleteResourceJob: + """Deletes a batch job. + + Args: + name (str): A fully-qualified BatchJob resource name or ID. + Example: "projects/.../locations/.../batchPredictionJobs/456" or "456" + when project and location are initialized in the client. + + Returns: + A DeleteResourceJob object that shows the status of the deletion. + + Usage: + + .. code-block:: python + + await client.aio.batches.delete(name='123456789') + """ + + parameter_model = types._DeleteBatchJobParameters( + name=name, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _DeleteBatchJobParameters_to_vertex( + self._api_client, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'batchPredictionJobs/{name}'.format_map(request_url_dict) + else: + path = 'batchPredictionJobs/{name}' + else: + request_dict = _DeleteBatchJobParameters_to_mldev( + self._api_client, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'batches/{name}'.format_map(request_url_dict) + else: + path = 'batches/{name}' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'delete', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _DeleteResourceJob_from_vertex(response_dict) + + if not self._api_client.vertexai: + response_dict = _DeleteResourceJob_from_mldev(response_dict) + + return_value = types.DeleteResourceJob._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + return_value.sdk_http_response = types.HttpResponse( + headers=response.headers + ) + self._api_client._verify_response(return_value) + return return_value + + async def create( + self, + *, + model: str, + src: types.BatchJobSourceUnionDict, + config: Optional[types.CreateBatchJobConfigOrDict] = None, + ) -> types.BatchJob: + """Creates a batch job asynchronously. + + Args: + model (str): The model to use for the batch job. + src: The source of the batch job. Currently Vertex AI supports GCS URI(-s) + or BigQuery URI. Example: "gs://path/to/input/data" or + "bq://projectId.bqDatasetId.bqTableId". Gemini Develop API supports List + of inlined_request, or file name. Example: "files/file_name". + config (CreateBatchJobConfig): Optional configuration for the batch job. + + Returns: + A BatchJob object that contains details about the batch job. + + Usage: + + .. code-block:: python + + batch_job = await client.aio.batches.create( + model="gemini-2.0-flash-001", + src="gs://path/to/input/data", + ) + """ + src = t.t_batch_job_source(self._api_client, src) + + # Convert all dicts to Pydantic objects. + parameter_model = types._CreateBatchJobParameters( + model=model, + src=src, + config=config, + ) + + if self._api_client.vertexai: + config = _extra_utils.format_destination(src, parameter_model.config) + return await self._create(model=model, src=src, config=config) + else: + return await self._create(model=model, src=src, config=config) + + async def create_embeddings( + self, + *, + model: str, + src: types.EmbeddingsBatchJobSourceOrDict, + config: Optional[types.CreateEmbeddingsBatchJobConfigOrDict] = None, + ) -> types.BatchJob: + """**Experimental** Creates an asynchronously embedding batch job. + + Args: + model (str): The model to use for the batch job. + src: Gemini Developer API supports inlined_requests, or file name. + Example: "files/file_name". + config (CreateBatchJobConfig): Optional configuration for the batch job. + + Returns: + A BatchJob object that contains details about the batch job. + + Usage: + + .. code-block:: python + + batch_job = await client.aio.batches.create_embeddings( + model="text-embedding-004", + src="files/my_embedding_input", + ) + print(batch_job.state) + """ + import warnings + + warnings.warn( + 'batches.create_embeddings() is experimental and may change without' + ' notice.', + category=_common.ExperimentalWarning, + stacklevel=2, # This is crucial! + ) + src = t.t_embedding_batch_job_source(self._api_client, src) + + # Convert all dicts to Pydantic objects. + parameter_model = types._CreateEmbeddingsBatchJobParameters( + model=model, + src=src, + config=config, + ) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + if self._api_client.vertexai: + raise ValueError('Vertex AI does not support batches.create_embeddings.') + else: + return await self._create_embeddings(model=model, src=src, config=config) + + async def list( + self, *, config: Optional[types.ListBatchJobsConfigOrDict] = None + ) -> AsyncPager[types.BatchJob]: + """Lists batch jobs asynchronously. + + Args: + config (ListBatchJobsConfig): Optional configuration for the list request. + + Returns: + A Pager object that contains one page of batch jobs. When iterating over + the pager, it automatically fetches the next page if there are more. + + Usage: + + .. code-block:: python + async for batch_job in await client.aio.batches.list(): + print(batch_job.name) + """ + + list_request = self._list + return AsyncPager( + 'batch_jobs', + list_request, + await self._list(config=config), + config, + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/caches.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/caches.py new file mode 100644 index 0000000000000000000000000000000000000000..78ad519211abe69c98cafe69433c99291d601c1b --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/caches.py @@ -0,0 +1,1950 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# Code generated by the Google Gen AI SDK generator DO NOT EDIT. + +import json +import logging +from typing import Any, Optional, Union +from urllib.parse import urlencode + +from . import _api_module +from . import _common +from . import _transformers as t +from . import types +from ._api_client import BaseApiClient +from ._common import get_value_by_path as getv +from ._common import set_value_by_path as setv +from .pagers import AsyncPager, Pager + +logger = logging.getLogger('google_genai.caches') + + +def _AuthConfig_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['api_key']) is not None: + setv(to_object, ['apiKey'], getv(from_object, ['api_key'])) + + if getv(from_object, ['api_key_config']) is not None: + raise ValueError('api_key_config parameter is not supported in Gemini API.') + + if getv(from_object, ['auth_type']) is not None: + raise ValueError('auth_type parameter is not supported in Gemini API.') + + if getv(from_object, ['google_service_account_config']) is not None: + raise ValueError( + 'google_service_account_config parameter is not supported in Gemini' + ' API.' + ) + + if getv(from_object, ['http_basic_auth_config']) is not None: + raise ValueError( + 'http_basic_auth_config parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['oauth_config']) is not None: + raise ValueError('oauth_config parameter is not supported in Gemini API.') + + if getv(from_object, ['oidc_config']) is not None: + raise ValueError('oidc_config parameter is not supported in Gemini API.') + + return to_object + + +def _Blob_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['data']) is not None: + setv(to_object, ['data'], getv(from_object, ['data'])) + + if getv(from_object, ['display_name']) is not None: + raise ValueError('display_name parameter is not supported in Gemini API.') + + if getv(from_object, ['mime_type']) is not None: + setv(to_object, ['mimeType'], getv(from_object, ['mime_type'])) + + return to_object + + +def _Content_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['parts']) is not None: + setv( + to_object, + ['parts'], + [ + _Part_to_mldev(item, to_object) + for item in getv(from_object, ['parts']) + ], + ) + + if getv(from_object, ['role']) is not None: + setv(to_object, ['role'], getv(from_object, ['role'])) + + return to_object + + +def _Content_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['parts']) is not None: + setv( + to_object, + ['parts'], + [ + _Part_to_vertex(item, to_object) + for item in getv(from_object, ['parts']) + ], + ) + + if getv(from_object, ['role']) is not None: + setv(to_object, ['role'], getv(from_object, ['role'])) + + return to_object + + +def _CreateCachedContentConfig_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['ttl']) is not None: + setv(parent_object, ['ttl'], getv(from_object, ['ttl'])) + + if getv(from_object, ['expire_time']) is not None: + setv(parent_object, ['expireTime'], getv(from_object, ['expire_time'])) + + if getv(from_object, ['display_name']) is not None: + setv(parent_object, ['displayName'], getv(from_object, ['display_name'])) + + if getv(from_object, ['contents']) is not None: + setv( + parent_object, + ['contents'], + [ + _Content_to_mldev(item, to_object) + for item in t.t_contents(getv(from_object, ['contents'])) + ], + ) + + if getv(from_object, ['system_instruction']) is not None: + setv( + parent_object, + ['systemInstruction'], + _Content_to_mldev( + t.t_content(getv(from_object, ['system_instruction'])), to_object + ), + ) + + if getv(from_object, ['tools']) is not None: + setv( + parent_object, + ['tools'], + [ + _Tool_to_mldev(item, to_object) + for item in getv(from_object, ['tools']) + ], + ) + + if getv(from_object, ['tool_config']) is not None: + setv( + parent_object, + ['toolConfig'], + _ToolConfig_to_mldev(getv(from_object, ['tool_config']), to_object), + ) + + if getv(from_object, ['kms_key_name']) is not None: + raise ValueError('kms_key_name parameter is not supported in Gemini API.') + + return to_object + + +def _CreateCachedContentConfig_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['ttl']) is not None: + setv(parent_object, ['ttl'], getv(from_object, ['ttl'])) + + if getv(from_object, ['expire_time']) is not None: + setv(parent_object, ['expireTime'], getv(from_object, ['expire_time'])) + + if getv(from_object, ['display_name']) is not None: + setv(parent_object, ['displayName'], getv(from_object, ['display_name'])) + + if getv(from_object, ['contents']) is not None: + setv( + parent_object, + ['contents'], + [ + _Content_to_vertex(item, to_object) + for item in t.t_contents(getv(from_object, ['contents'])) + ], + ) + + if getv(from_object, ['system_instruction']) is not None: + setv( + parent_object, + ['systemInstruction'], + _Content_to_vertex( + t.t_content(getv(from_object, ['system_instruction'])), to_object + ), + ) + + if getv(from_object, ['tools']) is not None: + setv( + parent_object, + ['tools'], + [ + _Tool_to_vertex(item, to_object) + for item in getv(from_object, ['tools']) + ], + ) + + if getv(from_object, ['tool_config']) is not None: + setv( + parent_object, + ['toolConfig'], + _ToolConfig_to_vertex(getv(from_object, ['tool_config']), to_object), + ) + + if getv(from_object, ['kms_key_name']) is not None: + setv( + parent_object, + ['encryption_spec', 'kmsKeyName'], + getv(from_object, ['kms_key_name']), + ) + + return to_object + + +def _CreateCachedContentParameters_to_mldev( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['model']) is not None: + setv( + to_object, + ['model'], + t.t_caches_model(api_client, getv(from_object, ['model'])), + ) + + if getv(from_object, ['config']) is not None: + _CreateCachedContentConfig_to_mldev( + getv(from_object, ['config']), to_object + ) + + return to_object + + +def _CreateCachedContentParameters_to_vertex( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['model']) is not None: + setv( + to_object, + ['model'], + t.t_caches_model(api_client, getv(from_object, ['model'])), + ) + + if getv(from_object, ['config']) is not None: + _CreateCachedContentConfig_to_vertex( + getv(from_object, ['config']), to_object + ) + + return to_object + + +def _DeleteCachedContentParameters_to_mldev( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['name']) is not None: + setv( + to_object, + ['_url', 'name'], + t.t_cached_content_name(api_client, getv(from_object, ['name'])), + ) + + return to_object + + +def _DeleteCachedContentParameters_to_vertex( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['name']) is not None: + setv( + to_object, + ['_url', 'name'], + t.t_cached_content_name(api_client, getv(from_object, ['name'])), + ) + + return to_object + + +def _DeleteCachedContentResponse_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['sdkHttpResponse']) is not None: + setv( + to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse']) + ) + + return to_object + + +def _DeleteCachedContentResponse_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['sdkHttpResponse']) is not None: + setv( + to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse']) + ) + + return to_object + + +def _FileData_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['display_name']) is not None: + raise ValueError('display_name parameter is not supported in Gemini API.') + + if getv(from_object, ['file_uri']) is not None: + setv(to_object, ['fileUri'], getv(from_object, ['file_uri'])) + + if getv(from_object, ['mime_type']) is not None: + setv(to_object, ['mimeType'], getv(from_object, ['mime_type'])) + + return to_object + + +def _FunctionCall_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['id']) is not None: + setv(to_object, ['id'], getv(from_object, ['id'])) + + if getv(from_object, ['args']) is not None: + setv(to_object, ['args'], getv(from_object, ['args'])) + + if getv(from_object, ['name']) is not None: + setv(to_object, ['name'], getv(from_object, ['name'])) + + if getv(from_object, ['partial_args']) is not None: + raise ValueError('partial_args parameter is not supported in Gemini API.') + + if getv(from_object, ['will_continue']) is not None: + raise ValueError('will_continue parameter is not supported in Gemini API.') + + return to_object + + +def _FunctionCallingConfig_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['allowed_function_names']) is not None: + setv( + to_object, + ['allowedFunctionNames'], + getv(from_object, ['allowed_function_names']), + ) + + if getv(from_object, ['mode']) is not None: + setv(to_object, ['mode'], getv(from_object, ['mode'])) + + if getv(from_object, ['stream_function_call_arguments']) is not None: + raise ValueError( + 'stream_function_call_arguments parameter is not supported in Gemini' + ' API.' + ) + + return to_object + + +def _FunctionDeclaration_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['description']) is not None: + setv(to_object, ['description'], getv(from_object, ['description'])) + + if getv(from_object, ['name']) is not None: + setv(to_object, ['name'], getv(from_object, ['name'])) + + if getv(from_object, ['parameters']) is not None: + setv(to_object, ['parameters'], getv(from_object, ['parameters'])) + + if getv(from_object, ['parameters_json_schema']) is not None: + setv( + to_object, + ['parametersJsonSchema'], + getv(from_object, ['parameters_json_schema']), + ) + + if getv(from_object, ['response']) is not None: + setv(to_object, ['response'], getv(from_object, ['response'])) + + if getv(from_object, ['response_json_schema']) is not None: + setv( + to_object, + ['responseJsonSchema'], + getv(from_object, ['response_json_schema']), + ) + + if getv(from_object, ['behavior']) is not None: + raise ValueError('behavior parameter is not supported in Vertex AI.') + + return to_object + + +def _GetCachedContentParameters_to_mldev( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['name']) is not None: + setv( + to_object, + ['_url', 'name'], + t.t_cached_content_name(api_client, getv(from_object, ['name'])), + ) + + return to_object + + +def _GetCachedContentParameters_to_vertex( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['name']) is not None: + setv( + to_object, + ['_url', 'name'], + t.t_cached_content_name(api_client, getv(from_object, ['name'])), + ) + + return to_object + + +def _GoogleMaps_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['auth_config']) is not None: + setv( + to_object, + ['authConfig'], + _AuthConfig_to_mldev(getv(from_object, ['auth_config']), to_object), + ) + + if getv(from_object, ['enable_widget']) is not None: + setv(to_object, ['enableWidget'], getv(from_object, ['enable_widget'])) + + return to_object + + +def _GoogleSearch_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['search_types']) is not None: + setv(to_object, ['searchTypes'], getv(from_object, ['search_types'])) + + if getv(from_object, ['blocking_confidence']) is not None: + raise ValueError( + 'blocking_confidence parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['exclude_domains']) is not None: + raise ValueError( + 'exclude_domains parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['time_range_filter']) is not None: + setv( + to_object, ['timeRangeFilter'], getv(from_object, ['time_range_filter']) + ) + + return to_object + + +def _ListCachedContentsConfig_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['page_size']) is not None: + setv( + parent_object, ['_query', 'pageSize'], getv(from_object, ['page_size']) + ) + + if getv(from_object, ['page_token']) is not None: + setv( + parent_object, + ['_query', 'pageToken'], + getv(from_object, ['page_token']), + ) + + return to_object + + +def _ListCachedContentsConfig_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['page_size']) is not None: + setv( + parent_object, ['_query', 'pageSize'], getv(from_object, ['page_size']) + ) + + if getv(from_object, ['page_token']) is not None: + setv( + parent_object, + ['_query', 'pageToken'], + getv(from_object, ['page_token']), + ) + + return to_object + + +def _ListCachedContentsParameters_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['config']) is not None: + _ListCachedContentsConfig_to_mldev(getv(from_object, ['config']), to_object) + + return to_object + + +def _ListCachedContentsParameters_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['config']) is not None: + _ListCachedContentsConfig_to_vertex( + getv(from_object, ['config']), to_object + ) + + return to_object + + +def _ListCachedContentsResponse_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['sdkHttpResponse']) is not None: + setv( + to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse']) + ) + + if getv(from_object, ['nextPageToken']) is not None: + setv(to_object, ['next_page_token'], getv(from_object, ['nextPageToken'])) + + if getv(from_object, ['cachedContents']) is not None: + setv( + to_object, + ['cached_contents'], + [item for item in getv(from_object, ['cachedContents'])], + ) + + return to_object + + +def _ListCachedContentsResponse_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['sdkHttpResponse']) is not None: + setv( + to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse']) + ) + + if getv(from_object, ['nextPageToken']) is not None: + setv(to_object, ['next_page_token'], getv(from_object, ['nextPageToken'])) + + if getv(from_object, ['cachedContents']) is not None: + setv( + to_object, + ['cached_contents'], + [item for item in getv(from_object, ['cachedContents'])], + ) + + return to_object + + +def _Part_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['media_resolution']) is not None: + setv( + to_object, ['mediaResolution'], getv(from_object, ['media_resolution']) + ) + + if getv(from_object, ['code_execution_result']) is not None: + setv( + to_object, + ['codeExecutionResult'], + getv(from_object, ['code_execution_result']), + ) + + if getv(from_object, ['executable_code']) is not None: + setv(to_object, ['executableCode'], getv(from_object, ['executable_code'])) + + if getv(from_object, ['file_data']) is not None: + setv( + to_object, + ['fileData'], + _FileData_to_mldev(getv(from_object, ['file_data']), to_object), + ) + + if getv(from_object, ['function_call']) is not None: + setv( + to_object, + ['functionCall'], + _FunctionCall_to_mldev(getv(from_object, ['function_call']), to_object), + ) + + if getv(from_object, ['function_response']) is not None: + setv( + to_object, + ['functionResponse'], + getv(from_object, ['function_response']), + ) + + if getv(from_object, ['inline_data']) is not None: + setv( + to_object, + ['inlineData'], + _Blob_to_mldev(getv(from_object, ['inline_data']), to_object), + ) + + if getv(from_object, ['text']) is not None: + setv(to_object, ['text'], getv(from_object, ['text'])) + + if getv(from_object, ['thought']) is not None: + setv(to_object, ['thought'], getv(from_object, ['thought'])) + + if getv(from_object, ['thought_signature']) is not None: + setv( + to_object, + ['thoughtSignature'], + getv(from_object, ['thought_signature']), + ) + + if getv(from_object, ['video_metadata']) is not None: + setv(to_object, ['videoMetadata'], getv(from_object, ['video_metadata'])) + + if getv(from_object, ['tool_call']) is not None: + setv(to_object, ['toolCall'], getv(from_object, ['tool_call'])) + + if getv(from_object, ['tool_response']) is not None: + setv(to_object, ['toolResponse'], getv(from_object, ['tool_response'])) + + if getv(from_object, ['part_metadata']) is not None: + setv(to_object, ['partMetadata'], getv(from_object, ['part_metadata'])) + + return to_object + + +def _Part_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['media_resolution']) is not None: + setv( + to_object, ['mediaResolution'], getv(from_object, ['media_resolution']) + ) + + if getv(from_object, ['code_execution_result']) is not None: + setv( + to_object, + ['codeExecutionResult'], + getv(from_object, ['code_execution_result']), + ) + + if getv(from_object, ['executable_code']) is not None: + setv(to_object, ['executableCode'], getv(from_object, ['executable_code'])) + + if getv(from_object, ['file_data']) is not None: + setv(to_object, ['fileData'], getv(from_object, ['file_data'])) + + if getv(from_object, ['function_call']) is not None: + setv(to_object, ['functionCall'], getv(from_object, ['function_call'])) + + if getv(from_object, ['function_response']) is not None: + setv( + to_object, + ['functionResponse'], + getv(from_object, ['function_response']), + ) + + if getv(from_object, ['inline_data']) is not None: + setv(to_object, ['inlineData'], getv(from_object, ['inline_data'])) + + if getv(from_object, ['text']) is not None: + setv(to_object, ['text'], getv(from_object, ['text'])) + + if getv(from_object, ['thought']) is not None: + setv(to_object, ['thought'], getv(from_object, ['thought'])) + + if getv(from_object, ['thought_signature']) is not None: + setv( + to_object, + ['thoughtSignature'], + getv(from_object, ['thought_signature']), + ) + + if getv(from_object, ['video_metadata']) is not None: + setv(to_object, ['videoMetadata'], getv(from_object, ['video_metadata'])) + + if getv(from_object, ['tool_call']) is not None: + raise ValueError('tool_call parameter is not supported in Vertex AI.') + + if getv(from_object, ['tool_response']) is not None: + raise ValueError('tool_response parameter is not supported in Vertex AI.') + + if getv(from_object, ['part_metadata']) is not None: + raise ValueError('part_metadata parameter is not supported in Vertex AI.') + + return to_object + + +def _ToolConfig_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['retrieval_config']) is not None: + setv( + to_object, ['retrievalConfig'], getv(from_object, ['retrieval_config']) + ) + + if getv(from_object, ['function_calling_config']) is not None: + setv( + to_object, + ['functionCallingConfig'], + _FunctionCallingConfig_to_mldev( + getv(from_object, ['function_calling_config']), to_object + ), + ) + + if getv(from_object, ['include_server_side_tool_invocations']) is not None: + setv( + to_object, + ['includeServerSideToolInvocations'], + getv(from_object, ['include_server_side_tool_invocations']), + ) + + return to_object + + +def _ToolConfig_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['retrieval_config']) is not None: + setv( + to_object, ['retrievalConfig'], getv(from_object, ['retrieval_config']) + ) + + if getv(from_object, ['function_calling_config']) is not None: + setv( + to_object, + ['functionCallingConfig'], + getv(from_object, ['function_calling_config']), + ) + + if getv(from_object, ['include_server_side_tool_invocations']) is not None: + raise ValueError( + 'include_server_side_tool_invocations parameter is not supported in' + ' Vertex AI.' + ) + + return to_object + + +def _Tool_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['retrieval']) is not None: + raise ValueError('retrieval parameter is not supported in Gemini API.') + + if getv(from_object, ['computer_use']) is not None: + setv(to_object, ['computerUse'], getv(from_object, ['computer_use'])) + + if getv(from_object, ['file_search']) is not None: + setv(to_object, ['fileSearch'], getv(from_object, ['file_search'])) + + if getv(from_object, ['google_search']) is not None: + setv( + to_object, + ['googleSearch'], + _GoogleSearch_to_mldev(getv(from_object, ['google_search']), to_object), + ) + + if getv(from_object, ['google_maps']) is not None: + setv( + to_object, + ['googleMaps'], + _GoogleMaps_to_mldev(getv(from_object, ['google_maps']), to_object), + ) + + if getv(from_object, ['code_execution']) is not None: + setv(to_object, ['codeExecution'], getv(from_object, ['code_execution'])) + + if getv(from_object, ['enterprise_web_search']) is not None: + raise ValueError( + 'enterprise_web_search parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['function_declarations']) is not None: + setv( + to_object, + ['functionDeclarations'], + [item for item in getv(from_object, ['function_declarations'])], + ) + + if getv(from_object, ['google_search_retrieval']) is not None: + setv( + to_object, + ['googleSearchRetrieval'], + getv(from_object, ['google_search_retrieval']), + ) + + if getv(from_object, ['parallel_ai_search']) is not None: + raise ValueError( + 'parallel_ai_search parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['url_context']) is not None: + setv(to_object, ['urlContext'], getv(from_object, ['url_context'])) + + if getv(from_object, ['mcp_servers']) is not None: + setv( + to_object, + ['mcpServers'], + [item for item in getv(from_object, ['mcp_servers'])], + ) + + return to_object + + +def _Tool_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['retrieval']) is not None: + setv(to_object, ['retrieval'], getv(from_object, ['retrieval'])) + + if getv(from_object, ['computer_use']) is not None: + setv(to_object, ['computerUse'], getv(from_object, ['computer_use'])) + + if getv(from_object, ['file_search']) is not None: + raise ValueError('file_search parameter is not supported in Vertex AI.') + + if getv(from_object, ['google_search']) is not None: + setv(to_object, ['googleSearch'], getv(from_object, ['google_search'])) + + if getv(from_object, ['google_maps']) is not None: + setv(to_object, ['googleMaps'], getv(from_object, ['google_maps'])) + + if getv(from_object, ['code_execution']) is not None: + setv(to_object, ['codeExecution'], getv(from_object, ['code_execution'])) + + if getv(from_object, ['enterprise_web_search']) is not None: + setv( + to_object, + ['enterpriseWebSearch'], + getv(from_object, ['enterprise_web_search']), + ) + + if getv(from_object, ['function_declarations']) is not None: + setv( + to_object, + ['functionDeclarations'], + [ + _FunctionDeclaration_to_vertex(item, to_object) + for item in getv(from_object, ['function_declarations']) + ], + ) + + if getv(from_object, ['google_search_retrieval']) is not None: + setv( + to_object, + ['googleSearchRetrieval'], + getv(from_object, ['google_search_retrieval']), + ) + + if getv(from_object, ['parallel_ai_search']) is not None: + setv( + to_object, + ['parallelAiSearch'], + getv(from_object, ['parallel_ai_search']), + ) + + if getv(from_object, ['url_context']) is not None: + setv(to_object, ['urlContext'], getv(from_object, ['url_context'])) + + if getv(from_object, ['mcp_servers']) is not None: + raise ValueError('mcp_servers parameter is not supported in Vertex AI.') + + return to_object + + +def _UpdateCachedContentConfig_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['ttl']) is not None: + setv(parent_object, ['ttl'], getv(from_object, ['ttl'])) + + if getv(from_object, ['expire_time']) is not None: + setv(parent_object, ['expireTime'], getv(from_object, ['expire_time'])) + + return to_object + + +def _UpdateCachedContentConfig_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['ttl']) is not None: + setv(parent_object, ['ttl'], getv(from_object, ['ttl'])) + + if getv(from_object, ['expire_time']) is not None: + setv(parent_object, ['expireTime'], getv(from_object, ['expire_time'])) + + return to_object + + +def _UpdateCachedContentParameters_to_mldev( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['name']) is not None: + setv( + to_object, + ['_url', 'name'], + t.t_cached_content_name(api_client, getv(from_object, ['name'])), + ) + + if getv(from_object, ['config']) is not None: + _UpdateCachedContentConfig_to_mldev( + getv(from_object, ['config']), to_object + ) + + return to_object + + +def _UpdateCachedContentParameters_to_vertex( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['name']) is not None: + setv( + to_object, + ['_url', 'name'], + t.t_cached_content_name(api_client, getv(from_object, ['name'])), + ) + + if getv(from_object, ['config']) is not None: + _UpdateCachedContentConfig_to_vertex( + getv(from_object, ['config']), to_object + ) + + return to_object + + +class Caches(_api_module.BaseModule): + + def create( + self, + *, + model: str, + config: Optional[types.CreateCachedContentConfigOrDict] = None, + ) -> types.CachedContent: + """Creates a cached contents resource. + + Usage: + + .. code-block:: python + + contents = ... // Initialize the content to cache. + response = client.caches.create( + model= ... // The publisher model id + contents=contents, + config={ + 'display_name': 'test cache', + 'system_instruction': 'What is the sum of the two pdfs?', + 'ttl': '86400s', + }, + ) + """ + + parameter_model = types._CreateCachedContentParameters( + model=model, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _CreateCachedContentParameters_to_vertex( + self._api_client, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'cachedContents'.format_map(request_url_dict) + else: + path = 'cachedContents' + else: + request_dict = _CreateCachedContentParameters_to_mldev( + self._api_client, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'cachedContents'.format_map(request_url_dict) + else: + path = 'cachedContents' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request( + 'post', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + return_value = types.CachedContent._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + + self._api_client._verify_response(return_value) + return return_value + + def get( + self, + *, + name: str, + config: Optional[types.GetCachedContentConfigOrDict] = None, + ) -> types.CachedContent: + """Gets cached content configurations. + + .. code-block:: python + + client.caches.get(name= ... ) // The server-generated resource name. + """ + + parameter_model = types._GetCachedContentParameters( + name=name, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _GetCachedContentParameters_to_vertex( + self._api_client, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{name}'.format_map(request_url_dict) + else: + path = '{name}' + else: + request_dict = _GetCachedContentParameters_to_mldev( + self._api_client, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{name}'.format_map(request_url_dict) + else: + path = '{name}' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request('get', path, request_dict, http_options) + + response_dict = {} if not response.body else json.loads(response.body) + + return_value = types.CachedContent._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + + self._api_client._verify_response(return_value) + return return_value + + def delete( + self, + *, + name: str, + config: Optional[types.DeleteCachedContentConfigOrDict] = None, + ) -> types.DeleteCachedContentResponse: + """Deletes cached content. + + Usage: + + .. code-block:: python + + client.caches.delete(name= ... ) // The server-generated resource name. + """ + + parameter_model = types._DeleteCachedContentParameters( + name=name, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _DeleteCachedContentParameters_to_vertex( + self._api_client, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{name}'.format_map(request_url_dict) + else: + path = '{name}' + else: + request_dict = _DeleteCachedContentParameters_to_mldev( + self._api_client, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{name}'.format_map(request_url_dict) + else: + path = '{name}' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request( + 'delete', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _DeleteCachedContentResponse_from_vertex(response_dict) + + if not self._api_client.vertexai: + response_dict = _DeleteCachedContentResponse_from_mldev(response_dict) + + return_value = types.DeleteCachedContentResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + return_value.sdk_http_response = types.HttpResponse( + headers=response.headers + ) + self._api_client._verify_response(return_value) + return return_value + + def update( + self, + *, + name: str, + config: Optional[types.UpdateCachedContentConfigOrDict] = None, + ) -> types.CachedContent: + """Updates cached content configurations. + + .. code-block:: python + + response = client.caches.update( + name= ... // The server-generated resource name. + config={ + 'ttl': '7600s', + }, + ) + """ + + parameter_model = types._UpdateCachedContentParameters( + name=name, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _UpdateCachedContentParameters_to_vertex( + self._api_client, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{name}'.format_map(request_url_dict) + else: + path = '{name}' + else: + request_dict = _UpdateCachedContentParameters_to_mldev( + self._api_client, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{name}'.format_map(request_url_dict) + else: + path = '{name}' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request( + 'patch', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + return_value = types.CachedContent._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + + self._api_client._verify_response(return_value) + return return_value + + def _list( + self, *, config: Optional[types.ListCachedContentsConfigOrDict] = None + ) -> types.ListCachedContentsResponse: + parameter_model = types._ListCachedContentsParameters( + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _ListCachedContentsParameters_to_vertex(parameter_model) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'cachedContents'.format_map(request_url_dict) + else: + path = 'cachedContents' + else: + request_dict = _ListCachedContentsParameters_to_mldev(parameter_model) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'cachedContents'.format_map(request_url_dict) + else: + path = 'cachedContents' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request('get', path, request_dict, http_options) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _ListCachedContentsResponse_from_vertex(response_dict) + + if not self._api_client.vertexai: + response_dict = _ListCachedContentsResponse_from_mldev(response_dict) + + return_value = types.ListCachedContentsResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + return_value.sdk_http_response = types.HttpResponse( + headers=response.headers + ) + self._api_client._verify_response(return_value) + return return_value + + def list( + self, *, config: Optional[types.ListCachedContentsConfigOrDict] = None + ) -> Pager[types.CachedContent]: + """Lists cached contents. + + Args: + config (ListCachedContentsConfig): Optional configuration for the list + request. + + Returns: + A Pager object that contains one page of cached contents. When iterating + over + the pager, it automatically fetches the next page if there are more. + + Usage: + + .. code-block:: python + for cached_content in client.caches.list(): + print(cached_content.name) + """ + + list_request = self._list + return Pager( + 'cached_contents', + list_request, + self._list(config=config), + config, + ) + + +class AsyncCaches(_api_module.BaseModule): + + async def create( + self, + *, + model: str, + config: Optional[types.CreateCachedContentConfigOrDict] = None, + ) -> types.CachedContent: + """Creates a cached contents resource. + + Usage: + + .. code-block:: python + + contents = ... // Initialize the content to cache. + response = await client.aio.caches.create( + model= ... // The publisher model id + contents=contents, + config={ + 'display_name': 'test cache', + 'system_instruction': 'What is the sum of the two pdfs?', + 'ttl': '86400s', + }, + ) + """ + + parameter_model = types._CreateCachedContentParameters( + model=model, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _CreateCachedContentParameters_to_vertex( + self._api_client, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'cachedContents'.format_map(request_url_dict) + else: + path = 'cachedContents' + else: + request_dict = _CreateCachedContentParameters_to_mldev( + self._api_client, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'cachedContents'.format_map(request_url_dict) + else: + path = 'cachedContents' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'post', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + return_value = types.CachedContent._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + + self._api_client._verify_response(return_value) + return return_value + + async def get( + self, + *, + name: str, + config: Optional[types.GetCachedContentConfigOrDict] = None, + ) -> types.CachedContent: + """Gets cached content configurations. + + .. code-block:: python + + await client.aio.caches.get(name= ... ) // The server-generated resource + name. + """ + + parameter_model = types._GetCachedContentParameters( + name=name, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _GetCachedContentParameters_to_vertex( + self._api_client, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{name}'.format_map(request_url_dict) + else: + path = '{name}' + else: + request_dict = _GetCachedContentParameters_to_mldev( + self._api_client, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{name}'.format_map(request_url_dict) + else: + path = '{name}' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'get', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + return_value = types.CachedContent._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + + self._api_client._verify_response(return_value) + return return_value + + async def delete( + self, + *, + name: str, + config: Optional[types.DeleteCachedContentConfigOrDict] = None, + ) -> types.DeleteCachedContentResponse: + """Deletes cached content. + + Usage: + + .. code-block:: python + + await client.aio.caches.delete(name= ... ) // The server-generated + resource name. + """ + + parameter_model = types._DeleteCachedContentParameters( + name=name, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _DeleteCachedContentParameters_to_vertex( + self._api_client, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{name}'.format_map(request_url_dict) + else: + path = '{name}' + else: + request_dict = _DeleteCachedContentParameters_to_mldev( + self._api_client, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{name}'.format_map(request_url_dict) + else: + path = '{name}' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'delete', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _DeleteCachedContentResponse_from_vertex(response_dict) + + if not self._api_client.vertexai: + response_dict = _DeleteCachedContentResponse_from_mldev(response_dict) + + return_value = types.DeleteCachedContentResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + return_value.sdk_http_response = types.HttpResponse( + headers=response.headers + ) + self._api_client._verify_response(return_value) + return return_value + + async def update( + self, + *, + name: str, + config: Optional[types.UpdateCachedContentConfigOrDict] = None, + ) -> types.CachedContent: + """Updates cached content configurations. + + .. code-block:: python + + response = await client.aio.caches.update( + name= ... // The server-generated resource name. + config={ + 'ttl': '7600s', + }, + ) + """ + + parameter_model = types._UpdateCachedContentParameters( + name=name, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _UpdateCachedContentParameters_to_vertex( + self._api_client, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{name}'.format_map(request_url_dict) + else: + path = '{name}' + else: + request_dict = _UpdateCachedContentParameters_to_mldev( + self._api_client, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{name}'.format_map(request_url_dict) + else: + path = '{name}' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'patch', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + return_value = types.CachedContent._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + + self._api_client._verify_response(return_value) + return return_value + + async def _list( + self, *, config: Optional[types.ListCachedContentsConfigOrDict] = None + ) -> types.ListCachedContentsResponse: + parameter_model = types._ListCachedContentsParameters( + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _ListCachedContentsParameters_to_vertex(parameter_model) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'cachedContents'.format_map(request_url_dict) + else: + path = 'cachedContents' + else: + request_dict = _ListCachedContentsParameters_to_mldev(parameter_model) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'cachedContents'.format_map(request_url_dict) + else: + path = 'cachedContents' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'get', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _ListCachedContentsResponse_from_vertex(response_dict) + + if not self._api_client.vertexai: + response_dict = _ListCachedContentsResponse_from_mldev(response_dict) + + return_value = types.ListCachedContentsResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + return_value.sdk_http_response = types.HttpResponse( + headers=response.headers + ) + self._api_client._verify_response(return_value) + return return_value + + async def list( + self, *, config: Optional[types.ListCachedContentsConfigOrDict] = None + ) -> AsyncPager[types.CachedContent]: + """Lists cached contents asynchronously. + + Args: + config (ListCachedContentsConfig): Optional configuration for the list + request. + + Returns: + A Pager object that contains one page of cached contents. When iterating + over + the pager, it automatically fetches the next page if there are more. + + Usage: + + .. code-block:: python + async for cached_content in await client.aio.caches.list(): + print(cached_content.name) + """ + + list_request = self._list + return AsyncPager( + 'cached_contents', + list_request, + await self._list(config=config), + config, + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/chats.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/chats.py new file mode 100644 index 0000000000000000000000000000000000000000..3d5e181e9f29b5cd65445079301344aae6f7287f --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/chats.py @@ -0,0 +1,529 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +from collections.abc import Iterator +import sys +from typing import AsyncIterator, Awaitable, Optional, Union, get_args + +from . import _transformers as t +from . import types +from .models import AsyncModels, Models +from .types import Content, ContentOrDict, GenerateContentConfigOrDict, GenerateContentResponse, Part, PartUnionDict + + +if sys.version_info >= (3, 10): + from typing import TypeGuard +else: + from typing_extensions import TypeGuard + + +def _validate_content(content: Content) -> bool: + if not content.parts: + return False + for part in content.parts: + if part == Part(): + return False + return True + + +def _validate_contents(contents: list[Content]) -> bool: + if not contents: + return False + for content in contents: + if not _validate_content(content): + return False + return True + + +def _validate_response(response: GenerateContentResponse) -> bool: + if not response.candidates: + return False + if not response.candidates[0].content: + return False + return _validate_content(response.candidates[0].content) + + +def _extract_curated_history( + comprehensive_history: list[Content], +) -> list[Content]: + """Extracts the curated (valid) history from a comprehensive history. + + The comprehensive history contains all turns (user input and model responses), + including any invalid or rejected model outputs. This function filters that + history to return only the valid turns. + + Args: + comprehensive_history: A list representing the complete chat history. + Including invalid turns. + + Returns: + curated history, which is a list of valid turns. + """ + if not comprehensive_history: + return [] + curated_history = [] + length = len(comprehensive_history) + i = 0 + current_input = comprehensive_history[i] + while i < length: + if comprehensive_history[i].role not in ["user", "model"]: + raise ValueError( + f"Role must be user or model, but got {comprehensive_history[i].role}" + ) + + if comprehensive_history[i].role == "user": + current_input = comprehensive_history[i] + curated_history.append(current_input) + i += 1 + else: + current_output = [] + is_valid = True + while i < length and comprehensive_history[i].role == "model": + current_output.append(comprehensive_history[i]) + if is_valid and not _validate_content(comprehensive_history[i]): + is_valid = False + i += 1 + if is_valid: + curated_history.extend(current_output) + elif curated_history: + curated_history.pop() + return curated_history + + +class _BaseChat: + """Base chat session.""" + + def __init__( + self, + *, + model: str, + config: Optional[GenerateContentConfigOrDict] = None, + history: list[ContentOrDict], + ): + self._model = model + self._config = config + content_models = [] + for content in history: + if not isinstance(content, Content): + content_model = Content.model_validate(content) + else: + content_model = content + content_models.append(content_model) + self._comprehensive_history = content_models + """Comprehensive history is the full history of the chat, including turns of the invalid contents from the model and their associated inputs. + """ + self._curated_history = _extract_curated_history(content_models) + """Curated history is the set of valid turns that will be used in the subsequent send requests. + """ + + def record_history( + self, + user_input: Content, + model_output: list[Content], + automatic_function_calling_history: list[Content], + is_valid: bool, + ) -> None: + """Records the chat history. + + Maintaining both comprehensive and curated histories. + + Args: + user_input: The user's input content. + model_output: A list of `Content` from the model's response. This can be + an empty list if the model produced no output. + automatic_function_calling_history: A list of `Content` representing the + history of automatic function calls, including the user input as the + first entry. + is_valid: A boolean flag indicating whether the current model output is + considered valid. + """ + input_contents = ( + # Because the AFC input contains the entire curated chat history in + # addition to the new user input, we need to truncate the AFC history + # to deduplicate the existing chat history. + automatic_function_calling_history[len(self._curated_history) :] + if automatic_function_calling_history + else [user_input] + ) + # Appends an empty content when model returns empty response, so that the + # history is always alternating between user and model. + output_contents = ( + model_output if model_output else [Content(role="model", parts=[])] + ) + self._comprehensive_history.extend(input_contents) + self._comprehensive_history.extend(output_contents) + if is_valid: + self._curated_history.extend(input_contents) + self._curated_history.extend(output_contents) + + def get_history(self, curated: bool = False) -> list[Content]: + """Returns the chat history. + + Args: + curated: A boolean flag indicating whether to return the curated (valid) + history or the comprehensive (all turns) history. Defaults to False + (returns the comprehensive history). + + Returns: + A list of `Content` objects representing the chat history. + """ + if curated: + return self._curated_history + else: + return self._comprehensive_history + + +def _is_part_type( + contents: Union[list[PartUnionDict], PartUnionDict], +) -> TypeGuard[t.ContentType]: + if isinstance(contents, list): + return all(_is_part_type(part) for part in contents) + else: + allowed_part_types = get_args(types.PartUnion) + if type(contents) in allowed_part_types: + return True + else: + # Some images don't pass isinstance(item, PIL.Image.Image) + # For example + if types.PIL_Image is not None and isinstance(contents, types.PIL_Image): + return True + return False + + +class Chat(_BaseChat): + """Chat session.""" + + def __init__( + self, + *, + modules: Models, + model: str, + config: Optional[GenerateContentConfigOrDict] = None, + history: list[ContentOrDict], + ): + self._modules = modules + super().__init__( + model=model, + config=config, + history=history, + ) + + def send_message( + self, + message: Union[list[PartUnionDict], PartUnionDict], + config: Optional[GenerateContentConfigOrDict] = None, + ) -> GenerateContentResponse: + """Sends the conversation history with the additional message and returns the model's response. + + Args: + message: The message to send to the model. + config: Optional config to override the default Chat config for this + request. + + Returns: + The model's response. + + Usage: + + .. code-block:: python + + chat = client.chats.create(model='gemini-2.0-flash') + response = chat.send_message('tell me a story') + """ + + if not _is_part_type(message): + raise ValueError( + f"Message must be a valid part type: {types.PartUnion} or" + f" {types.PartUnionDict}, got {type(message)}" + ) + input_content = t.t_content(message) + response = self._modules.generate_content( + model=self._model, + contents=self._curated_history + [input_content], # type: ignore[arg-type] + config=config if config else self._config, + ) + model_output = ( + [response.candidates[0].content] + if response.candidates and response.candidates[0].content + else [] + ) + automatic_function_calling_history = ( + response.automatic_function_calling_history + if response.automatic_function_calling_history + else [] + ) + self.record_history( + user_input=input_content, + model_output=model_output, + automatic_function_calling_history=automatic_function_calling_history, + is_valid=_validate_response(response), + ) + return response + + def send_message_stream( + self, + message: Union[list[PartUnionDict], PartUnionDict], + config: Optional[GenerateContentConfigOrDict] = None, + ) -> Iterator[GenerateContentResponse]: + """Sends the conversation history with the additional message and yields the model's response in chunks. + + Args: + message: The message to send to the model. + config: Optional config to override the default Chat config for this + request. + + Yields: + The model's response in chunks. + + Usage: + + .. code-block:: python + + chat = client.chats.create(model='gemini-2.0-flash') + for chunk in chat.send_message_stream('tell me a story'): + print(chunk.text) + """ + + if not _is_part_type(message): + raise ValueError( + f"Message must be a valid part type: {types.PartUnion} or" + f" {types.PartUnionDict}, got {type(message)}" + ) + input_content = t.t_content(message) + output_contents = [] + finish_reason = None + is_valid = True + chunk = None + if isinstance(self._modules, Models): + for chunk in self._modules.generate_content_stream( + model=self._model, + contents=self._curated_history + [input_content], # type: ignore[arg-type] + config=config if config else self._config, + ): + if not _validate_response(chunk): + is_valid = False + if chunk.candidates and chunk.candidates[0].content: + output_contents.append(chunk.candidates[0].content) + if chunk.candidates and chunk.candidates[0].finish_reason: + finish_reason = chunk.candidates[0].finish_reason + yield chunk + automatic_function_calling_history = ( + chunk.automatic_function_calling_history + if chunk is not None and chunk.automatic_function_calling_history + else [] + ) + self.record_history( + user_input=input_content, + model_output=output_contents, + automatic_function_calling_history=automatic_function_calling_history, + is_valid=is_valid + and output_contents is not None + and finish_reason is not None, + ) + + +class Chats: + """A util class to create chat sessions.""" + + def __init__(self, modules: Models): + self._modules = modules + + def create( + self, + *, + model: str, + config: Optional[GenerateContentConfigOrDict] = None, + history: Optional[list[ContentOrDict]] = None, + ) -> Chat: + """Creates a new chat session. + + Args: + model: The model to use for the chat. + config: The configuration to use for the generate content request. + history: The history to use for the chat. + + Returns: + A new chat session. + """ + return Chat( + modules=self._modules, + model=model, + config=config, + history=history if history else [], + ) + + +class AsyncChat(_BaseChat): + """Async chat session.""" + + def __init__( + self, + *, + modules: AsyncModels, + model: str, + config: Optional[GenerateContentConfigOrDict] = None, + history: list[ContentOrDict], + ): + self._modules = modules + super().__init__( + model=model, + config=config, + history=history, + ) + + async def send_message( + self, + message: Union[list[PartUnionDict], PartUnionDict], + config: Optional[GenerateContentConfigOrDict] = None, + ) -> GenerateContentResponse: + """Sends the conversation history with the additional message and returns model's response. + + Args: + message: The message to send to the model. + config: Optional config to override the default Chat config for this + request. + + Returns: + The model's response. + + Usage: + + .. code-block:: python + + chat = client.aio.chats.create(model='gemini-2.0-flash') + response = await chat.send_message('tell me a story') + """ + if not _is_part_type(message): + raise ValueError( + f"Message must be a valid part type: {types.PartUnion} or" + f" {types.PartUnionDict}, got {type(message)}" + ) + input_content = t.t_content(message) + response = await self._modules.generate_content( + model=self._model, + contents=self._curated_history + [input_content], # type: ignore[arg-type] + config=config if config else self._config, + ) + model_output = ( + [response.candidates[0].content] + if response.candidates and response.candidates[0].content + else [] + ) + automatic_function_calling_history = ( + response.automatic_function_calling_history + if response.automatic_function_calling_history + else [] + ) + self.record_history( + user_input=input_content, + model_output=model_output, + automatic_function_calling_history=automatic_function_calling_history, + is_valid=_validate_response(response), + ) + return response + + async def send_message_stream( + self, + message: Union[list[PartUnionDict], PartUnionDict], + config: Optional[GenerateContentConfigOrDict] = None, + ) -> AsyncIterator[GenerateContentResponse]: + """Sends the conversation history with the additional message and yields the model's response in chunks. + + Args: + message: The message to send to the model. + config: Optional config to override the default Chat config for this + request. + + Yields: + The model's response in chunks. + + Usage: + + .. code-block:: python + + chat = client.aio.chats.create(model='gemini-2.0-flash') + async for chunk in await chat.send_message_stream('tell me a story'): + print(chunk.text) + """ + + if not _is_part_type(message): + raise ValueError( + f"Message must be a valid part type: {types.PartUnion} or" + f" {types.PartUnionDict}, got {type(message)}" + ) + input_content = t.t_content(message) + + async def async_generator(): # type: ignore[no-untyped-def] + output_contents = [] + finish_reason = None + is_valid = True + chunk = None + async for chunk in await self._modules.generate_content_stream( # type: ignore[attr-defined] + model=self._model, + contents=self._curated_history + [input_content], # type: ignore[arg-type] + config=config if config else self._config, + ): + if not _validate_response(chunk): + is_valid = False + if chunk.candidates and chunk.candidates[0].content: + output_contents.append(chunk.candidates[0].content) + if chunk.candidates and chunk.candidates[0].finish_reason: + finish_reason = chunk.candidates[0].finish_reason + yield chunk + + if not output_contents or finish_reason is None: + is_valid = False + + self.record_history( + user_input=input_content, + model_output=output_contents, + automatic_function_calling_history=chunk.automatic_function_calling_history + if chunk is not None and chunk.automatic_function_calling_history + else [], + is_valid=is_valid, + ) + + return async_generator() # type: ignore[no-untyped-call, no-any-return] + + +class AsyncChats: + """A util class to create async chat sessions.""" + + def __init__(self, modules: AsyncModels): + self._modules = modules + + def create( + self, + *, + model: str, + config: Optional[GenerateContentConfigOrDict] = None, + history: Optional[list[ContentOrDict]] = None, + ) -> AsyncChat: + """Creates a new chat session. + + Args: + model: The model to use for the chat. + config: The configuration to use for the generate content request. + history: The history to use for the chat. + + Returns: + A new chat session. + """ + return AsyncChat( + modules=self._modules, + model=model, + config=config, + history=history if history else [], + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/client.py new file mode 100644 index 0000000000000000000000000000000000000000..8680a2b74af8878671cd39cdae1331ab476272ea --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/client.py @@ -0,0 +1,655 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +import asyncio +import os +from types import TracebackType +from typing import Optional, Union + +import google.auth +import pydantic + +from ._api_client import BaseApiClient +from ._base_url import get_base_url +from ._replay_api_client import ReplayApiClient +from .batches import AsyncBatches, Batches +from .caches import AsyncCaches, Caches +from .chats import AsyncChats, Chats +from .file_search_stores import AsyncFileSearchStores, FileSearchStores +from .files import AsyncFiles, Files +from .live import AsyncLive +from .models import AsyncModels, Models +from .operations import AsyncOperations, Operations +from .tokens import AsyncTokens, Tokens +from .tunings import AsyncTunings, Tunings +from .types import HttpOptions, HttpOptionsDict, HttpRetryOptions + +import warnings +import httpx + +from ._api_client import has_aiohttp + +from . import _common + +from ._interactions import AsyncGeminiNextGenAPIClient, DEFAULT_MAX_RETRIES, GeminiNextGenAPIClient +from . import _interactions + +from ._interactions.resources import AsyncInteractionsResource as AsyncNextGenInteractionsResource, InteractionsResource as NextGenInteractionsResource +from ._interactions.resources import WebhooksResource, AsyncWebhooksResource +_interactions_experimental_warned = False + +class AsyncGeminiNextGenAPIClientAdapter(_interactions.AsyncGeminiNextGenAPIClientAdapter): + """Adapter for the Gemini NextGen API Client.""" + def __init__(self, api_client: BaseApiClient): + self._api_client = api_client + + def is_vertex_ai(self) -> bool: + return self._api_client.vertexai or False + + def get_project(self) -> str | None: + return self._api_client.project + + def get_location(self) -> str | None: + return self._api_client.location + + async def async_get_auth_headers(self) -> dict[str, str]: + if self._api_client.api_key: + return {"x-goog-api-key": self._api_client.api_key} + access_token = await self._api_client._async_access_token() + headers = { + "Authorization": f"Bearer {access_token}", + } + if creds := self._api_client._credentials: + if creds.quota_project_id: + headers["x-goog-user-project"] = creds.quota_project_id + return headers + + +class GeminiNextGenAPIClientAdapter(_interactions.GeminiNextGenAPIClientAdapter): + """Adapter for the Gemini NextGen API Client.""" + def __init__(self, api_client: BaseApiClient): + self._api_client = api_client + + def is_vertex_ai(self) -> bool: + return self._api_client.vertexai or False + + def get_project(self) -> str | None: + return self._api_client.project + + def get_location(self) -> str | None: + return self._api_client.location + + def get_auth_headers(self) -> dict[str, str]: + if self._api_client.api_key: + return {"x-goog-api-key": self._api_client.api_key} + access_token = self._api_client._access_token() + headers = { + "Authorization": f"Bearer {access_token}", + } + if creds := self._api_client._credentials: + if creds.quota_project_id: + headers["x-goog-user-project"] = creds.quota_project_id + return headers + + +class AsyncClient: + """Client for making asynchronous (non-blocking) requests.""" + + def __init__(self, api_client: BaseApiClient): + + self._api_client = api_client + self._models = AsyncModels(self._api_client) + self._tunings = AsyncTunings(self._api_client) + self._caches = AsyncCaches(self._api_client) + self._batches = AsyncBatches(self._api_client) + self._files = AsyncFiles(self._api_client) + self._file_search_stores = AsyncFileSearchStores(self._api_client) + self._live = AsyncLive(self._api_client) + self._tokens = AsyncTokens(self._api_client) + self._operations = AsyncOperations(self._api_client) + self._nextgen_client_instance: Optional[AsyncGeminiNextGenAPIClient] = None + + @property + def _nextgen_client(self) -> AsyncGeminiNextGenAPIClient: + if self._nextgen_client_instance is not None: + return self._nextgen_client_instance + + http_opts = self._api_client._http_options + + if http_opts.extra_body: + warnings.warn( + 'extra_body properties are not supported in `.interactions` yet', + category=UserWarning, + stacklevel=5, + ) + + retry_opts = http_opts.retry_options + if retry_opts is not None and ( + retry_opts.initial_delay is not None + or retry_opts.max_delay is not None + or retry_opts.exp_base is not None + or retry_opts.jitter is not None + or retry_opts.http_status_codes is not None + ): + warnings.warn( + 'Granular retry options are not supported in `.interactions` yet', + category=UserWarning, + stacklevel=5, + ) + + http_client: Optional[httpx.AsyncClient] = ( + self._api_client._async_httpx_client + ) + + async_client_args = self._api_client._http_options.async_client_args or {} + has_custom_transport = 'transport' in async_client_args + + if has_aiohttp and not has_custom_transport: + warnings.warn( + 'Async interactions client cannot use aiohttp, fallingback to httpx.', + category=UserWarning, + stacklevel=5, + ) + + if retry_opts is not None and retry_opts.attempts is not None: + max_retries = retry_opts.attempts + else: + max_retries = DEFAULT_MAX_RETRIES + 1 + + self._nextgen_client_instance = AsyncGeminiNextGenAPIClient( + base_url=http_opts.base_url, + api_key=self._api_client.api_key, + api_version=http_opts.api_version, + default_headers=http_opts.headers, + http_client=http_client, + # uSDk expects ms, nextgen uses a httpx Timeout -> expects seconds. + timeout=http_opts.timeout / 1000 if http_opts.timeout else None, + max_retries=max_retries, + client_adapter=AsyncGeminiNextGenAPIClientAdapter(self._api_client) + ) + + client = self._nextgen_client_instance + if self._api_client.vertexai: + client._is_vertex = True + client._vertex_project = self._api_client.project + client._vertex_location = self._api_client.location + + return self._nextgen_client_instance + + @property + def interactions(self) -> AsyncNextGenInteractionsResource: + global _interactions_experimental_warned + if not _interactions_experimental_warned: + _interactions_experimental_warned = True + warnings.warn( + 'Interactions usage is experimental and may change in future versions.', + category=UserWarning, + stacklevel=1, + ) + return self._nextgen_client.interactions + + @property + def webhooks(self) -> AsyncWebhooksResource: + return self._nextgen_client.webhooks + + @property + def _has_nextgen_client(self) -> bool: + return ( + hasattr(self, '_nextgen_client_instance') and + self._nextgen_client_instance is not None + ) + + @property + def models(self) -> AsyncModels: + return self._models + + @property + def tunings(self) -> AsyncTunings: + return self._tunings + + @property + def caches(self) -> AsyncCaches: + return self._caches + + @property + def file_search_stores(self) -> AsyncFileSearchStores: + return self._file_search_stores + + @property + def batches(self) -> AsyncBatches: + return self._batches + + @property + def chats(self) -> AsyncChats: + return AsyncChats(modules=self.models) + + @property + def files(self) -> AsyncFiles: + return self._files + + @property + def live(self) -> AsyncLive: + return self._live + + @property + def auth_tokens(self) -> AsyncTokens: + return self._tokens + + @property + def operations(self) -> AsyncOperations: + return self._operations + + async def aclose(self) -> None: + """Closes the async client explicitly. + + However, it doesn't close the sync client, which can be closed using the + Client.close() method or using the context manager. + + Usage: + .. code-block:: python + + from google.genai import Client + + async_client = Client( + vertexai=True, project='my-project-id', location='us-central1' + ).aio + response_1 = await async_client.models.generate_content( + model='gemini-2.0-flash', + contents='Hello World', + ) + response_2 = await async_client.models.generate_content( + model='gemini-2.0-flash', + contents='Hello World', + ) + # Close the client to release resources. + await async_client.aclose() + """ + await self._api_client.aclose() + + if self._has_nextgen_client: + await self._nextgen_client.close() + + async def __aenter__(self) -> 'AsyncClient': + return self + + async def __aexit__( + self, + exc_type: Optional[Exception], + exc_value: Optional[Exception], + traceback: Optional[TracebackType], + ) -> None: + await self.aclose() + + def __del__(self) -> None: + try: + asyncio.get_running_loop().create_task(self.aclose()) + except Exception: + pass + + +class DebugConfig(pydantic.BaseModel): + """Configuration options that change client network behavior when testing.""" + + client_mode: Optional[str] = pydantic.Field( + default_factory=lambda: os.getenv('GOOGLE_GENAI_CLIENT_MODE', None) + ) + + replays_directory: Optional[str] = pydantic.Field( + default_factory=lambda: os.getenv('GOOGLE_GENAI_REPLAYS_DIRECTORY', None) + ) + + replay_id: Optional[str] = pydantic.Field( + default_factory=lambda: os.getenv('GOOGLE_GENAI_REPLAY_ID', None) + ) + + +class Client: + """Client for making synchronous requests. + + Use this client to make a request to the Gemini Developer API or Vertex AI + API and then wait for the response. + + To initialize the client, provide the required arguments either directly + or by using environment variables. Gemini API users and Vertex AI users in + express mode can provide API key by providing input argument + `api_key="your-api-key"` or by defining `GOOGLE_API_KEY="your-api-key"` as an + environment variable + + Vertex AI API users can provide inputs argument as `vertexai=True, + project="your-project-id", location="us-central1"` or by defining + `GOOGLE_GENAI_USE_VERTEXAI=true`, `GOOGLE_CLOUD_PROJECT` and + `GOOGLE_CLOUD_LOCATION` environment variables. + + Attributes: + api_key: The `API key `_ to + use for authentication. Applies to the Gemini Developer API only. + vertexai: Indicates whether the client should use the Vertex AI API + endpoints. Defaults to False (uses Gemini Developer API endpoints). + Applies to the Vertex AI API only. + credentials: The credentials to use for authentication when calling the + Vertex AI APIs. Credentials can be obtained from environment variables and + default credentials. For more information, see `Set up Application Default + Credentials + `_. + Applies to the Vertex AI API only. + project: The `Google Cloud project ID + `_ to use + for quota. Can be obtained from environment variables (for example, + ``GOOGLE_CLOUD_PROJECT``). Applies to the Vertex AI API only. + Find your `Google Cloud project ID `_. + location: The `location + `_ + to send API requests to (for example, ``us-central1``). Can be obtained + from environment variables. Applies to the Vertex AI API only. + debug_config: Config settings that control network behavior of the client. + This is typically used when running test code. + http_options: Http options to use for the client. These options will be + applied to all requests made by the client. Example usage: `client = + genai.Client(http_options=types.HttpOptions(api_version='v1'))`. + + Usage for the Gemini Developer API: + + .. code-block:: python + + from google import genai + + client = genai.Client(api_key='my-api-key') + + Usage for the Vertex AI API: + + .. code-block:: python + + from google import genai + + client = genai.Client( + vertexai=True, project='my-project-id', location='us-central1' + ) + """ + + def __init__( + self, + *, + vertexai: Optional[bool] = None, + api_key: Optional[str] = None, + credentials: Optional[google.auth.credentials.Credentials] = None, + project: Optional[str] = None, + location: Optional[str] = None, + debug_config: Optional[DebugConfig] = None, + http_options: Optional[Union[HttpOptions, HttpOptionsDict]] = None, + ): + """Initializes the client. + + Args: + vertexai (bool): Indicates whether the client should use the Vertex AI + API endpoints. Defaults to False (uses Gemini Developer API endpoints). + Applies to the Vertex AI API only. + api_key (str): The `API key + `_ to use for + authentication. Applies to the Gemini Developer API only. + credentials (google.auth.credentials.Credentials): The credentials to use + for authentication when calling the Vertex AI APIs. Credentials can be + obtained from environment variables and default credentials. For more + information, see `Set up Application Default Credentials + `_. + Applies to the Vertex AI API only. + project (str): The `Google Cloud project ID + `_ to + use for quota. Can be obtained from environment variables (for example, + ``GOOGLE_CLOUD_PROJECT``). Applies to the Vertex AI API only. + location (str): The `location + `_ + to send API requests to (for example, ``us-central1``). Can be obtained + from environment variables. Applies to the Vertex AI API only. + debug_config (DebugConfig): Config settings that control network behavior + of the client. This is typically used when running test code. + http_options (Union[HttpOptions, HttpOptionsDict]): Http options to use + for the client. + """ + + self._debug_config = debug_config or DebugConfig() + if isinstance(http_options, dict): + http_options = HttpOptions(**http_options) + + base_url = get_base_url(vertexai or False, http_options) + if base_url: + if http_options: + http_options.base_url = base_url + else: + http_options = HttpOptions(base_url=base_url) + + self._api_client = self._get_api_client( + vertexai=vertexai, + api_key=api_key, + credentials=credentials, + project=project, + location=location, + debug_config=self._debug_config, + http_options=http_options, + ) + + self._aio = AsyncClient(self._api_client) + self._models = Models(self._api_client) + self._tunings = Tunings(self._api_client) + self._caches = Caches(self._api_client) + self._file_search_stores = FileSearchStores(self._api_client) + self._batches = Batches(self._api_client) + self._files = Files(self._api_client) + self._tokens = Tokens(self._api_client) + self._operations = Operations(self._api_client) + self._nextgen_client_instance: Optional[GeminiNextGenAPIClient] = None + + @staticmethod + def _get_api_client( + vertexai: Optional[bool] = None, + api_key: Optional[str] = None, + credentials: Optional[google.auth.credentials.Credentials] = None, + project: Optional[str] = None, + location: Optional[str] = None, + debug_config: Optional[DebugConfig] = None, + http_options: Optional[HttpOptions] = None, + ) -> BaseApiClient: + if debug_config and debug_config.client_mode in [ + 'record', + 'replay', + 'auto', + ]: + return ReplayApiClient( + mode=debug_config.client_mode, # type: ignore[arg-type] + replay_id=debug_config.replay_id, # type: ignore[arg-type] + replays_directory=debug_config.replays_directory, + vertexai=vertexai, # type: ignore[arg-type] + api_key=api_key, + credentials=credentials, + project=project, + location=location, + http_options=http_options, + ) + + return BaseApiClient( + vertexai=vertexai, + api_key=api_key, + credentials=credentials, + project=project, + location=location, + http_options=http_options, + ) + + @property + def _nextgen_client(self) -> GeminiNextGenAPIClient: + if self._nextgen_client_instance is not None: + return self._nextgen_client_instance + + http_opts = self._api_client._http_options + + if http_opts.extra_body: + warnings.warn( + 'extra_body properties are not supported in `.interactions` yet', + category=UserWarning, + stacklevel=5, + ) + + retry_opts = http_opts.retry_options + if retry_opts is not None and ( + retry_opts.initial_delay is not None + or retry_opts.max_delay is not None + or retry_opts.exp_base is not None + or retry_opts.jitter is not None + or retry_opts.http_status_codes is not None + ): + warnings.warn( + 'Granular retry options are not supported in `.interactions` yet', + category=UserWarning, + stacklevel=5, + ) + + if retry_opts is not None and retry_opts.attempts is not None: + max_retries = retry_opts.attempts + else: + max_retries = DEFAULT_MAX_RETRIES + 1 + + self._nextgen_client_instance = GeminiNextGenAPIClient( + base_url=http_opts.base_url, + api_key=self._api_client.api_key, + api_version=http_opts.api_version, + default_headers=http_opts.headers, + http_client=self._api_client._httpx_client, + # uSDk expects ms, nextgen uses a httpx Timeout -> expects seconds. + timeout=http_opts.timeout / 1000 if http_opts.timeout else None, + max_retries=max_retries, + client_adapter=GeminiNextGenAPIClientAdapter(self._api_client), + ) + + client = self._nextgen_client_instance + if self._api_client.vertexai: + client._is_vertex = True + client._vertex_project = self._api_client.project + client._vertex_location = self._api_client.location + + return self._nextgen_client_instance + + @property + def interactions(self) -> NextGenInteractionsResource: + global _interactions_experimental_warned + if not _interactions_experimental_warned: + _interactions_experimental_warned = True + warnings.warn( + 'Interactions usage is experimental and may change in future versions.', + category=UserWarning, + stacklevel=2, + ) + return self._nextgen_client.interactions + + @property + def webhooks(self) -> WebhooksResource: + return self._nextgen_client.webhooks + + @property + def _has_nextgen_client(self) -> bool: + return ( + hasattr(self, '_nextgen_client_instance') and + self._nextgen_client_instance is not None + ) + + @property + def chats(self) -> Chats: + return Chats(modules=self.models) + + @property + def aio(self) -> AsyncClient: + return self._aio + + @property + def models(self) -> Models: + return self._models + + @property + def tunings(self) -> Tunings: + return self._tunings + + @property + def caches(self) -> Caches: + return self._caches + + @property + def file_search_stores(self) -> FileSearchStores: + return self._file_search_stores + + @property + def batches(self) -> Batches: + return self._batches + + @property + def files(self) -> Files: + return self._files + + @property + def auth_tokens(self) -> Tokens: + return self._tokens + + @property + def operations(self) -> Operations: + return self._operations + + @property + def vertexai(self) -> bool: + """Returns whether the client is using the Vertex AI API.""" + return self._api_client.vertexai or False + + def close(self) -> None: + """Closes the synchronous client explicitly. + + However, it doesn't close the async client, which can be closed using the + Client.aio.aclose() method or using the async context manager. + + Usage: + .. code-block:: python + + from google.genai import Client + + client = Client( + vertexai=True, project='my-project-id', location='us-central1' + ) + response_1 = client.models.generate_content( + model='gemini-2.0-flash', + contents='Hello World', + ) + response_2 = client.models.generate_content( + model='gemini-2.0-flash', + contents='Hello World', + ) + # Close the client to release resources. + client.close() + """ + self._api_client.close() + + if self._has_nextgen_client: + self._nextgen_client.close() + + def __enter__(self) -> 'Client': + return self + + def __exit__( + self, + exc_type: Optional[Exception], + exc_value: Optional[Exception], + traceback: Optional[TracebackType], + ) -> None: + self.close() + + def __del__(self) -> None: + try: + self.close() + except Exception: + pass diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/documents.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/documents.py new file mode 100644 index 0000000000000000000000000000000000000000..d542fea520941aab3a7afa8548fd1103e93a40f5 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/documents.py @@ -0,0 +1,589 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# Code generated by the Google Gen AI SDK generator DO NOT EDIT. + +from functools import partial +import json +import logging +from typing import Any, Optional, Union +from urllib.parse import urlencode + +from . import _api_module +from . import _common +from . import types +from ._common import get_value_by_path as getv +from ._common import set_value_by_path as setv +from .pagers import AsyncPager, Pager + +logger = logging.getLogger('google_genai.documents') + + +def _DeleteDocumentConfig_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['force']) is not None: + setv(parent_object, ['_query', 'force'], getv(from_object, ['force'])) + + return to_object + + +def _DeleteDocumentParameters_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['name']) is not None: + setv(to_object, ['_url', 'name'], getv(from_object, ['name'])) + + if getv(from_object, ['config']) is not None: + _DeleteDocumentConfig_to_mldev(getv(from_object, ['config']), to_object) + + return to_object + + +def _GetDocumentParameters_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['name']) is not None: + setv(to_object, ['_url', 'name'], getv(from_object, ['name'])) + + return to_object + + +def _ListDocumentsConfig_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['page_size']) is not None: + setv( + parent_object, ['_query', 'pageSize'], getv(from_object, ['page_size']) + ) + + if getv(from_object, ['page_token']) is not None: + setv( + parent_object, + ['_query', 'pageToken'], + getv(from_object, ['page_token']), + ) + + return to_object + + +def _ListDocumentsParameters_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['parent']) is not None: + setv(to_object, ['_url', 'parent'], getv(from_object, ['parent'])) + + if getv(from_object, ['config']) is not None: + _ListDocumentsConfig_to_mldev(getv(from_object, ['config']), to_object) + + return to_object + + +def _ListDocumentsResponse_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['sdkHttpResponse']) is not None: + setv( + to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse']) + ) + + if getv(from_object, ['nextPageToken']) is not None: + setv(to_object, ['next_page_token'], getv(from_object, ['nextPageToken'])) + + if getv(from_object, ['documents']) is not None: + setv( + to_object, + ['documents'], + [item for item in getv(from_object, ['documents'])], + ) + + return to_object + + +class Documents(_api_module.BaseModule): + + def get( + self, *, name: str, config: Optional[types.GetDocumentConfigOrDict] = None + ) -> types.Document: + """Gets metadata about a Document. + + Args: + name (str): The resource name of the Document. + Example: ragStores/rag-store-foo/documents/documents-bar + config (GetDocumentConfig | None): Optional parameters for the request. + + Returns: + The Document. + """ + + parameter_model = types._GetDocumentParameters( + name=name, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if self._api_client.vertexai: + raise ValueError( + 'This method is only supported in the Gemini Developer client.' + ) + else: + request_dict = _GetDocumentParameters_to_mldev(parameter_model) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{name}'.format_map(request_url_dict) + else: + path = '{name}' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request('get', path, request_dict, http_options) + + response_dict = {} if not response.body else json.loads(response.body) + + return_value = types.Document._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + + self._api_client._verify_response(return_value) + return return_value + + def delete( + self, + *, + name: str, + config: Optional[types.DeleteDocumentConfigOrDict] = None, + ) -> None: + """Deletes a Document. + + Args: + name (str): The resource name of the Document. + Example: ragStores/rag-store-foo/documents/documents-bar + config (DeleteDocumentConfig | None): Optional parameters for the request. + + Returns: + None + """ + + parameter_model = types._DeleteDocumentParameters( + name=name, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if self._api_client.vertexai: + raise ValueError( + 'This method is only supported in the Gemini Developer client.' + ) + else: + request_dict = _DeleteDocumentParameters_to_mldev(parameter_model) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{name}'.format_map(request_url_dict) + else: + path = '{name}' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + self._api_client.request('delete', path, request_dict, http_options) + + def _list( + self, + *, + parent: str, + config: Optional[types.ListDocumentsConfigOrDict] = None, + ) -> types.ListDocumentsResponse: + parameter_model = types._ListDocumentsParameters( + parent=parent, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if self._api_client.vertexai: + raise ValueError( + 'This method is only supported in the Gemini Developer client.' + ) + else: + request_dict = _ListDocumentsParameters_to_mldev(parameter_model) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{parent}/documents'.format_map(request_url_dict) + else: + path = '{parent}/documents' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request('get', path, request_dict, http_options) + + response_dict = {} if not response.body else json.loads(response.body) + + if not self._api_client.vertexai: + response_dict = _ListDocumentsResponse_from_mldev(response_dict) + + return_value = types.ListDocumentsResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + + self._api_client._verify_response(return_value) + return return_value + + def list( + self, + *, + parent: str, + config: Optional[types.ListDocumentsConfigOrDict] = None, + ) -> Pager[types.Document]: + """Lists documents. + + Args: + parent (str): The name of the RagStore containing the Documents. + config (ListDocumentsConfig): Optional configuration for the list request. + + Returns: + A Pager object that contains one page of documents. When iterating over + the pager, it automatically fetches the next page if there are more. + Usage: + .. code-block:: python + for document in client.documents.list(parent='rag_store_name'): + print(f"document: {document.name} - {document.display_name}") + """ + + list_request = partial(self._list, parent=parent) + return Pager( + 'documents', + list_request, + self._list(parent=parent, config=config), + config, + ) + + +class AsyncDocuments(_api_module.BaseModule): + + async def get( + self, *, name: str, config: Optional[types.GetDocumentConfigOrDict] = None + ) -> types.Document: + """Gets metadata about a Document. + + Args: + name (str): The resource name of the Document. + Example: ragStores/rag-store-foo/documents/documents-bar + config (GetDocumentConfig | None): Optional parameters for the request. + + Returns: + The Document. + """ + + parameter_model = types._GetDocumentParameters( + name=name, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if self._api_client.vertexai: + raise ValueError( + 'This method is only supported in the Gemini Developer client.' + ) + else: + request_dict = _GetDocumentParameters_to_mldev(parameter_model) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{name}'.format_map(request_url_dict) + else: + path = '{name}' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'get', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + return_value = types.Document._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + + self._api_client._verify_response(return_value) + return return_value + + async def delete( + self, + *, + name: str, + config: Optional[types.DeleteDocumentConfigOrDict] = None, + ) -> None: + """Deletes a Document. + + Args: + name (str): The resource name of the Document. + Example: ragStores/rag-store-foo/documents/documents-bar + config (DeleteDocumentConfig | None): Optional parameters for the request. + + Returns: + None + """ + + parameter_model = types._DeleteDocumentParameters( + name=name, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if self._api_client.vertexai: + raise ValueError( + 'This method is only supported in the Gemini Developer client.' + ) + else: + request_dict = _DeleteDocumentParameters_to_mldev(parameter_model) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{name}'.format_map(request_url_dict) + else: + path = '{name}' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + await self._api_client.async_request( + 'delete', path, request_dict, http_options + ) + + async def _list( + self, + *, + parent: str, + config: Optional[types.ListDocumentsConfigOrDict] = None, + ) -> types.ListDocumentsResponse: + parameter_model = types._ListDocumentsParameters( + parent=parent, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if self._api_client.vertexai: + raise ValueError( + 'This method is only supported in the Gemini Developer client.' + ) + else: + request_dict = _ListDocumentsParameters_to_mldev(parameter_model) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{parent}/documents'.format_map(request_url_dict) + else: + path = '{parent}/documents' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'get', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if not self._api_client.vertexai: + response_dict = _ListDocumentsResponse_from_mldev(response_dict) + + return_value = types.ListDocumentsResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + + self._api_client._verify_response(return_value) + return return_value + + async def list( + self, + *, + parent: str, + config: Optional[types.ListDocumentsConfigOrDict] = None, + ) -> AsyncPager[types.Document]: + """Lists documents asynchronously. + + Args: + parent (str): The name of the RagStore containing the Documents. + config (ListDocumentsConfig): Optional configuration for the list request. + + Returns: + A Pager object that contains one page of documents. When iterating over + the pager, it automatically fetches the next page if there are more. + Usage: + .. code-block:: python + async for document in await + client.aio.documents.list(parent='rag_store_name'): + print(f"document: {document.name} - {document.display_name}") + """ + + list_request = partial(self._list, parent=parent) + return AsyncPager( + 'documents', + list_request, + await self._list(parent=parent, config=config), + config, + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/errors.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..48bf1b131040b8304781f56f6c0ce34a6c986c52 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/errors.py @@ -0,0 +1,305 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +"""Error classes for the GenAI SDK.""" + +from typing import Any, Callable, Optional, TYPE_CHECKING, Union +import httpx +import json +import requests +from . import _common + + +if TYPE_CHECKING: + from .replay_api_client import ReplayResponse + import aiohttp + from google.auth.aio.transport.aiohttp import Response as AsyncAuthorizedSessionResponse + + +class APIError(Exception): + """General errors raised by the GenAI API.""" + code: int + response: Union[ + requests.Response, + 'ReplayResponse', + httpx.Response, + 'AsyncAuthorizedSessionResponse', + ] + + status: Optional[str] = None + message: Optional[str] = None + + def __init__( + self, + code: int, + response_json: Any, + response: Optional[ + Union[ + requests.Response, + 'ReplayResponse', + httpx.Response, + 'AsyncAuthorizedSessionResponse', + ] + ] = None, + ): + if isinstance(response_json, list) and len(response_json) == 1: + response_json = response_json[0] + + self.response = response + self.details = response_json + self.message = self._get_message(response_json) + self.status = self._get_status(response_json) + self.code = code if code else self._get_code(response_json) + + super().__init__(f'{self.code} {self.status}. {self.details}') + + def __reduce__( + self, + ) -> tuple[Callable[..., 'APIError'], tuple[dict[str, Any]]]: + """Returns a tuple that can be used to reconstruct the error for pickling.""" + state = self.__dict__.copy() + return (self.__class__._rebuild, (state,)) + + @staticmethod + def _rebuild(state: dict[str, Any]) -> 'APIError': + """Rebuilds the error from the state.""" + obj = APIError.__new__(APIError) + obj.__dict__.update(state) + Exception.__init__(obj, f'{obj.code} {obj.status}. {obj.details}') + return obj + + def _get_status(self, response_json: Any) -> Any: + try: + status = response_json.get( + 'status', response_json.get('error', {}).get('status', None) + ) + return status + except AttributeError: + # If response_json is not a dict, return close code to handle the case + # when encountering a websocket error. + return None + + def _get_message(self, response_json: Any) -> Any: + try: + message = response_json.get( + 'message', response_json.get('error', {}).get('message', None) + ) + return message + except AttributeError: + # If response_json is not a dict, return it as None. + # This is to handle the case when encountering a websocket error. + return None + + def _get_code(self, response_json: Any) -> Any: + return response_json.get( + 'code', response_json.get('error', {}).get('code', None) + ) + + def _to_replay_record(self) -> _common.StringDict: + """Returns a dictionary representation of the error for replay recording. + + details is not included since it may expose internal information in the + replay file. + """ + return { + 'error': { + 'code': self.code, + 'message': self.message, + 'status': self.status, + } + } + + @classmethod + def raise_for_response( + cls, response: Union['ReplayResponse', httpx.Response, requests.Response] + ) -> None: + """Raises an error with detailed error message if the response has an error status.""" + if response.status_code == 200: + return + + if isinstance(response, httpx.Response): + try: + response.read() + response_json = response.json() + except json.decoder.JSONDecodeError: + message = response.text + response_json = { + 'message': message, + 'status': response.reason_phrase, + } + elif isinstance(response, requests.Response): + try: + # do not do any extra muanipulation on the response. + # return the raw response json as is. + response_json = response.json() + except requests.exceptions.JSONDecodeError: + response_json = { + 'message': response.text, + 'status': response.reason, + } + else: + response_json = response.body_segments[0].get('error', {}) + + cls.raise_error(response.status_code, response_json, response) + + @classmethod + def raise_error( + cls, + status_code: int, + response_json: Any, + response: Optional[ + Union[ + 'ReplayResponse', + httpx.Response, + requests.Response, + ] + ], + ) -> None: + """Raises an appropriate APIError subclass based on the status code. + + Args: + status_code: The HTTP status code of the response. + response_json: The JSON body of the response, or a dict containing error + details. + response: The original response object. + + Raises: + ClientError: If the status code is in the 4xx range. + ServerError: If the status code is in the 5xx range. + APIError: For other error status codes. + """ + if 400 <= status_code < 500: + raise ClientError(status_code, response_json, response) + elif 500 <= status_code < 600: + raise ServerError(status_code, response_json, response) + else: + raise cls(status_code, response_json, response) + + @classmethod + async def raise_for_async_response( + cls, + response: Union[ + 'ReplayResponse', + httpx.Response, + 'aiohttp.ClientResponse', + 'AsyncAuthorizedSessionResponse', + ], + ) -> None: + """Raises an error with detailed error message if the response has an error status.""" + if isinstance(response, httpx.Response): + if response.status_code == 200: + return + try: + await response.aread() + response_json = response.json() + except json.decoder.JSONDecodeError: + message = response.text + response_json = { + 'message': message, + 'status': response.reason_phrase, + } + status_code = response.status_code + elif hasattr(response, 'body_segments') and hasattr( + response, 'status_code' + ): + if response.status_code == 200: + return + response_json = response.body_segments[0].get('error', {}) + status_code = response.status_code + else: + try: + import aiohttp # pylint: disable=g-import-not-at-top + + # Use a local variable to help Mypy handle the unwrapped response + unwrapped_response: Any = response + if hasattr(unwrapped_response, '_response'): + unwrapped_response = unwrapped_response._response + + if isinstance(unwrapped_response, aiohttp.ClientResponse): + if unwrapped_response.status == 200: + return + try: + response_json = await unwrapped_response.json() + except aiohttp.client_exceptions.ContentTypeError: + message = await unwrapped_response.text() + response_json = { + 'message': message, + 'status': unwrapped_response.reason, + } + status_code = unwrapped_response.status + else: + raise ValueError(f'Unsupported response type: {type(response)}') + except ImportError: + raise ValueError(f'Unsupported response type: {type(response)}') + + await cls.raise_error_async(status_code, response_json, response) + + @classmethod + async def raise_error_async( + cls, status_code: int, response_json: Any, response: Optional[ + Union['ReplayResponse', httpx.Response, 'aiohttp.ClientResponse'] + ] + ) -> None: + """Raises an appropriate APIError subclass based on the status code. + + Args: + status_code: The HTTP status code of the response. + response_json: The JSON body of the response, or a dict containing error + details. + response: The original response object. + + Raises: + ClientError: If the status code is in the 4xx range. + ServerError: If the status code is in the 5xx range. + APIError: For other error status codes. + """ + if 400 <= status_code < 500: + raise ClientError(status_code, response_json, response) + elif 500 <= status_code < 600: + raise ServerError(status_code, response_json, response) + else: + raise cls(status_code, response_json, response) + + +class ClientError(APIError): + """Client error raised by the GenAI API.""" + pass + + +class ServerError(APIError): + """Server error raised by the GenAI API.""" + pass + + +class UnknownFunctionCallArgumentError(ValueError): + """Raised when the function call argument cannot be converted to the parameter annotation.""" + pass + + +class UnsupportedFunctionError(ValueError): + """Raised when the function is not supported.""" + pass + + +class FunctionInvocationError(ValueError): + """Raised when the function cannot be invoked with the given arguments.""" + pass + + +class UnknownApiResponseError(ValueError): + """Raised when the response from the API cannot be parsed as JSON.""" + pass + +ExperimentalWarning = _common.ExperimentalWarning diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/file_search_stores.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/file_search_stores.py new file mode 100644 index 0000000000000000000000000000000000000000..51eb850881ba3bb736ec62714682fc00e62f8662 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/file_search_stores.py @@ -0,0 +1,1443 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# Code generated by the Google Gen AI SDK generator DO NOT EDIT. + +from functools import cached_property +import io +import json +import logging +import os +from typing import Any, Optional, Union +from urllib.parse import urlencode + +from . import _api_module +from . import _common +from . import _extra_utils +from . import types +from ._common import get_value_by_path as getv +from ._common import set_value_by_path as setv +from ._operations_converters import _UploadToFileSearchStoreOperation_from_mldev +from .documents import AsyncDocuments, Documents +from .pagers import AsyncPager, Pager + +logger = logging.getLogger('google_genai.filesearchstores') + + +def _CreateFileSearchStoreConfig_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['display_name']) is not None: + setv(parent_object, ['displayName'], getv(from_object, ['display_name'])) + + return to_object + + +def _CreateFileSearchStoreParameters_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['config']) is not None: + _CreateFileSearchStoreConfig_to_mldev( + getv(from_object, ['config']), to_object + ) + + return to_object + + +def _DeleteFileSearchStoreConfig_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['force']) is not None: + setv(parent_object, ['_query', 'force'], getv(from_object, ['force'])) + + return to_object + + +def _DeleteFileSearchStoreParameters_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['name']) is not None: + setv(to_object, ['_url', 'name'], getv(from_object, ['name'])) + + if getv(from_object, ['config']) is not None: + _DeleteFileSearchStoreConfig_to_mldev( + getv(from_object, ['config']), to_object + ) + + return to_object + + +def _GetFileSearchStoreParameters_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['name']) is not None: + setv(to_object, ['_url', 'name'], getv(from_object, ['name'])) + + return to_object + + +def _ImportFileConfig_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['custom_metadata']) is not None: + setv( + parent_object, + ['customMetadata'], + [item for item in getv(from_object, ['custom_metadata'])], + ) + + if getv(from_object, ['chunking_config']) is not None: + setv( + parent_object, + ['chunkingConfig'], + getv(from_object, ['chunking_config']), + ) + + return to_object + + +def _ImportFileOperation_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['name']) is not None: + setv(to_object, ['name'], getv(from_object, ['name'])) + + if getv(from_object, ['metadata']) is not None: + setv(to_object, ['metadata'], getv(from_object, ['metadata'])) + + if getv(from_object, ['done']) is not None: + setv(to_object, ['done'], getv(from_object, ['done'])) + + if getv(from_object, ['error']) is not None: + setv(to_object, ['error'], getv(from_object, ['error'])) + + if getv(from_object, ['response']) is not None: + setv( + to_object, + ['response'], + _ImportFileResponse_from_mldev( + getv(from_object, ['response']), to_object + ), + ) + + return to_object + + +def _ImportFileParameters_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['file_search_store_name']) is not None: + setv( + to_object, + ['_url', 'file_search_store_name'], + getv(from_object, ['file_search_store_name']), + ) + + if getv(from_object, ['file_name']) is not None: + setv(to_object, ['fileName'], getv(from_object, ['file_name'])) + + if getv(from_object, ['config']) is not None: + _ImportFileConfig_to_mldev(getv(from_object, ['config']), to_object) + + return to_object + + +def _ImportFileResponse_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['sdkHttpResponse']) is not None: + setv( + to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse']) + ) + + if getv(from_object, ['parent']) is not None: + setv(to_object, ['parent'], getv(from_object, ['parent'])) + + if getv(from_object, ['documentName']) is not None: + setv(to_object, ['document_name'], getv(from_object, ['documentName'])) + + return to_object + + +def _ListFileSearchStoresConfig_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['page_size']) is not None: + setv( + parent_object, ['_query', 'pageSize'], getv(from_object, ['page_size']) + ) + + if getv(from_object, ['page_token']) is not None: + setv( + parent_object, + ['_query', 'pageToken'], + getv(from_object, ['page_token']), + ) + + return to_object + + +def _ListFileSearchStoresParameters_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['config']) is not None: + _ListFileSearchStoresConfig_to_mldev( + getv(from_object, ['config']), to_object + ) + + return to_object + + +def _ListFileSearchStoresResponse_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['sdkHttpResponse']) is not None: + setv( + to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse']) + ) + + if getv(from_object, ['nextPageToken']) is not None: + setv(to_object, ['next_page_token'], getv(from_object, ['nextPageToken'])) + + if getv(from_object, ['fileSearchStores']) is not None: + setv( + to_object, + ['file_search_stores'], + [item for item in getv(from_object, ['fileSearchStores'])], + ) + + return to_object + + +def _UploadToFileSearchStoreConfig_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['mime_type']) is not None: + setv(parent_object, ['mimeType'], getv(from_object, ['mime_type'])) + + if getv(from_object, ['display_name']) is not None: + setv(parent_object, ['displayName'], getv(from_object, ['display_name'])) + + if getv(from_object, ['custom_metadata']) is not None: + setv( + parent_object, + ['customMetadata'], + [item for item in getv(from_object, ['custom_metadata'])], + ) + + if getv(from_object, ['chunking_config']) is not None: + setv( + parent_object, + ['chunkingConfig'], + getv(from_object, ['chunking_config']), + ) + + return to_object + + +def _UploadToFileSearchStoreParameters_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['file_search_store_name']) is not None: + setv( + to_object, + ['_url', 'file_search_store_name'], + getv(from_object, ['file_search_store_name']), + ) + + if getv(from_object, ['config']) is not None: + _UploadToFileSearchStoreConfig_to_mldev( + getv(from_object, ['config']), to_object + ) + + return to_object + + +def _UploadToFileSearchStoreResumableResponse_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['sdkHttpResponse']) is not None: + setv( + to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse']) + ) + + return to_object + + +class FileSearchStores(_api_module.BaseModule): + + @cached_property + def documents(self) -> Documents: + return Documents(self._api_client) + + def create( + self, *, config: Optional[types.CreateFileSearchStoreConfigOrDict] = None + ) -> types.FileSearchStore: + """Creates a File Search Store. + + Args: + config (CreateFileSearchStoreConfig | None): Optional parameters for the + request. + + Returns: + FileSearchStore + """ + + parameter_model = types._CreateFileSearchStoreParameters( + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if self._api_client.vertexai: + raise ValueError( + 'This method is only supported in the Gemini Developer client.' + ) + else: + request_dict = _CreateFileSearchStoreParameters_to_mldev(parameter_model) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'fileSearchStores'.format_map(request_url_dict) + else: + path = 'fileSearchStores' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request( + 'post', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + return_value = types.FileSearchStore._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + + self._api_client._verify_response(return_value) + return return_value + + def get( + self, + *, + name: str, + config: Optional[types.GetFileSearchStoreConfigOrDict] = None, + ) -> types.FileSearchStore: + """Gets metadata about a FileSearchStore. + + Args: + name (str): The resource name of the FileSearchStore. Example: + `FileSearchStores/my-file-search-store-123` + config (GetFileSearchStoreConfig | None): Optional parameters for the + request. + + Returns: + A FileSearchStore object containing the metadata. + """ + + parameter_model = types._GetFileSearchStoreParameters( + name=name, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if self._api_client.vertexai: + raise ValueError( + 'This method is only supported in the Gemini Developer client.' + ) + else: + request_dict = _GetFileSearchStoreParameters_to_mldev(parameter_model) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{name}'.format_map(request_url_dict) + else: + path = '{name}' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request('get', path, request_dict, http_options) + + response_dict = {} if not response.body else json.loads(response.body) + + return_value = types.FileSearchStore._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + + self._api_client._verify_response(return_value) + return return_value + + def delete( + self, + *, + name: str, + config: Optional[types.DeleteFileSearchStoreConfigOrDict] = None, + ) -> None: + """Deletes a FileSearchStore. + + Args: + name (str): The resource name of the FileSearchStore. Example: + `FileSearchStores/my-file-search-store-123` + config (DeleteFileSearchStoreConfig | None): Optional parameters for the + request. + + Returns: + None + """ + + parameter_model = types._DeleteFileSearchStoreParameters( + name=name, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if self._api_client.vertexai: + raise ValueError( + 'This method is only supported in the Gemini Developer client.' + ) + else: + request_dict = _DeleteFileSearchStoreParameters_to_mldev(parameter_model) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{name}'.format_map(request_url_dict) + else: + path = '{name}' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + self._api_client.request('delete', path, request_dict, http_options) + + def _list( + self, *, config: Optional[types.ListFileSearchStoresConfigOrDict] = None + ) -> types.ListFileSearchStoresResponse: + parameter_model = types._ListFileSearchStoresParameters( + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if self._api_client.vertexai: + raise ValueError( + 'This method is only supported in the Gemini Developer client.' + ) + else: + request_dict = _ListFileSearchStoresParameters_to_mldev(parameter_model) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'fileSearchStores'.format_map(request_url_dict) + else: + path = 'fileSearchStores' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request('get', path, request_dict, http_options) + + response_dict = {} if not response.body else json.loads(response.body) + + if not self._api_client.vertexai: + response_dict = _ListFileSearchStoresResponse_from_mldev(response_dict) + + return_value = types.ListFileSearchStoresResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + + self._api_client._verify_response(return_value) + return return_value + + def _upload_to_file_search_store( + self, + *, + file_search_store_name: str, + config: Optional[types.UploadToFileSearchStoreConfigOrDict] = None, + ) -> types.UploadToFileSearchStoreResumableResponse: + parameter_model = types._UploadToFileSearchStoreParameters( + file_search_store_name=file_search_store_name, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if self._api_client.vertexai: + raise ValueError( + 'This method is only supported in the Gemini Developer client.' + ) + else: + request_dict = _UploadToFileSearchStoreParameters_to_mldev( + parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = ( + 'upload/v1beta/{file_search_store_name}:uploadToFileSearchStore' + .format_map(request_url_dict) + ) + else: + path = 'upload/v1beta/{file_search_store_name}:uploadToFileSearchStore' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request( + 'post', path, request_dict, http_options + ) + + if config is not None and getattr( + config, 'should_return_http_response', None + ): + return_value = types.UploadToFileSearchStoreResumableResponse( + sdk_http_response=response + ) + self._api_client._verify_response(return_value) + return return_value + + response_dict = {} if not response.body else json.loads(response.body) + + if not self._api_client.vertexai: + response_dict = _UploadToFileSearchStoreResumableResponse_from_mldev( + response_dict + ) + + return_value = ( + types.UploadToFileSearchStoreResumableResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + ) + + self._api_client._verify_response(return_value) + return return_value + + def import_file( + self, + *, + file_search_store_name: str, + file_name: str, + config: Optional[types.ImportFileConfigOrDict] = None, + ) -> types.ImportFileOperation: + """Imports a File from File Service to a FileSearchStore. + + This is a long-running operation, see aip.dev/151 + + Args: + file_search_store_name (str): The resource name of the FileSearchStore. + Example: `fileSearchStores/my-file-search-store-123` + file_name (str): The resource name of the File to import. Example: + `files/abc-123` + config (ImportFileConfig | None): Optional parameters for the request. + + Returns: + ImportFileOperation. + """ + + parameter_model = types._ImportFileParameters( + file_search_store_name=file_search_store_name, + file_name=file_name, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if self._api_client.vertexai: + raise ValueError( + 'This method is only supported in the Gemini Developer client.' + ) + else: + request_dict = _ImportFileParameters_to_mldev(parameter_model) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{file_search_store_name}:importFile'.format_map( + request_url_dict + ) + else: + path = '{file_search_store_name}:importFile' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request( + 'post', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if not self._api_client.vertexai: + response_dict = _ImportFileOperation_from_mldev(response_dict) + + return_value = types.ImportFileOperation._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + + self._api_client._verify_response(return_value) + return return_value + + def upload_to_file_search_store( + self, + *, + file_search_store_name: str, + file: Union[str, os.PathLike[str], io.IOBase], + config: Optional[types.UploadToFileSearchStoreConfigOrDict] = None, + ) -> types.UploadToFileSearchStoreOperation: + """Calls the API to upload a file to the given file search store. + + Args: + file_search_store_name: The resource name of the FileSearchStore. Example: + `fileSearchStores/file-search-store-123` + file: A path to the file or an `IOBase` object to be uploaded. If it's an + IOBase object, it must be opened in blocking (the default) mode and + binary mode. In other words, do not use non-blocking mode or text mode. + The given stream must be seekable, that is, it must be able to call + `seek()` on 'path'. + config: Optional parameters to set `diplay_name`, `mime_type`, and others. + """ + if self._api_client.vertexai: + raise ValueError( + 'This method is only supported in the Gemini Developer client.' + ) + if config is None: + user_config_dict: dict[str, Any] = {} + elif isinstance(config, dict): + user_config_dict = dict(config) + else: + user_config_dict = config.model_dump(exclude_unset=True) + + http_options, size_bytes, _ = _extra_utils.prepare_resumable_upload( + file, + user_http_options=user_config_dict.get('http_options'), + user_mime_type=user_config_dict.get('mime_type'), + ) + final_config_dict = { + **user_config_dict, + 'http_options': http_options, + 'should_return_http_response': True, + } + response = self._upload_to_file_search_store( + file_search_store_name=file_search_store_name, + config=types.UploadToFileSearchStoreConfig(**final_config_dict), + ) + if ( + response.sdk_http_response is None + or response.sdk_http_response.headers is None + or ( + 'x-goog-upload-url' not in response.sdk_http_response.headers + and 'X-Goog-Upload-URL' not in response.sdk_http_response.headers + ) + ): + raise KeyError( + 'Failed to upload file to file search store. Upload URL did not' + ' returned from the upload request.' + ) + elif 'x-goog-upload-url' in response.sdk_http_response.headers: + upload_url = response.sdk_http_response.headers['x-goog-upload-url'] + else: + upload_url = response.sdk_http_response.headers['X-Goog-Upload-URL'] + if isinstance(file, io.IOBase): + upload_response = self._api_client.upload_file( + file, upload_url, size_bytes, http_options=http_options + ) + else: + fs_path = os.fspath(file) + upload_response = self._api_client.upload_file( + fs_path, upload_url, size_bytes, http_options=http_options + ) + response_dict = _UploadToFileSearchStoreOperation_from_mldev( + upload_response.json + ) + return types.UploadToFileSearchStoreOperation._from_response( + response=response_dict, kwargs={} + ) + + def list( + self, *, config: Optional[types.ListFileSearchStoresConfigOrDict] = None + ) -> Pager[types.FileSearchStore]: + """Lists FileSearchStores. + + Args: + config (ListFileSearchStoresConfig): Optional configuration for the list + request. + + Returns: + A Pager object that contains one page of file search stores. When + iterating over + the pager, it automatically fetches the next page if there are more. + + Usage: + + .. code-block:: python + for file_search_store in client.file_search_stores.list(): + print(f"file search store: {file_search_store.name} - + {file_search_store.display_name}") + """ + + list_request = self._list + return Pager( + 'file_search_stores', + list_request, + self._list(config=config), + config, + ) + + +class AsyncFileSearchStores(_api_module.BaseModule): + + @cached_property + def documents(self) -> AsyncDocuments: + return AsyncDocuments(self._api_client) + + async def create( + self, *, config: Optional[types.CreateFileSearchStoreConfigOrDict] = None + ) -> types.FileSearchStore: + """Creates a File Search Store. + + Args: + config (CreateFileSearchStoreConfig | None): Optional parameters for the + request. + + Returns: + FileSearchStore + """ + + parameter_model = types._CreateFileSearchStoreParameters( + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if self._api_client.vertexai: + raise ValueError( + 'This method is only supported in the Gemini Developer client.' + ) + else: + request_dict = _CreateFileSearchStoreParameters_to_mldev(parameter_model) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'fileSearchStores'.format_map(request_url_dict) + else: + path = 'fileSearchStores' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'post', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + return_value = types.FileSearchStore._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + + self._api_client._verify_response(return_value) + return return_value + + async def get( + self, + *, + name: str, + config: Optional[types.GetFileSearchStoreConfigOrDict] = None, + ) -> types.FileSearchStore: + """Gets metadata about a FileSearchStore. + + Args: + name (str): The resource name of the FileSearchStore. Example: + `FileSearchStores/my-file-search-store-123` + config (GetFileSearchStoreConfig | None): Optional parameters for the + request. + + Returns: + A FileSearchStore object containing the metadata. + """ + + parameter_model = types._GetFileSearchStoreParameters( + name=name, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if self._api_client.vertexai: + raise ValueError( + 'This method is only supported in the Gemini Developer client.' + ) + else: + request_dict = _GetFileSearchStoreParameters_to_mldev(parameter_model) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{name}'.format_map(request_url_dict) + else: + path = '{name}' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'get', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + return_value = types.FileSearchStore._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + + self._api_client._verify_response(return_value) + return return_value + + async def delete( + self, + *, + name: str, + config: Optional[types.DeleteFileSearchStoreConfigOrDict] = None, + ) -> None: + """Deletes a FileSearchStore. + + Args: + name (str): The resource name of the FileSearchStore. Example: + `FileSearchStores/my-file-search-store-123` + config (DeleteFileSearchStoreConfig | None): Optional parameters for the + request. + + Returns: + None + """ + + parameter_model = types._DeleteFileSearchStoreParameters( + name=name, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if self._api_client.vertexai: + raise ValueError( + 'This method is only supported in the Gemini Developer client.' + ) + else: + request_dict = _DeleteFileSearchStoreParameters_to_mldev(parameter_model) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{name}'.format_map(request_url_dict) + else: + path = '{name}' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + await self._api_client.async_request( + 'delete', path, request_dict, http_options + ) + + async def _list( + self, *, config: Optional[types.ListFileSearchStoresConfigOrDict] = None + ) -> types.ListFileSearchStoresResponse: + parameter_model = types._ListFileSearchStoresParameters( + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if self._api_client.vertexai: + raise ValueError( + 'This method is only supported in the Gemini Developer client.' + ) + else: + request_dict = _ListFileSearchStoresParameters_to_mldev(parameter_model) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'fileSearchStores'.format_map(request_url_dict) + else: + path = 'fileSearchStores' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'get', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if not self._api_client.vertexai: + response_dict = _ListFileSearchStoresResponse_from_mldev(response_dict) + + return_value = types.ListFileSearchStoresResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + + self._api_client._verify_response(return_value) + return return_value + + async def _upload_to_file_search_store( + self, + *, + file_search_store_name: str, + config: Optional[types.UploadToFileSearchStoreConfigOrDict] = None, + ) -> types.UploadToFileSearchStoreResumableResponse: + parameter_model = types._UploadToFileSearchStoreParameters( + file_search_store_name=file_search_store_name, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if self._api_client.vertexai: + raise ValueError( + 'This method is only supported in the Gemini Developer client.' + ) + else: + request_dict = _UploadToFileSearchStoreParameters_to_mldev( + parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = ( + 'upload/v1beta/{file_search_store_name}:uploadToFileSearchStore' + .format_map(request_url_dict) + ) + else: + path = 'upload/v1beta/{file_search_store_name}:uploadToFileSearchStore' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'post', path, request_dict, http_options + ) + + if config is not None and getattr( + config, 'should_return_http_response', None + ): + return_value = types.UploadToFileSearchStoreResumableResponse( + sdk_http_response=response + ) + self._api_client._verify_response(return_value) + return return_value + + response_dict = {} if not response.body else json.loads(response.body) + + if not self._api_client.vertexai: + response_dict = _UploadToFileSearchStoreResumableResponse_from_mldev( + response_dict + ) + + return_value = ( + types.UploadToFileSearchStoreResumableResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + ) + + self._api_client._verify_response(return_value) + return return_value + + async def import_file( + self, + *, + file_search_store_name: str, + file_name: str, + config: Optional[types.ImportFileConfigOrDict] = None, + ) -> types.ImportFileOperation: + """Imports a File from File Service to a FileSearchStore. + + This is a long-running operation, see aip.dev/151 + + Args: + file_search_store_name (str): The resource name of the FileSearchStore. + Example: `fileSearchStores/my-file-search-store-123` + file_name (str): The resource name of the File to import. Example: + `files/abc-123` + config (ImportFileConfig | None): Optional parameters for the request. + + Returns: + ImportFileOperation. + """ + + parameter_model = types._ImportFileParameters( + file_search_store_name=file_search_store_name, + file_name=file_name, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if self._api_client.vertexai: + raise ValueError( + 'This method is only supported in the Gemini Developer client.' + ) + else: + request_dict = _ImportFileParameters_to_mldev(parameter_model) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{file_search_store_name}:importFile'.format_map( + request_url_dict + ) + else: + path = '{file_search_store_name}:importFile' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'post', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if not self._api_client.vertexai: + response_dict = _ImportFileOperation_from_mldev(response_dict) + + return_value = types.ImportFileOperation._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + + self._api_client._verify_response(return_value) + return return_value + + async def upload_to_file_search_store( + self, + *, + file_search_store_name: str, + file: Union[str, os.PathLike[str], io.IOBase], + config: Optional[types.UploadToFileSearchStoreConfigOrDict] = None, + ) -> types.UploadToFileSearchStoreOperation: + """Calls the API to upload a file to the given file search store. + + Args: + file_search_store_name: The resource name of the FileSearchStore. Example: + `fileSearchStores/file-search-store-123` + file: A path to the file or an `IOBase` object to be uploaded. If it's an + IOBase object, it must be opened in blocking (the default) mode and + binary mode. In other words, do not use non-blocking mode or text mode. + The given stream must be seekable, that is, it must be able to call + `seek()` on 'path'. + config: Optional parameters to set `diplay_name`, `mime_type` and others. + """ + if self._api_client.vertexai: + raise ValueError( + 'This method is only supported in the Gemini Developer client.' + ) + if config is None: + user_config_dict: dict[str, Any] = {} + elif isinstance(config, dict): + user_config_dict = dict(config) + else: + user_config_dict = config.model_dump(exclude_unset=True) + + http_options, size_bytes, _ = _extra_utils.prepare_resumable_upload( + file, + user_http_options=user_config_dict.get('http_options'), + user_mime_type=user_config_dict.get('mime_type'), + ) + final_config_dict = { + **user_config_dict, + 'http_options': http_options, + 'should_return_http_response': True, + } + response = await self._upload_to_file_search_store( + file_search_store_name=file_search_store_name, + config=types.UploadToFileSearchStoreConfig(**final_config_dict), + ) + if ( + response.sdk_http_response is None + or response.sdk_http_response.headers is None + or ( + 'x-goog-upload-url' not in response.sdk_http_response.headers + and 'X-Goog-Upload-URL' not in response.sdk_http_response.headers + ) + ): + raise KeyError( + 'Failed to upload file to file search store. Upload URL did not' + ' returned from the upload request.' + ) + elif 'x-goog-upload-url' in response.sdk_http_response.headers: + upload_url = response.sdk_http_response.headers['x-goog-upload-url'] + else: + upload_url = response.sdk_http_response.headers['X-Goog-Upload-URL'] + if isinstance(file, io.IOBase): + upload_response = await self._api_client.async_upload_file( + file, upload_url, size_bytes, http_options=http_options + ) + else: + fs_path = os.fspath(file) + upload_response = await self._api_client.async_upload_file( + fs_path, upload_url, size_bytes, http_options=http_options + ) + response_dict = _UploadToFileSearchStoreOperation_from_mldev( + upload_response.json + ) + return types.UploadToFileSearchStoreOperation._from_response( + response=response_dict, kwargs={} + ) + + async def list( + self, *, config: Optional[types.ListFileSearchStoresConfigOrDict] = None + ) -> AsyncPager[types.FileSearchStore]: + """Lists FileSearchStores asynchronously. + + Args: + config (ListFileSearchStoresConfig): Optional parameters for the request, + such as page_size. + + Returns: + A Pager object that contains one page of FileSearchStores. When iterating + over + the pager, it automatically fetches the next page if there are more. + + Usage: + + .. code-block:: python + async for file_search_store in await client.aio.file_search_stores.list(): + print(f"file search store: {file_search_store.name} - + {file_search_store.display_name}") + """ + + list_request = self._list + return AsyncPager( + 'file_search_stores', + list_request, + await self._list(config=config), + config, + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/files.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/files.py new file mode 100644 index 0000000000000000000000000000000000000000..20f1f8c7523b0e40483a7d5598d7d57c6448a959 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/files.py @@ -0,0 +1,1394 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# Code generated by the Google Gen AI SDK generator DO NOT EDIT. + +import io +import json +import logging +import os +from typing import Any, Optional, Union +from urllib.parse import urlencode + +import google.auth + +from . import _api_client +from . import _api_module +from . import _common +from . import _extra_utils +from . import _transformers as t +from . import types +from ._common import get_value_by_path as getv +from ._common import set_value_by_path as setv +from .pagers import AsyncPager, Pager + +logger = logging.getLogger('google_genai.files') + + +def _CreateFileParameters_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['file']) is not None: + setv(to_object, ['file'], getv(from_object, ['file'])) + + return to_object + + +def _CreateFileResponse_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['sdkHttpResponse']) is not None: + setv( + to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse']) + ) + + return to_object + + +def _DeleteFileParameters_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['name']) is not None: + setv( + to_object, ['_url', 'file'], t.t_file_name(getv(from_object, ['name'])) + ) + + return to_object + + +def _DeleteFileResponse_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['sdkHttpResponse']) is not None: + setv( + to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse']) + ) + + return to_object + + +def _GetFileParameters_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['name']) is not None: + setv( + to_object, ['_url', 'file'], t.t_file_name(getv(from_object, ['name'])) + ) + + return to_object + + +def _InternalRegisterFilesParameters_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['uris']) is not None: + setv(to_object, ['uris'], getv(from_object, ['uris'])) + + return to_object + + +def _ListFilesConfig_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['page_size']) is not None: + setv( + parent_object, ['_query', 'pageSize'], getv(from_object, ['page_size']) + ) + + if getv(from_object, ['page_token']) is not None: + setv( + parent_object, + ['_query', 'pageToken'], + getv(from_object, ['page_token']), + ) + + return to_object + + +def _ListFilesParameters_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['config']) is not None: + _ListFilesConfig_to_mldev(getv(from_object, ['config']), to_object) + + return to_object + + +def _ListFilesResponse_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['sdkHttpResponse']) is not None: + setv( + to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse']) + ) + + if getv(from_object, ['nextPageToken']) is not None: + setv(to_object, ['next_page_token'], getv(from_object, ['nextPageToken'])) + + if getv(from_object, ['files']) is not None: + setv(to_object, ['files'], [item for item in getv(from_object, ['files'])]) + + return to_object + + +def _RegisterFilesResponse_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['sdkHttpResponse']) is not None: + setv( + to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse']) + ) + + if getv(from_object, ['files']) is not None: + setv(to_object, ['files'], [item for item in getv(from_object, ['files'])]) + + return to_object + + +class Files(_api_module.BaseModule): + + def _list( + self, *, config: Optional[types.ListFilesConfigOrDict] = None + ) -> types.ListFilesResponse: + parameter_model = types._ListFilesParameters( + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if self._api_client.vertexai: + raise ValueError( + 'This method is only supported in the Gemini Developer client.' + ) + else: + request_dict = _ListFilesParameters_to_mldev(parameter_model) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'files'.format_map(request_url_dict) + else: + path = 'files' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request('get', path, request_dict, http_options) + + response_dict = {} if not response.body else json.loads(response.body) + + if not self._api_client.vertexai: + response_dict = _ListFilesResponse_from_mldev(response_dict) + + return_value = types.ListFilesResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + return_value.sdk_http_response = types.HttpResponse( + headers=response.headers + ) + self._api_client._verify_response(return_value) + return return_value + + def _create( + self, + *, + file: types.FileOrDict, + config: Optional[types.CreateFileConfigOrDict] = None, + ) -> types.CreateFileResponse: + parameter_model = types._CreateFileParameters( + file=file, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if self._api_client.vertexai: + raise ValueError( + 'This method is only supported in the Gemini Developer client.' + ) + else: + request_dict = _CreateFileParameters_to_mldev(parameter_model) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'upload/v1beta/files'.format_map(request_url_dict) + else: + path = 'upload/v1beta/files' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request( + 'post', path, request_dict, http_options + ) + + if config is not None and getattr( + config, 'should_return_http_response', None + ): + return_value = types.CreateFileResponse(sdk_http_response=response) + self._api_client._verify_response(return_value) + return return_value + + response_dict = {} if not response.body else json.loads(response.body) + + if not self._api_client.vertexai: + response_dict = _CreateFileResponse_from_mldev(response_dict) + + return_value = types.CreateFileResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + + self._api_client._verify_response(return_value) + return return_value + + def get( + self, *, name: str, config: Optional[types.GetFileConfigOrDict] = None + ) -> types.File: + """Retrieves the file information from the service. + + Args: + name (str): The name identifier for the file to retrieve. + config (GetFileConfig): Optional, configuration for the get method. + + Returns: + File: The file information. + + Usage: + + .. code-block:: python + + file = client.files.get(name='files/...') + print(file.uri) + """ + + parameter_model = types._GetFileParameters( + name=name, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if self._api_client.vertexai: + raise ValueError( + 'This method is only supported in the Gemini Developer client.' + ) + else: + request_dict = _GetFileParameters_to_mldev(parameter_model) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'files/{file}'.format_map(request_url_dict) + else: + path = 'files/{file}' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request('get', path, request_dict, http_options) + + response_dict = {} if not response.body else json.loads(response.body) + + return_value = types.File._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + + self._api_client._verify_response(return_value) + return return_value + + def delete( + self, *, name: str, config: Optional[types.DeleteFileConfigOrDict] = None + ) -> types.DeleteFileResponse: + """Deletes a remotely stored file. + + Args: + name (str): The name identifier for the file to delete. + config (DeleteFileConfig): Optional, configuration for the delete method. + + Returns: + DeleteFileResponse: The response for the delete method + + Usage: + + .. code-block:: python + + client.files.delete(name='files/...') + """ + + parameter_model = types._DeleteFileParameters( + name=name, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if self._api_client.vertexai: + raise ValueError( + 'This method is only supported in the Gemini Developer client.' + ) + else: + request_dict = _DeleteFileParameters_to_mldev(parameter_model) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'files/{file}'.format_map(request_url_dict) + else: + path = 'files/{file}' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request( + 'delete', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if not self._api_client.vertexai: + response_dict = _DeleteFileResponse_from_mldev(response_dict) + + return_value = types.DeleteFileResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + return_value.sdk_http_response = types.HttpResponse( + headers=response.headers + ) + self._api_client._verify_response(return_value) + return return_value + + def _register_files( + self, + *, + uris: list[str], + config: Optional[types.RegisterFilesConfigOrDict] = None, + ) -> types.RegisterFilesResponse: + parameter_model = types._InternalRegisterFilesParameters( + uris=uris, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if self._api_client.vertexai: + raise ValueError( + 'This method is only supported in the Gemini Developer client.' + ) + else: + request_dict = _InternalRegisterFilesParameters_to_mldev(parameter_model) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'files:register'.format_map(request_url_dict) + else: + path = 'files:register' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request( + 'post', path, request_dict, http_options + ) + + if config is not None and getattr( + config, 'should_return_http_response', None + ): + return_value = types.RegisterFilesResponse(sdk_http_response=response) + self._api_client._verify_response(return_value) + return return_value + + response_dict = {} if not response.body else json.loads(response.body) + + if not self._api_client.vertexai: + response_dict = _RegisterFilesResponse_from_mldev(response_dict) + + return_value = types.RegisterFilesResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + + self._api_client._verify_response(return_value) + return return_value + + def upload( + self, + *, + file: Union[str, os.PathLike[str], io.IOBase], + config: Optional[types.UploadFileConfigOrDict] = None, + ) -> types.File: + """Calls the API to upload a file using a supported file service. + + Args: + file: A path to the file or an `IOBase` object to be uploaded. If it's an + IOBase object, it must be opened in blocking (the default) mode and + binary mode. In other words, do not use non-blocking mode or text mode. + The given stream must be seekable, that is, it must be able to call + `seek()` on 'path'. + config: Optional parameters to set `diplay_name`, `mime_type`, and `name`. + """ + if self._api_client.vertexai: + raise ValueError( + 'This method is only supported in the Gemini Developer client.' + ) + config_model = types.UploadFileConfig() + if config: + if isinstance(config, dict): + config_model = types.UploadFileConfig(**config) + else: + config_model = config + file_obj = types.File( + mime_type=config_model.mime_type, + name=config_model.name, + display_name=config_model.display_name, + ) + else: # if not config + file_obj = types.File() + if file_obj.name is not None and not file_obj.name.startswith('files/'): + file_obj.name = f'files/{file_obj.name}' + + http_options, size_bytes, mime_type = _extra_utils.prepare_resumable_upload( + file, + user_http_options=config_model.http_options, + user_mime_type=config_model.mime_type, + ) + file_obj.size_bytes = size_bytes + file_obj.mime_type = mime_type + response = self._create( + file=file_obj, + config=types.CreateFileConfig( + http_options=http_options, should_return_http_response=True + ), + ) + + if ( + response.sdk_http_response is None + or response.sdk_http_response.headers is None + or 'x-goog-upload-url' not in response.sdk_http_response.headers + ): + raise KeyError( + 'Failed to create file. Upload URL did not returned from the create' + ' file request.' + ) + upload_url = response.sdk_http_response.headers['x-goog-upload-url'] + + if isinstance(file, io.IOBase): + return_file = self._api_client.upload_file( + file, upload_url, file_obj.size_bytes, http_options=http_options + ) + else: + fs_path = os.fspath(file) + return_file = self._api_client.upload_file( + fs_path, upload_url, file_obj.size_bytes, http_options=http_options + ) + + return types.File._from_response( + response=return_file.json['file'], + kwargs=config_model.model_dump() if config else {}, + ) + + def download( + self, + *, + file: Union[str, types.File, types.Video, types.GeneratedVideo], + config: Optional[types.DownloadFileConfigOrDict] = None, + ) -> bytes: + """Downloads a file's data from storage. + + Files created by `upload` can't be downloaded. You can tell which files are + downloadable by checking the `source` or `download_uri` property. + + Note: This method returns the data as bytes. For `Video` and + `GeneratedVideo` objects there is an additional side effect, that it also + sets the `video_bytes` property on the `Video` object. + + Args: + file (str): A file name, uri, or file object. Identifying which file to + download. + config (DownloadFileConfigOrDict): Optional, configuration for the get + method. + + Returns: + File: The file data as bytes. + + Usage: + + .. code-block:: python + + for file client.files.list(): + if file.download_uri is not None: + break + else: + raise ValueError('No files found with a `download_uri`.') + data = client.files.download(file=file) + # data = client.files.download(file=file.name) + # data = client.files.download(file=file.download_uri) + + video = types.Video(uri=file.uri) + video_bytes = client.files.download(file=video) + video.video_bytes + """ + if self._api_client.vertexai: + raise ValueError( + 'This method is only supported in the Gemini Developer client.' + ) + + config_model = None + if config: + if isinstance(config, dict): + config_model = types.DownloadFileConfig(**config) + else: + config_model = config + + if isinstance(file, types.File) and file.download_uri is None: + raise ValueError( + "Only generated files can be downloaded, uploaded files can't be " + 'downloaded. You can tell which files are downloadable by checking ' + 'the `source` or `download_uri` property.' + ) + name = t.t_file_name(file) + + path = f'files/{name}:download' + + query_params = {'alt': 'media'} + path = f'{path}?{urlencode(query_params)}' + http_options = None + if getv(config_model, ['http_options']) is not None: + http_options = getv(config_model, ['http_options']) + + data = self._api_client.download_file( + path, + http_options=http_options, + ) + + if isinstance(file, types.Video): + file.video_bytes = data + elif isinstance(file, types.GeneratedVideo) and file.video is not None: + file.video.video_bytes = data + + return data + + def register_files( + self, + *, + auth: google.auth.credentials.Credentials, + uris: list[str], + config: Optional[types.RegisterFilesConfigOrDict] = None, + ) -> types.RegisterFilesResponse: + """Registers gcs files with the file service.""" + if not isinstance(auth, google.auth.credentials.Credentials): + raise ValueError( + 'auth must be a google.auth.credentials.Credentials object.' + ) + if config is None: + config = types.RegisterFilesConfig() + else: + config = types.RegisterFilesConfig.model_validate(config) + config = config.model_copy(deep=True) + + http_options = config.http_options or types.HttpOptions() + headers = http_options.headers or {} + headers = {k.lower(): v for k, v in headers.items()} + + token = _api_client.get_token_from_credentials(self._api_client, auth) + headers['authorization'] = f'Bearer {token}' + + if auth.quota_project_id: + headers['x-goog-user-project'] = auth.quota_project_id + + http_options.headers = headers + config.http_options = http_options + + return self._register_files(uris=uris, config=config) + + def list( + self, *, config: Optional[types.ListFilesConfigOrDict] = None + ) -> Pager[types.File]: + """Lists all files from the service. + + Args: + config (ListFilesConfig): Optional, configuration for the list method. + + Returns: + A Pager object that contains one page of files. When iterating over + the pager, it automatically fetches the next page if there are more. + + Usage: + + .. code-block:: python + + for file in client.files.list(config={'page_size': 10}): + print(file.name) + """ + + list_request = self._list + return Pager( + 'files', + list_request, + self._list(config=config), + config, + ) + + +class AsyncFiles(_api_module.BaseModule): + + async def _list( + self, *, config: Optional[types.ListFilesConfigOrDict] = None + ) -> types.ListFilesResponse: + parameter_model = types._ListFilesParameters( + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if self._api_client.vertexai: + raise ValueError( + 'This method is only supported in the Gemini Developer client.' + ) + else: + request_dict = _ListFilesParameters_to_mldev(parameter_model) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'files'.format_map(request_url_dict) + else: + path = 'files' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'get', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if not self._api_client.vertexai: + response_dict = _ListFilesResponse_from_mldev(response_dict) + + return_value = types.ListFilesResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + return_value.sdk_http_response = types.HttpResponse( + headers=response.headers + ) + self._api_client._verify_response(return_value) + return return_value + + async def _create( + self, + *, + file: types.FileOrDict, + config: Optional[types.CreateFileConfigOrDict] = None, + ) -> types.CreateFileResponse: + parameter_model = types._CreateFileParameters( + file=file, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if self._api_client.vertexai: + raise ValueError( + 'This method is only supported in the Gemini Developer client.' + ) + else: + request_dict = _CreateFileParameters_to_mldev(parameter_model) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'upload/v1beta/files'.format_map(request_url_dict) + else: + path = 'upload/v1beta/files' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'post', path, request_dict, http_options + ) + + if config is not None and getattr( + config, 'should_return_http_response', None + ): + return_value = types.CreateFileResponse(sdk_http_response=response) + self._api_client._verify_response(return_value) + return return_value + + response_dict = {} if not response.body else json.loads(response.body) + + if not self._api_client.vertexai: + response_dict = _CreateFileResponse_from_mldev(response_dict) + + return_value = types.CreateFileResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + + self._api_client._verify_response(return_value) + return return_value + + async def get( + self, *, name: str, config: Optional[types.GetFileConfigOrDict] = None + ) -> types.File: + """Retrieves the file information from the service. + + Args: + name (str): The name identifier for the file to retrieve. + config (GetFileConfig): Optional, configuration for the get method. + + Returns: + File: The file information. + + Usage: + + .. code-block:: python + + file = await client.aio.files.get(name='files/...') + print(file.uri) + """ + + parameter_model = types._GetFileParameters( + name=name, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if self._api_client.vertexai: + raise ValueError( + 'This method is only supported in the Gemini Developer client.' + ) + else: + request_dict = _GetFileParameters_to_mldev(parameter_model) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'files/{file}'.format_map(request_url_dict) + else: + path = 'files/{file}' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'get', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + return_value = types.File._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + + self._api_client._verify_response(return_value) + return return_value + + async def delete( + self, *, name: str, config: Optional[types.DeleteFileConfigOrDict] = None + ) -> types.DeleteFileResponse: + """Deletes a remotely stored file. + + Args: + name (str): The name identifier for the file to delete. + config (DeleteFileConfig): Optional, configuration for the delete method. + + Returns: + DeleteFileResponse: The response for the delete method + + Usage: + + .. code-block:: python + + await client.aio.files.delete(name='files/...') + """ + + parameter_model = types._DeleteFileParameters( + name=name, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if self._api_client.vertexai: + raise ValueError( + 'This method is only supported in the Gemini Developer client.' + ) + else: + request_dict = _DeleteFileParameters_to_mldev(parameter_model) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'files/{file}'.format_map(request_url_dict) + else: + path = 'files/{file}' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'delete', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if not self._api_client.vertexai: + response_dict = _DeleteFileResponse_from_mldev(response_dict) + + return_value = types.DeleteFileResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + return_value.sdk_http_response = types.HttpResponse( + headers=response.headers + ) + self._api_client._verify_response(return_value) + return return_value + + async def _register_files( + self, + *, + uris: list[str], + config: Optional[types.RegisterFilesConfigOrDict] = None, + ) -> types.RegisterFilesResponse: + parameter_model = types._InternalRegisterFilesParameters( + uris=uris, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if self._api_client.vertexai: + raise ValueError( + 'This method is only supported in the Gemini Developer client.' + ) + else: + request_dict = _InternalRegisterFilesParameters_to_mldev(parameter_model) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'files:register'.format_map(request_url_dict) + else: + path = 'files:register' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'post', path, request_dict, http_options + ) + + if config is not None and getattr( + config, 'should_return_http_response', None + ): + return_value = types.RegisterFilesResponse(sdk_http_response=response) + self._api_client._verify_response(return_value) + return return_value + + response_dict = {} if not response.body else json.loads(response.body) + + if not self._api_client.vertexai: + response_dict = _RegisterFilesResponse_from_mldev(response_dict) + + return_value = types.RegisterFilesResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + + self._api_client._verify_response(return_value) + return return_value + + async def upload( + self, + *, + file: Union[str, os.PathLike[str], io.IOBase], + config: Optional[types.UploadFileConfigOrDict] = None, + ) -> types.File: + """Calls the API to upload a file asynchronously using a supported file service. + + Args: + file: A path to the file or an `IOBase` object to be uploaded. If it's an + IOBase object, it must be opened in blocking (the default) mode and + binary mode. In other words, do not use non-blocking mode or text mode. + The given stream must be seekable, that is, it must be able to call + `seek()` on 'path'. + config: Optional parameters to set `diplay_name`, `mime_type`, and `name`. + """ + if self._api_client.vertexai: + raise ValueError( + 'This method is only supported in the Gemini Developer client.' + ) + config_model = types.UploadFileConfig() + if config: + if isinstance(config, dict): + config_model = types.UploadFileConfig(**config) + else: + config_model = config + file_obj = types.File( + mime_type=config_model.mime_type, + name=config_model.name, + display_name=config_model.display_name, + ) + else: # if not config + file_obj = types.File() + if file_obj.name is not None and not file_obj.name.startswith('files/'): + file_obj.name = f'files/{file_obj.name}' + + http_options, size_bytes, mime_type = _extra_utils.prepare_resumable_upload( + file, + user_http_options=config_model.http_options, + user_mime_type=config_model.mime_type, + ) + file_obj.size_bytes = size_bytes + file_obj.mime_type = mime_type + response = await self._create( + file=file_obj, + config=types.CreateFileConfig( + http_options=http_options, should_return_http_response=True + ), + ) + if ( + response.sdk_http_response is None + or response.sdk_http_response.headers is None + or ( + 'x-goog-upload-url' not in response.sdk_http_response.headers + and 'X-Goog-Upload-URL' not in response.sdk_http_response.headers + ) + ): + raise KeyError( + 'Failed to create file. Upload URL did not returned from the create' + ' file request.' + ) + elif 'x-goog-upload-url' in response.sdk_http_response.headers: + upload_url = response.sdk_http_response.headers['x-goog-upload-url'] + else: + upload_url = response.sdk_http_response.headers['X-Goog-Upload-URL'] + + if isinstance(file, io.IOBase): + return_file = await self._api_client.async_upload_file( + file, upload_url, file_obj.size_bytes, http_options=http_options + ) + else: + fs_path = os.fspath(file) + return_file = await self._api_client.async_upload_file( + fs_path, upload_url, file_obj.size_bytes, http_options=http_options + ) + + return types.File._from_response( + response=return_file.json['file'], + kwargs=config_model.model_dump() if config else {}, + ) + + async def download( + self, + *, + file: Union[str, types.File], + config: Optional[types.DownloadFileConfigOrDict] = None, + ) -> bytes: + """Downloads a file's data from the file service. + + The Vertex-AI implementation of the API foes not include the file service. + + Files created by `upload` can't be downloaded. You can tell which files are + downloadable by checking the `download_uri` property. + + Args: + File (str): A file name, uri, or file object. Identifying which file to + download. + config (DownloadFileConfigOrDict): Optional, configuration for the get + method. + + Returns: + File: The file data as bytes. + + Usage: + + .. code-block:: python + + for file client.files.list(): + if file.download_uri is not None: + break + else: + raise ValueError('No files found with a `download_uri`.') + data = client.files.download(file=file) + # data = client.files.download(file=file.name) + # data = client.files.download(file=file.uri) + """ + if self._api_client.vertexai: + raise ValueError( + 'This method is only supported in the Gemini Developer client.' + ) + + config_model = None + if config: + if isinstance(config, dict): + config_model = types.DownloadFileConfig(**config) + else: + config_model = config + + name = t.t_file_name(file) + + path = f'files/{name}:download' + + http_options = None + if getv(config_model, ['http_options']) is not None: + http_options = getv(config_model, ['http_options']) + + query_params = {'alt': 'media'} + if query_params: + path = f'{path}?{urlencode(query_params)}' + + data = await self._api_client.async_download_file( + path, + http_options=http_options, + ) + + return data + + async def register_files( + self, + *, + auth: google.auth.credentials.Credentials, + uris: list[str], + config: Optional[types.RegisterFilesConfigOrDict] = None, + ) -> types.RegisterFilesResponse: + """Registers gcs files with the file service.""" + if not isinstance(auth, google.auth.credentials.Credentials): + raise ValueError( + 'auth must be a google.auth.credentials.Credentials object.' + ) + if config is None: + config = types.RegisterFilesConfig() + else: + config = types.RegisterFilesConfig.model_validate(config) + config = config.model_copy(deep=True) + + http_options = config.http_options or types.HttpOptions() + headers = http_options.headers or {} + headers = {k.lower(): v for k, v in headers.items()} + + token = await _api_client.async_get_token_from_credentials( + self._api_client, auth + ) + headers['authorization'] = f'Bearer {token}' + + if auth.quota_project_id: + headers['x-goog-user-project'] = auth.quota_project_id + + http_options.headers = headers + config.http_options = http_options + + return await self._register_files(uris=uris, config=config) + + async def list( + self, *, config: Optional[types.ListFilesConfigOrDict] = None + ) -> AsyncPager[types.File]: + """Lists all files from the service asynchronously. + + Args: + config (ListFilesConfig): Optional, configuration for the list method. + + Returns: + A Pager object that contains one page of files. When iterating over + the pager, it automatically fetches the next page if there are more. + + Usage: + + .. code-block:: python + + async for file in await client.aio.files.list(config={'page_size': 10}): + print(file.name) + """ + + list_request = self._list + return AsyncPager( + 'files', + list_request, + await self._list(config=config), + config, + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/interactions.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/interactions.py new file mode 100644 index 0000000000000000000000000000000000000000..de2302b390fe9db333c731daa4929d453449d63a --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/interactions.py @@ -0,0 +1,17 @@ +# Copyright 2025 Google LLC +# +# Licensed 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 stainless types.""" + +from ._interactions.types import * diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/live.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/live.py new file mode 100644 index 0000000000000000000000000000000000000000..b35e918cec378c56dc7e414ac38e4c03e003dfa3 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/live.py @@ -0,0 +1,1198 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +"""[Preview] Live API client.""" + +import asyncio +import base64 +import contextlib +import json +import logging +import typing +from typing import Any, AsyncIterator, Optional, Sequence, Union, get_args +import warnings + +import google.auth +import pydantic +import websockets + +from . import _api_module +from . import _common +from . import _live_converters as live_converters +from . import _mcp_utils +from . import _transformers as t +from . import errors +from . import types +from ._api_client import BaseApiClient +from ._common import get_value_by_path as getv +from ._common import set_value_by_path as setv +from .live_music import AsyncLiveMusic +from .models import _Content_to_mldev + +ConnectionClosed = websockets.ConnectionClosed + +try: + from websockets.asyncio.client import ClientConnection + from websockets.asyncio.client import connect as ws_connect +except ModuleNotFoundError: + # This try/except is for TAP, mypy complains about it which is why we have the type: ignore + from websockets.client import ClientConnection # type: ignore + from websockets.client import connect as ws_connect # type: ignore + +try: + from google.auth.transport import requests +except ImportError: + requests = None # type: ignore[assignment] + +if typing.TYPE_CHECKING: + from mcp import ClientSession as McpClientSession + from mcp.types import Tool as McpTool + from ._adapters import McpToGenAiToolAdapter + from ._mcp_utils import mcp_to_gemini_tool +else: + McpClientSession: typing.Type = Any + McpTool: typing.Type = Any + McpToGenAiToolAdapter: typing.Type = Any + try: + from mcp import ClientSession as McpClientSession + from mcp.types import Tool as McpTool + from ._adapters import McpToGenAiToolAdapter + from ._mcp_utils import mcp_to_gemini_tool + except ImportError: + McpClientSession = None + McpTool = None + McpToGenAiToolAdapter = None + mcp_to_gemini_tool = None + +logger = logging.getLogger('google_genai.live') + +_FUNCTION_RESPONSE_REQUIRES_ID = ( + 'FunctionResponse request must have an `id` field from the' + ' response of a ToolCall.FunctionalCalls in Google AI.' +) + + +class AsyncSession: + """[Preview] AsyncSession.""" + + def __init__( + self, + api_client: BaseApiClient, + websocket: ClientConnection, + session_id: Optional[str] = None, + setup_complete: Optional[types.LiveServerSetupComplete] = None, + ): + self._api_client = api_client + self._ws = websocket + self.session_id = session_id + self.setup_complete = setup_complete + + async def send( + self, + *, + input: Optional[ + Union[ + types.ContentListUnion, + types.ContentListUnionDict, + types.LiveClientContentOrDict, + types.LiveClientRealtimeInputOrDict, + types.LiveClientToolResponseOrDict, + types.FunctionResponseOrDict, + Sequence[types.FunctionResponseOrDict], + ] + ] = None, + end_of_turn: Optional[bool] = False, + ) -> None: + """[Deprecated] Send input to the model. + + > **Warning**: This method is deprecated and will be removed in a future + version (not before Q3 2025). Please use one of the more specific methods: + `send_client_content`, `send_realtime_input`, or `send_tool_response` + instead. + + The method will send the input request to the server. + + Args: + input: The input request to the model. + end_of_turn: Whether the input is the last message in a turn. + + Example usage: + + .. code-block:: python + + client = genai.Client(api_key=API_KEY) + + async with client.aio.live.connect(model='...') as session: + await session.send(input='Hello world!', end_of_turn=True) + async for message in session.receive(): + print(message) + """ + warnings.warn( + 'The `session.send` method is deprecated and will be removed in a ' + 'future version (not before Q3 2025).\n' + 'Please use one of the more specific methods: `send_client_content`, ' + '`send_realtime_input`, or `send_tool_response` instead.', + DeprecationWarning, + stacklevel=2, + ) + client_message = self._parse_client_message(input, end_of_turn) + await self._ws.send(json.dumps(client_message)) + + async def send_client_content( + self, + *, + turns: Optional[ + Union[ + types.Content, + types.ContentDict, + list[Union[types.Content, types.ContentDict]], + ] + ] = None, + turn_complete: bool = True, + ) -> None: + """Send non-realtime, turn based content to the model. + + There are two ways to send messages to the live API: + `send_client_content` and `send_realtime_input`. + + `send_client_content` messages are added to the model context **in order**. + Having a conversation using `send_client_content` messages is roughly + equivalent to using the `Chat.send_message_stream` method, except that the + state of the `chat` history is stored on the API server. + + Because of `send_client_content`'s order guarantee, the model cannot + respond as quickly to `send_client_content` messages as to + `send_realtime_input` messages. This makes the biggest difference when + sending objects that have significant preprocessing time (typically images). + + The `send_client_content` message sends a list of `Content` objects, + which has more options than the `media:Blob` sent by `send_realtime_input`. + + The main use-cases for `send_client_content` over `send_realtime_input` are: + + - Prefilling a conversation context (including sending anything that can't + be represented as a realtime message), before starting a realtime + conversation. + - Conducting a non-realtime conversation, similar to `client.chat`, using + the live api. + + Caution: Interleaving `send_client_content` and `send_realtime_input` + in the same conversation is not recommended and can lead to unexpected + results. + + Args: + turns: A `Content` object or list of `Content` objects (or equivalent + dicts). + turn_complete: if true (the default) the model will reply immediately. If + false, the model will wait for you to send additional client_content, + and will not return until you send `turn_complete=True`. + + Example: + + .. code-block:: python + + import google.genai + from google.genai import types + import os + + if os.environ.get('GOOGLE_GENAI_USE_VERTEXAI'): + MODEL_NAME = 'gemini-2.0-flash-live-preview-04-09' + else: + MODEL_NAME = 'gemini-live-2.5-flash-preview'; + + client = genai.Client() + async with client.aio.live.connect( + model=MODEL_NAME, + config={"response_modalities": ["TEXT"]} + ) as session: + await session.send_client_content( + turns=types.Content( + role='user', + parts=[types.Part(text="Hello world!")])) + async for msg in session.receive(): + if msg.text: + print(msg.text) + """ + client_content = t.t_client_content(turns, turn_complete).model_dump( + mode='json', exclude_none=True + ) + + if self._api_client.vertexai: + client_content_dict = _common.convert_to_dict( + client_content, convert_keys=True + ) + else: + client_content_dict = live_converters._LiveClientContent_to_mldev( + from_object=client_content + ) + + await self._ws.send(json.dumps({'client_content': client_content_dict})) + + async def send_realtime_input( + self, + *, + media: Optional[types.BlobImageUnionDict] = None, + audio: Optional[types.BlobOrDict] = None, + audio_stream_end: Optional[bool] = None, + video: Optional[types.BlobImageUnionDict] = None, + text: Optional[str] = None, + activity_start: Optional[types.ActivityStartOrDict] = None, + activity_end: Optional[types.ActivityEndOrDict] = None, + ) -> None: + """Send realtime input to the model, only send one argument per call. + + Use `send_realtime_input` for realtime audio chunks and video + frames(images). + + With `send_realtime_input` the api will respond to audio automatically + based on voice activity detection (VAD). + + `send_realtime_input` is optimized for responsivness at the expense of + deterministic ordering. Audio and video tokens are added to the + context when they become available. + + Args: + media: A `Blob`-like object, the realtime media to send. + + Example: + + .. code-block:: python + + from pathlib import Path + + from google import genai + from google.genai import types + + import PIL.Image + + import os + + if os.environ.get('GOOGLE_GENAI_USE_VERTEXAI'): + MODEL_NAME = 'gemini-2.0-flash-live-preview-04-09' + else: + MODEL_NAME = 'gemini-live-2.5-flash-preview'; + + + client = genai.Client() + + async with client.aio.live.connect( + model=MODEL_NAME, + config={"response_modalities": ["TEXT"]}, + ) as session: + await session.send_realtime_input( + media=PIL.Image.open('image.jpg')) + + audio_bytes = Path('audio.pcm').read_bytes() + await session.send_realtime_input( + media=types.Blob(data=audio_bytes, mime_type='audio/pcm;rate=16000')) + + async for msg in session.receive(): + if msg.text is not None: + print(f'{msg.text}') + """ + kwargs: _common.StringDict = {} + if media is not None: + kwargs['media'] = media + if audio is not None: + kwargs['audio'] = audio + if audio_stream_end is not None: + kwargs['audio_stream_end'] = audio_stream_end + if video is not None: + kwargs['video'] = video + if text is not None: + kwargs['text'] = text + if activity_start is not None: + kwargs['activity_start'] = activity_start + if activity_end is not None: + kwargs['activity_end'] = activity_end + + if len(kwargs) != 1: + raise ValueError( + f'Only one argument can be set, got {len(kwargs)}:' + f' {list(kwargs.keys())}' + ) + realtime_input = types.LiveSendRealtimeInputParameters.model_validate( + kwargs + ) + + if self._api_client.vertexai: + realtime_input_dict = ( + live_converters._LiveSendRealtimeInputParameters_to_vertex( + from_object=realtime_input + ) + ) + else: + realtime_input_dict = ( + live_converters._LiveSendRealtimeInputParameters_to_mldev( + from_object=realtime_input + ) + ) + realtime_input_dict = _common.convert_to_dict(realtime_input_dict) + realtime_input_dict = _common.encode_unserializable_types( + realtime_input_dict + ) + await self._ws.send(json.dumps({'realtime_input': realtime_input_dict})) + + async def send_tool_response( + self, + *, + function_responses: Union[ + types.FunctionResponseOrDict, + Sequence[types.FunctionResponseOrDict], + ], + ) -> None: + """Send a tool response to the session. + + Use `send_tool_response` to reply to `LiveServerToolCall` messages + from the server. + + To set the available tools, use the `config.tools` argument + when you connect to the session (`client.live.connect`). + + Args: + function_responses: A `FunctionResponse`-like object or list of + `FunctionResponse`-like objects. + + Example: + + .. code-block:: python + + from google import genai + from google.genai import types + + import os + + if os.environ.get('GOOGLE_GENAI_USE_VERTEXAI'): + MODEL_NAME = 'gemini-2.0-flash-live-preview-04-09' + else: + MODEL_NAME = 'gemini-live-2.5-flash-preview'; + + client = genai.Client() + + tools = [{'function_declarations': [{'name': 'turn_on_the_lights'}]}] + config = { + "tools": tools, + "response_modalities": ['TEXT'] + } + + async with client.aio.live.connect( + model='models/gemini-live-2.5-flash-preview', + config=config + ) as session: + prompt = "Turn on the lights please" + await session.send_client_content( + turns={"parts": [{'text': prompt}]} + ) + + async for chunk in session.receive(): + if chunk.server_content: + if chunk.text is not None: + print(chunk.text) + elif chunk.tool_call: + print(chunk.tool_call) + print('_'*80) + function_response=types.FunctionResponse( + name='turn_on_the_lights', + response={'result': 'ok'}, + id=chunk.tool_call.function_calls[0].id, + ) + print(function_response) + await session.send_tool_response( + function_responses=function_response + ) + + print('_'*80) + """ + tool_response = t.t_tool_response(function_responses) + if self._api_client.vertexai: + tool_response_dict = _common.convert_to_dict( + tool_response, convert_keys=True + ) + else: + tool_response_dict = _common.convert_to_dict( + tool_response, convert_keys=True + ) + for response in tool_response_dict.get('functionResponses', []): + if response.get('id') is None: + raise ValueError(_FUNCTION_RESPONSE_REQUIRES_ID) + + await self._ws.send(json.dumps({'tool_response': tool_response_dict})) + + async def receive(self) -> AsyncIterator[types.LiveServerMessage]: + """Receive model responses from the server. + + The method will yield the model responses from the server. The returned + responses will represent a complete model turn. When the returned message + is function call, user must call `send` with the function response to + continue the turn. + + Yields: + The model responses from the server. + + Example usage: + + .. code-block:: python + + client = genai.Client(api_key=API_KEY) + + async with client.aio.live.connect(model='...') as session: + await session.send(input='Hello world!', end_of_turn=True) + async for message in session.receive(): + print(message) + """ + # TODO(b/365983264) Handle intermittent issues for the user. + while result := await self._receive(): + if result.server_content and result.server_content.turn_complete: + yield result + break + yield result + + async def start_stream( + self, *, stream: AsyncIterator[bytes], mime_type: str + ) -> AsyncIterator[types.LiveServerMessage]: + """[Deprecated] Start a live session from a data stream. + + > **Warning**: This method is deprecated and will be removed in a future + version (not before Q2 2025). Please use one of the more specific methods: + `send_client_content`, `send_realtime_input`, or `send_tool_response` + instead. + + The interaction terminates when the input stream is complete. + This method will start two async tasks. One task will be used to send the + input stream to the model and the other task will be used to receive the + responses from the model. + + Args: + stream: An iterator that yields the model response. + mime_type: The MIME type of the data in the stream. + + Yields: + The audio bytes received from the model and server response messages. + + Example usage: + + .. code-block:: python + + client = genai.Client(api_key=API_KEY) + config = {'response_modalities': ['AUDIO']} + async def audio_stream(): + stream = read_audio() + for data in stream: + yield data + async with client.aio.live.connect(model='...', config=config) as session: + for audio in session.start_stream(stream = audio_stream(), + mime_type = 'audio/pcm'): + play_audio_chunk(audio.data) + """ + warnings.warn( + 'Setting `AsyncSession.start_stream` is deprecated, ' + 'and will be removed in a future release (not before Q3 2025). ' + 'Please use the `receive`, and `send_realtime_input`, methods instead.', + DeprecationWarning, + stacklevel=4, + ) + stop_event = asyncio.Event() + # Start the send loop. When stream is complete stop_event is set. + asyncio.create_task(self._send_loop(stream, mime_type, stop_event)) + recv_task = None + while not stop_event.is_set(): + try: + recv_task = asyncio.create_task(self._receive()) + await asyncio.wait( + [ + recv_task, + asyncio.create_task(stop_event.wait()), + ], + return_when=asyncio.FIRST_COMPLETED, + ) + if recv_task.done(): + yield recv_task.result() + # Give a chance for the send loop to process requests. + await asyncio.sleep(10**-12) + except ConnectionClosed: + break + if recv_task is not None and not recv_task.done(): + recv_task.cancel() + # Wait for the task to finish (cancelled or not) + try: + await recv_task + except asyncio.CancelledError: + pass + + async def _receive(self) -> types.LiveServerMessage: + parameter_model = types.LiveServerMessage() + try: + raw_response = await self._ws.recv(decode=False) + except TypeError: + raw_response = await self._ws.recv() # type: ignore[assignment] + except ConnectionClosed as e: + if e.rcvd: + code = e.rcvd.code + reason = e.rcvd.reason + else: + code = 1006 + reason = websockets.frames.CLOSE_CODE_EXPLANATIONS.get(code, 'Abnormal closure.') + errors.APIError.raise_error(code, reason, None) + if raw_response: + try: + response = json.loads(raw_response) + except json.decoder.JSONDecodeError: + raise ValueError(f'Failed to parse response: {raw_response!r}') + else: + response = {} + + if self._api_client.vertexai: + response_dict = live_converters._LiveServerMessage_from_vertex(response) + else: + response_dict = live_converters._LiveServerMessage_from_mldev(response) + + if not response_dict and response: + # Error handling. + errors.APIError.raise_error(response.get('code'), response, None) + return types.LiveServerMessage._from_response( + response=response_dict, kwargs=parameter_model.model_dump() + ) + + async def _send_loop( + self, + data_stream: AsyncIterator[bytes], + mime_type: str, + stop_event: asyncio.Event, + ) -> None: + async for data in data_stream: + model_input = types.LiveClientRealtimeInput( + media_chunks=[types.Blob(data=data, mime_type=mime_type)] + ) + await self.send(input=model_input) + # Give a chance for the receive loop to process responses. + await asyncio.sleep(10**-12) + # Give a chance for the receiver to process the last response. + stop_event.set() + + def _parse_client_message( + self, + input: Optional[ + Union[ + types.ContentListUnion, + types.ContentListUnionDict, + types.LiveClientContentOrDict, + types.LiveClientRealtimeInputOrDict, + types.LiveClientToolResponseOrDict, + types.FunctionResponseOrDict, + Sequence[types.FunctionResponseOrDict], + ] + ] = None, + end_of_turn: Optional[bool] = False, + ) -> types.LiveClientMessageDict: + + formatted_input: Any = input + + if not input: + logging.info('No input provided. Assume it is the end of turn.') + return {'client_content': {'turn_complete': True}} + if isinstance(input, str): + formatted_input = [input] + elif isinstance(input, dict) and 'data' in input: + try: + blob_input = types.Blob(**input) + except pydantic.ValidationError: + raise ValueError( + f'Unsupported input type "{type(input)}" or input content "{input}"' + ) + if isinstance(blob_input, types.Blob) and isinstance( + blob_input.data, bytes + ): + formatted_input = [ + blob_input.model_dump(mode='json', exclude_none=True) + ] + elif isinstance(input, types.Blob): + formatted_input = [input] + elif isinstance(input, dict) and 'name' in input and 'response' in input: + # ToolResponse.FunctionResponse + if not (self._api_client.vertexai) and 'id' not in input: + raise ValueError(_FUNCTION_RESPONSE_REQUIRES_ID) + formatted_input = [input] + + if isinstance(formatted_input, Sequence) and any( + isinstance(c, dict) and 'name' in c and 'response' in c + for c in formatted_input + ): + # ToolResponse.FunctionResponse + function_responses_input = [] + for item in formatted_input: + if isinstance(item, dict): + try: + function_response_input = types.FunctionResponse(**item) + except pydantic.ValidationError: + raise ValueError( + f'Unsupported input type "{type(input)}" or input content' + f' "{input}"' + ) + if ( + function_response_input.id is None + and not self._api_client.vertexai + ): + raise ValueError(_FUNCTION_RESPONSE_REQUIRES_ID) + else: + function_response_dict = function_response_input.model_dump( + exclude_none=True, mode='json' + ) + function_response_typeddict = types.FunctionResponseDict( + name=function_response_dict.get('name'), + response=function_response_dict.get('response'), + ) + if function_response_dict.get('id'): + function_response_typeddict['id'] = function_response_dict.get( + 'id' + ) + function_responses_input.append(function_response_typeddict) + client_message = types.LiveClientMessageDict( + tool_response=types.LiveClientToolResponseDict( + function_responses=function_responses_input + ) + ) + elif isinstance(formatted_input, Sequence) and any( + isinstance(c, str) for c in formatted_input + ): + to_object: _common.StringDict = {} + content_input_parts: list[types.PartUnion] = [] + for item in formatted_input: + if isinstance(item, get_args(types.PartUnion)): + content_input_parts.append(item) + if self._api_client.vertexai: + contents = [ + _common.convert_to_dict(item, convert_keys=True) + for item in t.t_contents(content_input_parts) + ] + else: + contents = [ + _Content_to_mldev(item, to_object) + for item in t.t_contents(content_input_parts) + ] + + content_dict_list: list[types.ContentDict] = [] + for item in contents: + try: + content_input = types.Content(**item) + except pydantic.ValidationError: + raise ValueError( + f'Unsupported input type "{type(input)}" or input content' + f' "{input}"' + ) + content_dict_list.append( + types.ContentDict( + parts=content_input.model_dump(exclude_none=True, mode='json')[ + 'parts' + ], + role=content_input.role, + ) + ) + + client_message = types.LiveClientMessageDict( + client_content=types.LiveClientContentDict( + turns=content_dict_list, turn_complete=end_of_turn + ) + ) + elif isinstance(formatted_input, Sequence): + if any((isinstance(b, dict) and 'data' in b) for b in formatted_input): + pass + elif any(isinstance(b, types.Blob) for b in formatted_input): + formatted_input = [ + b.model_dump(exclude_none=True, mode='json') + for b in formatted_input + ] + else: + raise ValueError( + f'Unsupported input type "{type(input)}" or input content "{input}"' + ) + + client_message = types.LiveClientMessageDict( + realtime_input=types.LiveClientRealtimeInputDict( + media_chunks=formatted_input + ) + ) + + elif isinstance(formatted_input, dict): + if 'content' in formatted_input or 'turns' in formatted_input: + # TODO(b/365983264) Add validation checks for content_update input_dict. + if 'turns' in formatted_input: + content_turns = formatted_input['turns'] + else: + content_turns = formatted_input['content'] + client_message = types.LiveClientMessageDict( + client_content=types.LiveClientContentDict( + turns=content_turns, + turn_complete=formatted_input.get('turn_complete'), + ) + ) + elif 'media_chunks' in formatted_input: + try: + realtime_input = types.LiveClientRealtimeInput(**formatted_input) + except pydantic.ValidationError: + raise ValueError( + f'Unsupported input type "{type(input)}" or input content' + f' "{input}"' + ) + client_message = types.LiveClientMessageDict( + realtime_input=types.LiveClientRealtimeInputDict( + media_chunks=realtime_input.model_dump( + exclude_none=True, mode='json' + )['media_chunks'] + ) + ) + elif 'function_responses' in formatted_input: + try: + tool_response_input = types.LiveClientToolResponse(**formatted_input) + except pydantic.ValidationError: + raise ValueError( + f'Unsupported input type "{type(input)}" or input content' + f' "{input}"' + ) + client_message = types.LiveClientMessageDict( + tool_response=types.LiveClientToolResponseDict( + function_responses=tool_response_input.model_dump( + exclude_none=True, mode='json' + )['function_responses'] + ) + ) + else: + raise ValueError( + f'Unsupported input type "{type(input)}" or input content "{input}"' + ) + elif isinstance(formatted_input, types.LiveClientRealtimeInput): + realtime_input_dict = formatted_input.model_dump( + exclude_none=True, mode='json' + ) + client_message = types.LiveClientMessageDict( + realtime_input=types.LiveClientRealtimeInputDict( + media_chunks=realtime_input_dict.get('media_chunks') + ) + ) + if ( + client_message['realtime_input'] is not None + and client_message['realtime_input']['media_chunks'] is not None + and isinstance( + client_message['realtime_input']['media_chunks'][0]['data'], bytes + ) + ): + formatted_media_chunks: list[types.BlobDict] = [] + for item in client_message['realtime_input']['media_chunks']: + if isinstance(item, dict): + try: + blob_input = types.Blob(**item) + except pydantic.ValidationError: + raise ValueError( + f'Unsupported input type "{type(input)}" or input content' + f' "{input}"' + ) + if ( + isinstance(blob_input, types.Blob) + and isinstance(blob_input.data, bytes) + and blob_input.data is not None + ): + formatted_media_chunks.append( + types.BlobDict( + data=base64.b64decode(blob_input.data), + mime_type=blob_input.mime_type, + ) + ) + + client_message['realtime_input'][ + 'media_chunks' + ] = formatted_media_chunks + + elif isinstance(formatted_input, types.LiveClientContent): + client_content_dict = formatted_input.model_dump( + exclude_none=True, mode='json' + ) + client_message = types.LiveClientMessageDict( + client_content=types.LiveClientContentDict( + turns=client_content_dict.get('turns'), + turn_complete=client_content_dict.get('turn_complete'), + ) + ) + elif isinstance(formatted_input, types.LiveClientToolResponse): + # ToolResponse.FunctionResponse + if ( + not (self._api_client.vertexai) + and formatted_input.function_responses is not None + and not (formatted_input.function_responses[0].id) + ): + raise ValueError(_FUNCTION_RESPONSE_REQUIRES_ID) + client_message = types.LiveClientMessageDict( + tool_response=types.LiveClientToolResponseDict( + function_responses=formatted_input.model_dump( + exclude_none=True, mode='json' + ).get('function_responses') + ) + ) + elif isinstance(formatted_input, types.FunctionResponse): + if not (self._api_client.vertexai) and not (formatted_input.id): + raise ValueError(_FUNCTION_RESPONSE_REQUIRES_ID) + function_response_dict = formatted_input.model_dump( + exclude_none=True, mode='json' + ) + function_response_typeddict = types.FunctionResponseDict( + name=function_response_dict.get('name'), + response=function_response_dict.get('response'), + ) + if function_response_dict.get('id'): + function_response_typeddict['id'] = function_response_dict.get('id') + client_message = types.LiveClientMessageDict( + tool_response=types.LiveClientToolResponseDict( + function_responses=[function_response_typeddict] + ) + ) + elif isinstance(formatted_input, Sequence) and isinstance( + formatted_input[0], types.FunctionResponse + ): + if not (self._api_client.vertexai) and not (formatted_input[0].id): + raise ValueError(_FUNCTION_RESPONSE_REQUIRES_ID) + function_response_list: list[types.FunctionResponseDict] = [] + for item in formatted_input: + function_response_dict = item.model_dump(exclude_none=True, mode='json') + function_response_typeddict = types.FunctionResponseDict( + name=function_response_dict.get('name'), + response=function_response_dict.get('response'), + ) + if function_response_dict.get('id'): + function_response_typeddict['id'] = function_response_dict.get('id') + function_response_list.append(function_response_typeddict) + client_message = types.LiveClientMessageDict( + tool_response=types.LiveClientToolResponseDict( + function_responses=function_response_list + ) + ) + + else: + raise ValueError( + f'Unsupported input type "{type(input)}" or input content "{input}"' + ) + + return client_message + + async def close(self) -> None: + # Close the websocket connection. + await self._ws.close() + + +class AsyncLive(_api_module.BaseModule): + """[Preview] AsyncLive.""" + + def __init__(self, api_client: BaseApiClient): + super().__init__(api_client) + self._music = AsyncLiveMusic(api_client) + + @property + def music(self) -> AsyncLiveMusic: + return self._music + + @contextlib.asynccontextmanager + async def connect( + self, + *, + model: str, + config: Optional[types.LiveConnectConfigOrDict] = None, + ) -> AsyncIterator[AsyncSession]: + """[Preview] Connect to the live server. + + Note: the live API is currently in preview. + + Usage: + + .. code-block:: python + + client = genai.Client(api_key=API_KEY) + config = {} + async with client.aio.live.connect(model='...', config=config) as session: + await session.send_client_content( + turns=types.Content( + role='user', + parts=[types.Part(text='hello!')] + ), + turn_complete=True + ) + async for message in session.receive(): + print(message) + + Args: + model: The model to use for the live session. + config: The configuration for the live session. + **kwargs: additional keyword arguments. + + Yields: + An AsyncSession object. + """ + # TODO(b/404946570): Support per request http options. + if isinstance(config, dict): + config = types.LiveConnectConfig(**config) + if config and config.http_options: + raise ValueError( + 'google.genai.client.aio.live.connect() does not support' + ' http_options at request-level in LiveConnectConfig yet. Please use' + ' the client-level http_options configuration instead.' + ) + + base_url = self._api_client._websocket_base_url() + if isinstance(base_url, bytes): + base_url = base_url.decode('utf-8') + transformed_model = t.t_model(self._api_client, model) # type: ignore + + parameter_model = await _t_live_connect_config(self._api_client, config) + + if self._api_client.api_key and not self._api_client.vertexai: + version = self._api_client._http_options.api_version + api_key = self._api_client.api_key + method = 'BidiGenerateContent' + original_headers = self._api_client._http_options.headers + headers = original_headers.copy() if original_headers is not None else {} + if api_key.startswith('auth_tokens/'): + warnings.warn( + message=( + "The SDK's ephemeral token support is experimental, and may" + ' change in future versions.' + ), + category=errors.ExperimentalWarning, + ) + method = 'BidiGenerateContentConstrained' + headers['Authorization'] = f'Token {api_key}' + if version != 'v1alpha': + warnings.warn( + message=( + "The SDK's ephemeral token support is in v1alpha only." + 'Please use client = genai.Client(api_key=token.name, ' + 'http_options=types.HttpOptions(api_version="v1alpha"))' + ' before session connection.' + ), + category=errors.ExperimentalWarning, + ) + uri = f'{base_url}/ws/google.ai.generativelanguage.{version}.GenerativeService.{method}' + + request_dict = _common.convert_to_dict( + live_converters._LiveConnectParameters_to_mldev( + api_client=self._api_client, + from_object=types.LiveConnectParameters( + model=transformed_model, + config=parameter_model, + ).model_dump(exclude_none=True), + ) + ) + + del request_dict['config'] + request_dict = _common.encode_unserializable_types(request_dict) + setv(request_dict, ['setup', 'model'], transformed_model) + + request = json.dumps(request_dict) + elif self._api_client.api_key and self._api_client.vertexai: + # Headers already contains api key for express mode. + api_key = self._api_client.api_key + version = self._api_client._http_options.api_version + uri = f'{base_url}/ws/google.cloud.aiplatform.{version}.LlmBidiService/BidiGenerateContent' + original_headers = self._api_client._http_options.headers + headers = original_headers.copy() if original_headers is not None else {} + + request_dict = _common.convert_to_dict( + live_converters._LiveConnectParameters_to_vertex( + api_client=self._api_client, + from_object=types.LiveConnectParameters( + model=transformed_model, + config=parameter_model, + ).model_dump(exclude_none=True), + ) + ) + del request_dict['config'] + request_dict = _common.encode_unserializable_types(request_dict) + setv(request_dict, ['setup', 'model'], transformed_model) + + request = json.dumps(request_dict) + else: + version = self._api_client._http_options.api_version + has_sufficient_auth = ( + self._api_client.project and self._api_client.location + ) + if self._api_client.custom_base_url and not has_sufficient_auth: + # API gateway proxy can use the auth in custom headers, not url. + # Enable custom url if auth is not sufficient. + uri = self._api_client.custom_base_url + # Keep the model as is. + transformed_model = model + # Do not get credentials for custom url. + original_headers = self._api_client._http_options.headers + headers = ( + original_headers.copy() if original_headers is not None else {} + ) + + else: + uri = f'{base_url}/ws/google.cloud.aiplatform.{version}.LlmBidiService/BidiGenerateContent' + + if not self._api_client._credentials: + # Get bearer token through Application Default Credentials. + creds, _ = google.auth.default( # type: ignore + scopes=['https://www.googleapis.com/auth/cloud-platform'] + ) + else: + creds = self._api_client._credentials + # creds.valid is False, and creds.token is None + # Need to refresh credentials to populate those + if not (creds.token and creds.valid): + if requests is None: + raise ValueError('The requests module is required to refresh google-auth credentials. Please install with `pip install google-auth[requests]`') + auth_req = requests.Request() # type: ignore + creds.refresh(auth_req) # type: ignore[no-untyped-call] + bearer_token = creds.token + + original_headers = self._api_client._http_options.headers + headers = ( + original_headers.copy() if original_headers is not None else {} + ) + if not headers.get('Authorization'): + headers['Authorization'] = f'Bearer {bearer_token}' + + location = self._api_client.location + project = self._api_client.project + if transformed_model.startswith('publishers/') and project and location: + transformed_model = ( + f'projects/{project}/locations/{location}/' + transformed_model + ) + request_dict = _common.convert_to_dict( + live_converters._LiveConnectParameters_to_vertex( + api_client=self._api_client, + from_object=types.LiveConnectParameters( + model=transformed_model, + config=parameter_model, + ).model_dump(exclude_none=True), + ) + ) + del request_dict['config'] + request_dict = _common.encode_unserializable_types(request_dict) + if ( + getv( + request_dict, ['setup', 'generationConfig', 'responseModalities'] + ) + is None + ): + setv( + request_dict, + ['setup', 'generationConfig', 'responseModalities'], + ['AUDIO'], + ) + + request = json.dumps(request_dict) + + if parameter_model.tools and _mcp_utils.has_mcp_tool_usage( + parameter_model.tools + ): + if headers is None: + headers = {} + _mcp_utils.set_mcp_usage_header(headers) + + async with ws_connect( + uri, additional_headers=headers, **self._api_client._websocket_ssl_ctx + ) as ws: + await ws.send(request) + try: + # websockets 14.0+ + raw_response = await ws.recv(decode=False) + except TypeError: + raw_response = await ws.recv() # type: ignore[assignment] + except ConnectionClosed as e: + if e.rcvd: + code = e.rcvd.code + reason = e.rcvd.reason + else: + code = 1006 + reason = 'Abnormal closure.' + errors.APIError.raise_error(code, reason, None) + if raw_response: + try: + response = json.loads(raw_response) + except json.decoder.JSONDecodeError: + raise ValueError(f'Failed to parse response: {raw_response!r}') + else: + response = {} + + if self._api_client.vertexai: + response_dict = live_converters._LiveServerMessage_from_vertex(response) + else: + response_dict = response + + setup_response = types.LiveServerMessage._from_response( + response=response_dict, kwargs=parameter_model.model_dump() + ) + if setup_response.setup_complete: + session_id = setup_response.setup_complete.session_id + setup_complete = setup_response.setup_complete + else: + session_id = None + setup_complete = None + yield AsyncSession( + api_client=self._api_client, + websocket=ws, + session_id=session_id, + setup_complete=setup_complete, + ) + + +async def _t_live_connect_config( + api_client: BaseApiClient, + config: Optional[types.LiveConnectConfigOrDict], +) -> types.LiveConnectConfig: + # Ensure the config is a LiveConnectConfig. + if config is None: + parameter_model = types.LiveConnectConfig() + elif isinstance(config, dict): + if getv(config, ['system_instruction']) is not None: + converted_system_instruction = t.t_content( + getv(config, ['system_instruction']) + ) + else: + converted_system_instruction = None + parameter_model = types.LiveConnectConfig(**config) + parameter_model.system_instruction = converted_system_instruction + else: + if config.system_instruction is None: + system_instruction = None + else: + system_instruction = t.t_content(getv(config, ['system_instruction'])) + parameter_model = config + parameter_model.system_instruction = system_instruction + + # Create a copy of the config model with the tools field cleared as they will + # be replaced with the MCP tools converted to GenAI tools. + parameter_model_copy = parameter_model.model_copy(update={'tools': None}) + if parameter_model.tools: + parameter_model_copy.tools = [] + for tool in parameter_model.tools: + if McpClientSession is not None and isinstance(tool, McpClientSession): + mcp_to_genai_tool_adapter = McpToGenAiToolAdapter( + tool, await tool.list_tools() + ) + # Extend the config with the MCP session tools converted to GenAI tools. + parameter_model_copy.tools.extend(mcp_to_genai_tool_adapter.tools) + elif McpTool is not None and isinstance(tool, McpTool): + parameter_model_copy.tools.append(mcp_to_gemini_tool(tool)) + else: + parameter_model_copy.tools.append(tool) + + if parameter_model_copy.generation_config is not None: + warnings.warn( + 'Setting `LiveConnectConfig.generation_config` is deprecated, ' + 'please set the fields on `LiveConnectConfig` directly. This will ' + 'become an error in a future version (not before Q3 2025)', + DeprecationWarning, + stacklevel=4, + ) + + return parameter_model_copy diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/live_music.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/live_music.py new file mode 100644 index 0000000000000000000000000000000000000000..8730e08f99e714362c73868aac27fa115db7a393 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/live_music.py @@ -0,0 +1,210 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +"""[Experimental] Live Music API client.""" + +import contextlib +import json +import logging +from typing import AsyncIterator +import websockets + +from . import _api_module +from . import _common +from . import _live_converters as live_converters +from . import _transformers as t +from . import errors +from . import types +from ._api_client import BaseApiClient +from ._common import set_value_by_path as setv + +ConnectionClosed = websockets.ConnectionClosed + +try: + from websockets.asyncio.client import ClientConnection + from websockets.asyncio.client import connect +except ModuleNotFoundError: + from websockets.client import ClientConnection # type: ignore + from websockets.client import connect # type: ignore + +logger = logging.getLogger('google_genai.live_music') + + +class AsyncMusicSession: + """[Experimental] AsyncMusicSession.""" + + def __init__(self, api_client: BaseApiClient, websocket: ClientConnection): + self._api_client = api_client + self._ws = websocket + + async def set_weighted_prompts( + self, prompts: list[types.WeightedPrompt] + ) -> None: + if self._api_client.vertexai: + raise NotImplementedError( + 'Live music generation is not supported in Vertex AI.' + ) + else: + client_content_dict = { + 'weightedPrompts': [ + _common.convert_to_dict(prompt, convert_keys=True) + for prompt in prompts + ] + } + + await self._ws.send(json.dumps({'clientContent': client_content_dict})) + + async def set_music_generation_config( + self, config: types.LiveMusicGenerationConfig + ) -> None: + if self._api_client.vertexai: + raise NotImplementedError( + 'Live music generation is not supported in Vertex AI.' + ) + else: + config_dict = _common.convert_to_dict(config, convert_keys=True) + await self._ws.send(json.dumps({'musicGenerationConfig': config_dict})) + + async def _send_control_signal( + self, playback_control: types.LiveMusicPlaybackControl + ) -> None: + if self._api_client.vertexai: + raise NotImplementedError( + 'Live music generation is not supported in Vertex AI.' + ) + else: + playback_control_dict = {'playbackControl': playback_control.value} + await self._ws.send(json.dumps(playback_control_dict)) + + async def play(self) -> None: + """Sends playback signal to start the music stream.""" + return await self._send_control_signal(types.LiveMusicPlaybackControl.PLAY) + + async def pause(self) -> None: + """Sends a playback signal to pause the music stream.""" + return await self._send_control_signal(types.LiveMusicPlaybackControl.PAUSE) + + async def stop(self) -> None: + """Sends a playback signal to stop the music stream. + + Resets the music generation context while retaining the current config. + """ + return await self._send_control_signal(types.LiveMusicPlaybackControl.STOP) + + async def reset_context(self) -> None: + """Reset the context (prompts retained) without stopping the music generation.""" + return await self._send_control_signal( + types.LiveMusicPlaybackControl.RESET_CONTEXT + ) + + async def receive(self) -> AsyncIterator[types.LiveMusicServerMessage]: + """Receive model responses from the server. + + Yields: + The audio chunks from the server. + """ + # TODO(b/365983264) Handle intermittent issues for the user. + while result := await self._receive(): + yield result + + async def _receive(self) -> types.LiveMusicServerMessage: + parameter_model = types.LiveMusicServerMessage() + try: + raw_response = await self._ws.recv(decode=False) + except TypeError: + raw_response = await self._ws.recv() # type: ignore[assignment] + except ConnectionClosed as e: + if e.rcvd: + code = e.rcvd.code + reason = e.rcvd.reason + else: + code = 1006 + reason = websockets.frames.CLOSE_CODE_EXPLANATIONS.get(code, 'Abnormal closure.') + errors.APIError.raise_error(code, reason, None) + if raw_response: + try: + response = json.loads(raw_response) + except json.decoder.JSONDecodeError: + raise ValueError(f'Failed to parse response: {raw_response!r}') + else: + response = {} + + if self._api_client.vertexai: + raise NotImplementedError('Live music generation is not supported in Vertex AI.') + else: + response_dict = response + if not response_dict and response: + # Error handling. + errors.APIError.raise_error(response.get('code'), response, None) + return types.LiveMusicServerMessage._from_response( + response=response_dict, kwargs=parameter_model.model_dump() + ) + + async def close(self) -> None: + """Closes the bi-directional stream and terminates the session.""" + await self._ws.close() + + +class AsyncLiveMusic(_api_module.BaseModule): + """[Experimental] Live music module. + + Live music can be accessed via `client.aio.live.music`. + """ + + @_common.experimental_warning( + 'Realtime music generation is experimental and may change in future versions.' + ) + @contextlib.asynccontextmanager + async def connect(self, *, model: str) -> AsyncIterator[AsyncMusicSession]: + """[Experimental] Connect to the live music server.""" + base_url = self._api_client._websocket_base_url() + if isinstance(base_url, bytes): + base_url = base_url.decode('utf-8') + transformed_model = t.t_model(self._api_client, model) + + if self._api_client.api_key: + api_key = self._api_client.api_key + version = self._api_client._http_options.api_version + uri = f'{base_url}/ws/google.ai.generativelanguage.{version}.GenerativeService.BidiGenerateMusic?key={api_key}' + headers = self._api_client._http_options.headers + + # Only mldev supported + request_dict = _common.convert_to_dict( + live_converters._LiveMusicConnectParameters_to_mldev( + from_object=types.LiveMusicConnectParameters( + model=transformed_model, + ).model_dump(exclude_none=True) + ) + ) + + setv(request_dict, ['setup', 'model'], transformed_model) + + request = json.dumps(request_dict) + else: + raise NotImplementedError('Live music generation is not supported in Vertex AI.') + + try: + async with connect(uri, additional_headers=headers) as ws: + await ws.send(request) + logger.info(await ws.recv(decode=False)) + + yield AsyncMusicSession(api_client=self._api_client, websocket=ws) + except TypeError: + # Try with the older websockets API + async with connect(uri, extra_headers=headers) as ws: + await ws.send(request) + logger.info(await ws.recv()) + + yield AsyncMusicSession(api_client=self._api_client, websocket=ws) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/local_tokenizer.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/local_tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..5db6d69226469ca0ac61641325783254d03dbc41 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/local_tokenizer.py @@ -0,0 +1,395 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +"""[Experimental] Text Only Local Tokenizer.""" + +import logging +from typing import Any, Iterable +from typing import Optional, Union + +from sentencepiece import sentencepiece_model_pb2 + +from . import _common +from . import _local_tokenizer_loader as loader +from . import _transformers as t +from . import types + +logger = logging.getLogger("google_genai.local_tokenizer") + +__all__ = [ + "_parse_hex_byte", + "_token_str_to_bytes", + "LocalTokenizer", + "_TextsAccumulator", +] + + +class _TextsAccumulator: + """Accumulates countable texts from `Content` and `Tool` objects. + + This class is responsible for traversing complex `Content` and `Tool` + objects and extracting all the text content that should be included when + calculating token counts. + + A key feature of this class is its ability to detect unsupported fields in + `Content` objects. If a user provides a `Content` object with fields that + this local tokenizer doesn't recognize (e.g., new fields added in a future + API update), this class will log a warning. + + The detection mechanism for `Content` objects works by recursively building + a "counted" version of the input object. This "counted" object only + contains the data that was successfully processed and added to the text + list for tokenization. After traversing the input, the original `Content` + object is compared to the "counted" object. If they don't match, it + signifies the presence of unsupported fields, and a warning is logged. + """ + + def __init__(self) -> None: + self._texts: list[str] = [] + + def get_texts(self) -> Iterable[str]: + return self._texts + + def add_contents(self, contents: Iterable[types.Content]) -> None: + for content in contents: + self.add_content(content) + + def add_content(self, content: types.Content) -> None: + counted_content = types.Content(parts=[], role=content.role) + if content.parts: + for part in content.parts: + assert counted_content.parts is not None + counted_part = types.Part() + if part.file_data is not None or part.inline_data is not None: + raise ValueError( + "LocalTokenizers do not support non-text content types." + ) + if part.video_metadata is not None: + counted_part.video_metadata = part.video_metadata + if part.function_call is not None: + self.add_function_call(part.function_call) + counted_part.function_call = part.function_call + if part.function_response is not None: + self.add_function_response(part.function_response) + counted_part.function_response = part.function_response + if part.text is not None: + counted_part.text = part.text + self._texts.append(part.text) + counted_content.parts.append(counted_part) + + if content.model_dump(exclude_none=True) != counted_content.model_dump( + exclude_none=True + ): + logger.warning( + "Content contains unsupported types for token counting. Supported" + f" fields {counted_content}. Got {content}." + ) + + def add_function_call(self, function_call: types.FunctionCall) -> None: + """Processes a function call and adds relevant text to the accumulator. + + Args: + function_call: The function call to process. + """ + if function_call.name: + self._texts.append(function_call.name) + counted_function_call = types.FunctionCall(name=function_call.name) + if function_call.args: + counted_args = self._dict_traverse(function_call.args) + counted_function_call.args = counted_args + + def add_tool(self, tool: types.Tool) -> types.Tool: + counted_tool = types.Tool(function_declarations=[]) + if tool.function_declarations: + for function_declaration in tool.function_declarations: + counted_function_declaration = self._function_declaration_traverse( + function_declaration + ) + if counted_tool.function_declarations is None: + counted_tool.function_declarations = [] + counted_tool.function_declarations.append(counted_function_declaration) + + return counted_tool + + def add_tools(self, tools: Iterable[types.Tool]) -> None: + for tool in tools: + self.add_tool(tool) + + def add_function_responses( + self, function_responses: Iterable[types.FunctionResponse] + ) -> None: + for function_response in function_responses: + self.add_function_response(function_response) + + def add_function_response( + self, function_response: types.FunctionResponse + ) -> None: + counted_function_response = types.FunctionResponse() + if function_response.name: + self._texts.append(function_response.name) + counted_function_response.name = function_response.name + if function_response.response: + counted_response = self._dict_traverse(function_response.response) + counted_function_response.response = counted_response + + def _function_declaration_traverse( + self, function_declaration: types.FunctionDeclaration + ) -> types.FunctionDeclaration: + counted_function_declaration = types.FunctionDeclaration() + if function_declaration.name: + self._texts.append(function_declaration.name) + counted_function_declaration.name = function_declaration.name + if function_declaration.description: + self._texts.append(function_declaration.description) + counted_function_declaration.description = ( + function_declaration.description + ) + if function_declaration.parameters: + counted_parameters = self.add_schema(function_declaration.parameters) + counted_function_declaration.parameters = counted_parameters + if function_declaration.response: + counted_response = self.add_schema(function_declaration.response) + counted_function_declaration.response = counted_response + return counted_function_declaration + + def add_schema(self, schema: types.Schema) -> types.Schema: + """Processes a schema and adds relevant text to the accumulator. + + Args: + schema: The schema to process. + + Returns: + The new schema object with only countable fields. + """ + counted_schema = types.Schema() + if schema.type: + counted_schema.type = schema.type + if schema.title: + counted_schema.title = schema.title + if schema.default is not None: + counted_schema.default = schema.default + if schema.format: + self._texts.append(schema.format) + counted_schema.format = schema.format + if schema.description: + self._texts.append(schema.description) + counted_schema.description = schema.description + if schema.enum: + self._texts.extend(schema.enum) + counted_schema.enum = schema.enum + if schema.required: + self._texts.extend(schema.required) + counted_schema.required = schema.required + if schema.property_ordering: + counted_schema.property_ordering = schema.property_ordering + if schema.items: + counted_schema_items = self.add_schema(schema.items) + counted_schema.items = counted_schema_items + if schema.properties: + d = {} + for key, value in schema.properties.items(): + self._texts.append(key) + counted_value = self.add_schema(value) + d[key] = counted_value + counted_schema.properties = d + if schema.example: + counted_schema_example = self._any_traverse(schema.example) + counted_schema.example = counted_schema_example + return counted_schema + + def _dict_traverse(self, d: dict[str, Any]) -> dict[str, Any]: + """Processes a dict and adds relevant text to the accumulator. + + Args: + d: The dict to process. + + Returns: + The new dict object with only countable fields. + """ + counted_dict = {} + self._texts.extend(list(d.keys())) + for key, val in d.items(): + counted_dict[key] = self._any_traverse(val) + return counted_dict + + def _any_traverse(self, value: Any) -> Any: + """Processes a value and adds relevant text to the accumulator. + + Args: + value: The value to process. + + Returns: + The new value with only countable fields. + """ + if isinstance(value, str): + self._texts.append(value) + return value + elif isinstance(value, dict): + return self._dict_traverse(value) + elif isinstance(value, list): + return [self._any_traverse(item) for item in value] + else: + return value + + +def _token_str_to_bytes( + token: str, type: sentencepiece_model_pb2.ModelProto.SentencePiece.Type +) -> bytes: + if type == sentencepiece_model_pb2.ModelProto.SentencePiece.Type.BYTE: + return _parse_hex_byte(token).to_bytes(length=1, byteorder="big") + else: + return token.replace("▁", " ").encode("utf-8") + + +def _parse_hex_byte(token: str) -> int: + """Parses a hex byte string of the form '<0xXX>' and returns the integer value. + + Raises ValueError if the input is malformed or the byte value is invalid. + """ + + if len(token) != 6: + raise ValueError(f"Invalid byte length: {token}") + if not token.startswith("<0x") or not token.endswith(">"): + raise ValueError(f"Invalid byte format: {token}") + + try: + val = int(token[3:5], 16) # Parse the hex part directly + except ValueError: + raise ValueError(f"Invalid hex value: {token}") + + if val >= 256: + raise ValueError(f"Byte value out of range: {token}") + + return val + + +class LocalTokenizer: + """[Experimental] Text Only Local Tokenizer. + + This class provides a local tokenizer for text only token counting. + + LIMITATIONS: + - Only supports text based tokenization and no multimodal tokenization. + - Forward compatibility depends on the open-source tokenizer models for future + Gemini versions. + - For token counting of tools and response schemas, the `LocalTokenizer` only + supports `types.Tool` and `types.Schema` objects. Python functions or Pydantic + models cannot be passed directly. + """ + + def __init__(self, model_name: str): + self._tokenizer_name = loader.get_tokenizer_name(model_name) + self._model_proto = loader.load_model_proto(self._tokenizer_name) + self._tokenizer = loader.get_sentencepiece(self._tokenizer_name) + + @_common.experimental_warning( + "The SDK's local tokenizer implementation is experimental and may change" + " in the future. It only supports text based tokenization." + ) + def count_tokens( + self, + contents: Union[types.ContentListUnion, types.ContentListUnionDict], + *, + config: Optional[types.CountTokensConfigOrDict] = None, + ) -> types.CountTokensResult: + """Counts the number of tokens in a given text. + + Args: + contents: The contents to tokenize. + config: The configuration for counting tokens. + + Returns: + A `CountTokensResult` containing the total number of tokens. + + Usage: + + .. code-block:: python + + from google import genai + tokenizer = genai.LocalTokenizer(model_name='gemini-2.0-flash-001') + result = tokenizer.count_tokens("What is your name?") + print(result) + # total_tokens=5 + """ + processed_contents = t.t_contents(contents) + text_accumulator = _TextsAccumulator() + config = types.CountTokensConfig.model_validate(config or {}) + text_accumulator.add_contents(processed_contents) + if config.tools: + text_accumulator.add_tools(config.tools) + if config.generation_config and config.generation_config.response_schema: + text_accumulator.add_schema(config.generation_config.response_schema) + if config.system_instruction: + text_accumulator.add_contents(t.t_contents([config.system_instruction])) + tokens_list = self._tokenizer.encode(list(text_accumulator.get_texts())) + return types.CountTokensResult( + total_tokens=sum(len(tokens) for tokens in tokens_list) + ) + + @_common.experimental_warning( + "The SDK's local tokenizer implementation is experimental and may change" + " in the future. It only supports text based tokenization." + ) + def compute_tokens( + self, + contents: Union[types.ContentListUnion, types.ContentListUnionDict], + ) -> types.ComputeTokensResult: + """Computes the tokens ids and string pieces in the input. + + Args: + contents: The contents to tokenize. + + Returns: + A `ComputeTokensResult` containing the token information. + + Usage: + + .. code-block:: python + + from google import genai + tokenizer = genai.LocalTokenizer(model_name='gemini-2.0-flash-001') + result = tokenizer.compute_tokens("What is your name?") + print(result) + # tokens_info=[TokensInfo(token_ids=[279, 329, 1313, 2508, 13], tokens=[b' What', b' is', b' your', b' name', b'?'], role='user')] + """ + processed_contents = t.t_contents(contents) + text_accumulator = _TextsAccumulator() + for content in processed_contents: + text_accumulator.add_content(content) + tokens_protos = self._tokenizer.EncodeAsImmutableProto( + text_accumulator.get_texts() + ) + + roles = [] + for content in processed_contents: + if content.parts: + for _ in content.parts: + roles.append(content.role) + + token_infos = [] + for tokens_proto, role in zip(tokens_protos, roles): + token_infos.append( + types.TokensInfo( + token_ids=[piece.id for piece in tokens_proto.pieces], + tokens=[ + _token_str_to_bytes( + piece.piece, self._model_proto.pieces[piece.id].type + ) + for piece in tokens_proto.pieces + ], + role=role, + ) + ) + return types.ComputeTokensResult(tokens_info=token_infos) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/models.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/models.py new file mode 100644 index 0000000000000000000000000000000000000000..b05985cc924ba5e74ebf4b53d98859fe763ac580 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/models.py @@ -0,0 +1,9012 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# Code generated by the Google Gen AI SDK generator DO NOT EDIT. + +import json +import logging +from typing import Any, AsyncIterator, Awaitable, Iterator, Optional, Union +from urllib.parse import urlencode + +from . import _api_module +from . import _base_transformers as base_t +from . import _common +from . import _extra_utils +from . import _mcp_utils +from . import _transformers as t +from . import errors +from . import types +from ._api_client import BaseApiClient +from ._common import get_value_by_path as getv +from ._common import set_value_by_path as setv +from .pagers import AsyncPager, Pager + +logger = logging.getLogger('google_genai.models') + + +def _PersonGeneration_to_mldev_enum_validate(enum_value: Any) -> None: + if enum_value in set(['ALLOW_ALL']): + raise ValueError(f'{enum_value} enum value is not supported in Gemini API.') + + +def _SafetyFilterLevel_to_mldev_enum_validate(enum_value: Any) -> None: + if enum_value in set(['BLOCK_NONE']): + raise ValueError(f'{enum_value} enum value is not supported in Gemini API.') + + +def _VideoGenerationReferenceType_to_mldev_enum_validate( + enum_value: Any, +) -> None: + if enum_value in set(['STYLE']): + raise ValueError(f'{enum_value} enum value is not supported in Gemini API.') + + +def _AuthConfig_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['api_key']) is not None: + setv(to_object, ['apiKey'], getv(from_object, ['api_key'])) + + if getv(from_object, ['api_key_config']) is not None: + raise ValueError('api_key_config parameter is not supported in Gemini API.') + + if getv(from_object, ['auth_type']) is not None: + raise ValueError('auth_type parameter is not supported in Gemini API.') + + if getv(from_object, ['google_service_account_config']) is not None: + raise ValueError( + 'google_service_account_config parameter is not supported in Gemini' + ' API.' + ) + + if getv(from_object, ['http_basic_auth_config']) is not None: + raise ValueError( + 'http_basic_auth_config parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['oauth_config']) is not None: + raise ValueError('oauth_config parameter is not supported in Gemini API.') + + if getv(from_object, ['oidc_config']) is not None: + raise ValueError('oidc_config parameter is not supported in Gemini API.') + + return to_object + + +def _Blob_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['data']) is not None: + setv(to_object, ['data'], getv(from_object, ['data'])) + + if getv(from_object, ['display_name']) is not None: + raise ValueError('display_name parameter is not supported in Gemini API.') + + if getv(from_object, ['mime_type']) is not None: + setv(to_object, ['mimeType'], getv(from_object, ['mime_type'])) + + return to_object + + +def _Candidate_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['content']) is not None: + setv(to_object, ['content'], getv(from_object, ['content'])) + + if getv(from_object, ['citationMetadata']) is not None: + setv( + to_object, + ['citation_metadata'], + _CitationMetadata_from_mldev( + getv(from_object, ['citationMetadata']), to_object, root_object + ), + ) + + if getv(from_object, ['tokenCount']) is not None: + setv(to_object, ['token_count'], getv(from_object, ['tokenCount'])) + + if getv(from_object, ['finishReason']) is not None: + setv(to_object, ['finish_reason'], getv(from_object, ['finishReason'])) + + if getv(from_object, ['groundingMetadata']) is not None: + setv( + to_object, + ['grounding_metadata'], + getv(from_object, ['groundingMetadata']), + ) + + if getv(from_object, ['avgLogprobs']) is not None: + setv(to_object, ['avg_logprobs'], getv(from_object, ['avgLogprobs'])) + + if getv(from_object, ['index']) is not None: + setv(to_object, ['index'], getv(from_object, ['index'])) + + if getv(from_object, ['logprobsResult']) is not None: + setv(to_object, ['logprobs_result'], getv(from_object, ['logprobsResult'])) + + if getv(from_object, ['safetyRatings']) is not None: + setv( + to_object, + ['safety_ratings'], + [item for item in getv(from_object, ['safetyRatings'])], + ) + + if getv(from_object, ['urlContextMetadata']) is not None: + setv( + to_object, + ['url_context_metadata'], + getv(from_object, ['urlContextMetadata']), + ) + + return to_object + + +def _CitationMetadata_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['citationSources']) is not None: + setv( + to_object, + ['citations'], + [item for item in getv(from_object, ['citationSources'])], + ) + + return to_object + + +def _ComputeTokensParameters_to_vertex( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['model']) is not None: + setv( + to_object, + ['_url', 'model'], + t.t_model(api_client, getv(from_object, ['model'])), + ) + + if getv(from_object, ['contents']) is not None: + setv( + to_object, + ['contents'], + [ + _Content_to_vertex(item, to_object, root_object) + for item in t.t_contents(getv(from_object, ['contents'])) + ], + ) + + return to_object + + +def _ComputeTokensResponse_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['sdkHttpResponse']) is not None: + setv( + to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse']) + ) + + if getv(from_object, ['tokensInfo']) is not None: + setv( + to_object, + ['tokens_info'], + [item for item in getv(from_object, ['tokensInfo'])], + ) + + return to_object + + +def _ContentEmbeddingStatistics_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['truncated']) is not None: + setv(to_object, ['truncated'], getv(from_object, ['truncated'])) + + if getv(from_object, ['token_count']) is not None: + setv(to_object, ['token_count'], getv(from_object, ['token_count'])) + + return to_object + + +def _ContentEmbedding_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['values']) is not None: + setv(to_object, ['values'], getv(from_object, ['values'])) + + if getv(from_object, ['statistics']) is not None: + setv( + to_object, + ['statistics'], + _ContentEmbeddingStatistics_from_vertex( + getv(from_object, ['statistics']), to_object, root_object + ), + ) + + return to_object + + +def _Content_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['parts']) is not None: + setv( + to_object, + ['parts'], + [ + _Part_to_mldev(item, to_object, root_object) + for item in getv(from_object, ['parts']) + ], + ) + + if getv(from_object, ['role']) is not None: + setv(to_object, ['role'], getv(from_object, ['role'])) + + return to_object + + +def _Content_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['parts']) is not None: + setv( + to_object, + ['parts'], + [ + _Part_to_vertex(item, to_object, root_object) + for item in getv(from_object, ['parts']) + ], + ) + + if getv(from_object, ['role']) is not None: + setv(to_object, ['role'], getv(from_object, ['role'])) + + return to_object + + +def _ControlReferenceConfig_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['control_type']) is not None: + setv(to_object, ['controlType'], getv(from_object, ['control_type'])) + + if getv(from_object, ['enable_control_image_computation']) is not None: + setv( + to_object, + ['computeControl'], + getv(from_object, ['enable_control_image_computation']), + ) + + return to_object + + +def _CountTokensConfig_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['system_instruction']) is not None: + raise ValueError( + 'system_instruction parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['tools']) is not None: + raise ValueError('tools parameter is not supported in Gemini API.') + + if getv(from_object, ['generation_config']) is not None: + raise ValueError( + 'generation_config parameter is not supported in Gemini API.' + ) + + return to_object + + +def _CountTokensConfig_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['system_instruction']) is not None: + setv( + parent_object, + ['systemInstruction'], + _Content_to_vertex( + t.t_content(getv(from_object, ['system_instruction'])), + to_object, + root_object, + ), + ) + + if getv(from_object, ['tools']) is not None: + setv( + parent_object, + ['tools'], + [ + _Tool_to_vertex(item, to_object, root_object) + for item in getv(from_object, ['tools']) + ], + ) + + if getv(from_object, ['generation_config']) is not None: + setv( + parent_object, + ['generationConfig'], + _GenerationConfig_to_vertex( + getv(from_object, ['generation_config']), to_object, root_object + ), + ) + + return to_object + + +def _CountTokensParameters_to_mldev( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['model']) is not None: + setv( + to_object, + ['_url', 'model'], + t.t_model(api_client, getv(from_object, ['model'])), + ) + + if getv(from_object, ['contents']) is not None: + setv( + to_object, + ['contents'], + [ + _Content_to_mldev(item, to_object, root_object) + for item in t.t_contents(getv(from_object, ['contents'])) + ], + ) + + if getv(from_object, ['config']) is not None: + _CountTokensConfig_to_mldev( + getv(from_object, ['config']), to_object, root_object + ) + + return to_object + + +def _CountTokensParameters_to_vertex( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['model']) is not None: + setv( + to_object, + ['_url', 'model'], + t.t_model(api_client, getv(from_object, ['model'])), + ) + + if getv(from_object, ['contents']) is not None: + setv( + to_object, + ['contents'], + [ + _Content_to_vertex(item, to_object, root_object) + for item in t.t_contents(getv(from_object, ['contents'])) + ], + ) + + if getv(from_object, ['config']) is not None: + _CountTokensConfig_to_vertex( + getv(from_object, ['config']), to_object, root_object + ) + + return to_object + + +def _CountTokensResponse_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['sdkHttpResponse']) is not None: + setv( + to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse']) + ) + + if getv(from_object, ['totalTokens']) is not None: + setv(to_object, ['total_tokens'], getv(from_object, ['totalTokens'])) + + if getv(from_object, ['cachedContentTokenCount']) is not None: + setv( + to_object, + ['cached_content_token_count'], + getv(from_object, ['cachedContentTokenCount']), + ) + + return to_object + + +def _CountTokensResponse_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['sdkHttpResponse']) is not None: + setv( + to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse']) + ) + + if getv(from_object, ['totalTokens']) is not None: + setv(to_object, ['total_tokens'], getv(from_object, ['totalTokens'])) + + return to_object + + +def _DeleteModelParameters_to_mldev( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['model']) is not None: + setv( + to_object, + ['_url', 'name'], + t.t_model(api_client, getv(from_object, ['model'])), + ) + + return to_object + + +def _DeleteModelParameters_to_vertex( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['model']) is not None: + setv( + to_object, + ['_url', 'name'], + t.t_model(api_client, getv(from_object, ['model'])), + ) + + return to_object + + +def _DeleteModelResponse_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['sdkHttpResponse']) is not None: + setv( + to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse']) + ) + + return to_object + + +def _DeleteModelResponse_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['sdkHttpResponse']) is not None: + setv( + to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse']) + ) + + return to_object + + +def _EditImageConfig_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['output_gcs_uri']) is not None: + setv( + parent_object, + ['parameters', 'storageUri'], + getv(from_object, ['output_gcs_uri']), + ) + + if getv(from_object, ['negative_prompt']) is not None: + setv( + parent_object, + ['parameters', 'negativePrompt'], + getv(from_object, ['negative_prompt']), + ) + + if getv(from_object, ['number_of_images']) is not None: + setv( + parent_object, + ['parameters', 'sampleCount'], + getv(from_object, ['number_of_images']), + ) + + if getv(from_object, ['aspect_ratio']) is not None: + setv( + parent_object, + ['parameters', 'aspectRatio'], + getv(from_object, ['aspect_ratio']), + ) + + if getv(from_object, ['guidance_scale']) is not None: + setv( + parent_object, + ['parameters', 'guidanceScale'], + getv(from_object, ['guidance_scale']), + ) + + if getv(from_object, ['seed']) is not None: + setv(parent_object, ['parameters', 'seed'], getv(from_object, ['seed'])) + + if getv(from_object, ['safety_filter_level']) is not None: + setv( + parent_object, + ['parameters', 'safetySetting'], + getv(from_object, ['safety_filter_level']), + ) + + if getv(from_object, ['person_generation']) is not None: + setv( + parent_object, + ['parameters', 'personGeneration'], + getv(from_object, ['person_generation']), + ) + + if getv(from_object, ['include_safety_attributes']) is not None: + setv( + parent_object, + ['parameters', 'includeSafetyAttributes'], + getv(from_object, ['include_safety_attributes']), + ) + + if getv(from_object, ['include_rai_reason']) is not None: + setv( + parent_object, + ['parameters', 'includeRaiReason'], + getv(from_object, ['include_rai_reason']), + ) + + if getv(from_object, ['language']) is not None: + setv( + parent_object, + ['parameters', 'language'], + getv(from_object, ['language']), + ) + + if getv(from_object, ['output_mime_type']) is not None: + setv( + parent_object, + ['parameters', 'outputOptions', 'mimeType'], + getv(from_object, ['output_mime_type']), + ) + + if getv(from_object, ['output_compression_quality']) is not None: + setv( + parent_object, + ['parameters', 'outputOptions', 'compressionQuality'], + getv(from_object, ['output_compression_quality']), + ) + + if getv(from_object, ['add_watermark']) is not None: + setv( + parent_object, + ['parameters', 'addWatermark'], + getv(from_object, ['add_watermark']), + ) + + if getv(from_object, ['labels']) is not None: + setv(parent_object, ['labels'], getv(from_object, ['labels'])) + + if getv(from_object, ['edit_mode']) is not None: + setv( + parent_object, + ['parameters', 'editMode'], + getv(from_object, ['edit_mode']), + ) + + if getv(from_object, ['base_steps']) is not None: + setv( + parent_object, + ['parameters', 'editConfig', 'baseSteps'], + getv(from_object, ['base_steps']), + ) + + return to_object + + +def _EditImageParameters_to_vertex( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['model']) is not None: + setv( + to_object, + ['_url', 'model'], + t.t_model(api_client, getv(from_object, ['model'])), + ) + + if getv(from_object, ['prompt']) is not None: + setv(to_object, ['instances[0]', 'prompt'], getv(from_object, ['prompt'])) + + if getv(from_object, ['reference_images']) is not None: + setv( + to_object, + ['instances[0]', 'referenceImages'], + [ + _ReferenceImageAPI_to_vertex(item, to_object, root_object) + for item in getv(from_object, ['reference_images']) + ], + ) + + if getv(from_object, ['config']) is not None: + _EditImageConfig_to_vertex( + getv(from_object, ['config']), to_object, root_object + ) + + return to_object + + +def _EditImageResponse_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['sdkHttpResponse']) is not None: + setv( + to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse']) + ) + + if getv(from_object, ['predictions']) is not None: + setv( + to_object, + ['generated_images'], + [ + _GeneratedImage_from_vertex(item, to_object, root_object) + for item in getv(from_object, ['predictions']) + ], + ) + + return to_object + + +def _EmbedContentConfig_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['task_type']) is not None: + setv( + parent_object, + ['requests[]', 'taskType'], + getv(from_object, ['task_type']), + ) + + if getv(from_object, ['title']) is not None: + setv(parent_object, ['requests[]', 'title'], getv(from_object, ['title'])) + + if getv(from_object, ['output_dimensionality']) is not None: + setv( + parent_object, + ['requests[]', 'outputDimensionality'], + getv(from_object, ['output_dimensionality']), + ) + + if getv(from_object, ['mime_type']) is not None: + raise ValueError('mime_type parameter is not supported in Gemini API.') + + if getv(from_object, ['auto_truncate']) is not None: + raise ValueError('auto_truncate parameter is not supported in Gemini API.') + + if getv(from_object, ['document_ocr']) is not None: + raise ValueError('document_ocr parameter is not supported in Gemini API.') + + if getv(from_object, ['audio_track_extraction']) is not None: + raise ValueError( + 'audio_track_extraction parameter is not supported in Gemini API.' + ) + + return to_object + + +def _EmbedContentConfig_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + discriminator = getv(root_object, ['embedding_api_type']) + if discriminator is None: + discriminator = 'PREDICT' + if discriminator == 'PREDICT': + if getv(from_object, ['task_type']) is not None: + setv( + parent_object, + ['instances[]', 'task_type'], + getv(from_object, ['task_type']), + ) + elif discriminator == 'EMBED_CONTENT': + if getv(from_object, ['task_type']) is not None: + setv( + parent_object, + ['embedContentConfig', 'taskType'], + getv(from_object, ['task_type']), + ) + + discriminator = getv(root_object, ['embedding_api_type']) + if discriminator is None: + discriminator = 'PREDICT' + if discriminator == 'PREDICT': + if getv(from_object, ['title']) is not None: + setv( + parent_object, ['instances[]', 'title'], getv(from_object, ['title']) + ) + elif discriminator == 'EMBED_CONTENT': + if getv(from_object, ['title']) is not None: + setv( + parent_object, + ['embedContentConfig', 'title'], + getv(from_object, ['title']), + ) + + discriminator = getv(root_object, ['embedding_api_type']) + if discriminator is None: + discriminator = 'PREDICT' + if discriminator == 'PREDICT': + if getv(from_object, ['output_dimensionality']) is not None: + setv( + parent_object, + ['parameters', 'outputDimensionality'], + getv(from_object, ['output_dimensionality']), + ) + elif discriminator == 'EMBED_CONTENT': + if getv(from_object, ['output_dimensionality']) is not None: + setv( + parent_object, + ['embedContentConfig', 'outputDimensionality'], + getv(from_object, ['output_dimensionality']), + ) + + discriminator = getv(root_object, ['embedding_api_type']) + if discriminator is None: + discriminator = 'PREDICT' + if discriminator == 'PREDICT': + if getv(from_object, ['mime_type']) is not None: + setv( + parent_object, + ['instances[]', 'mimeType'], + getv(from_object, ['mime_type']), + ) + + discriminator = getv(root_object, ['embedding_api_type']) + if discriminator is None: + discriminator = 'PREDICT' + if discriminator == 'PREDICT': + if getv(from_object, ['auto_truncate']) is not None: + setv( + parent_object, + ['parameters', 'autoTruncate'], + getv(from_object, ['auto_truncate']), + ) + elif discriminator == 'EMBED_CONTENT': + if getv(from_object, ['auto_truncate']) is not None: + setv( + parent_object, + ['embedContentConfig', 'autoTruncate'], + getv(from_object, ['auto_truncate']), + ) + + discriminator = getv(root_object, ['embedding_api_type']) + if discriminator is None: + discriminator = 'PREDICT' + if discriminator == 'EMBED_CONTENT': + if getv(from_object, ['document_ocr']) is not None: + setv( + parent_object, + ['embedContentConfig', 'documentOcr'], + getv(from_object, ['document_ocr']), + ) + + discriminator = getv(root_object, ['embedding_api_type']) + if discriminator is None: + discriminator = 'PREDICT' + if discriminator == 'EMBED_CONTENT': + if getv(from_object, ['audio_track_extraction']) is not None: + setv( + parent_object, + ['embedContentConfig', 'audioTrackExtraction'], + getv(from_object, ['audio_track_extraction']), + ) + + return to_object + + +def _EmbedContentParametersPrivate_to_mldev( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['model']) is not None: + setv( + to_object, + ['_url', 'model'], + t.t_model(api_client, getv(from_object, ['model'])), + ) + + if getv(from_object, ['contents']) is not None: + setv( + to_object, + ['requests[]', 'content'], + [ + item + for item in t.t_contents_for_embed( + api_client, getv(from_object, ['contents']) + ) + ], + ) + + if getv(from_object, ['content']) is not None: + _Content_to_mldev( + t.t_content(getv(from_object, ['content'])), to_object, root_object + ) + + if getv(from_object, ['config']) is not None: + _EmbedContentConfig_to_mldev( + getv(from_object, ['config']), to_object, root_object + ) + + setv( + to_object, + ['requests[]', 'model'], + t.t_model(api_client, getv(from_object, ['model'])), + ) + return to_object + + +def _EmbedContentParametersPrivate_to_vertex( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['model']) is not None: + setv( + to_object, + ['_url', 'model'], + t.t_model(api_client, getv(from_object, ['model'])), + ) + + discriminator = getv(root_object, ['embedding_api_type']) + if discriminator is None: + discriminator = 'PREDICT' + if discriminator == 'PREDICT': + if getv(from_object, ['contents']) is not None: + setv( + to_object, + ['instances[]', 'content'], + [ + item + for item in t.t_contents_for_embed( + api_client, getv(from_object, ['contents']) + ) + ], + ) + + discriminator = getv(root_object, ['embedding_api_type']) + if discriminator is None: + discriminator = 'PREDICT' + if discriminator == 'EMBED_CONTENT': + if getv(from_object, ['content']) is not None: + setv( + to_object, + ['content'], + _Content_to_vertex( + t.t_content(getv(from_object, ['content'])), + to_object, + root_object, + ), + ) + + if getv(from_object, ['config']) is not None: + _EmbedContentConfig_to_vertex( + getv(from_object, ['config']), to_object, root_object + ) + + return to_object + + +def _EmbedContentResponse_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['sdkHttpResponse']) is not None: + setv( + to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse']) + ) + + if getv(from_object, ['embeddings']) is not None: + setv( + to_object, + ['embeddings'], + [item for item in getv(from_object, ['embeddings'])], + ) + + if getv(from_object, ['metadata']) is not None: + setv(to_object, ['metadata'], getv(from_object, ['metadata'])) + + return to_object + + +def _EmbedContentResponse_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['sdkHttpResponse']) is not None: + setv( + to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse']) + ) + + if getv(from_object, ['predictions[]', 'embeddings']) is not None: + setv( + to_object, + ['embeddings'], + [ + _ContentEmbedding_from_vertex(item, to_object, root_object) + for item in getv(from_object, ['predictions[]', 'embeddings']) + ], + ) + + if getv(from_object, ['metadata']) is not None: + setv(to_object, ['metadata'], getv(from_object, ['metadata'])) + + if getv(root_object, ['embedding_api_type']) == 'EMBED_CONTENT': + embedding = getv(from_object, ['embedding']) + usage_metadata = getv(from_object, ['usageMetadata']) + truncated = getv(from_object, ['truncated']) + if embedding: + stats = {} + if usage_metadata and usage_metadata.get('promptTokenCount'): + stats['token_count'] = usage_metadata['promptTokenCount'] + if truncated: + stats['truncated'] = truncated + embedding['statistics'] = stats + setv(to_object, ['embeddings'], [embedding]) + + return to_object + + +def _Endpoint_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['endpoint']) is not None: + setv(to_object, ['name'], getv(from_object, ['endpoint'])) + + if getv(from_object, ['deployedModelId']) is not None: + setv( + to_object, ['deployed_model_id'], getv(from_object, ['deployedModelId']) + ) + + return to_object + + +def _FileData_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['display_name']) is not None: + raise ValueError('display_name parameter is not supported in Gemini API.') + + if getv(from_object, ['file_uri']) is not None: + setv(to_object, ['fileUri'], getv(from_object, ['file_uri'])) + + if getv(from_object, ['mime_type']) is not None: + setv(to_object, ['mimeType'], getv(from_object, ['mime_type'])) + + return to_object + + +def _FunctionCall_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['id']) is not None: + setv(to_object, ['id'], getv(from_object, ['id'])) + + if getv(from_object, ['args']) is not None: + setv(to_object, ['args'], getv(from_object, ['args'])) + + if getv(from_object, ['name']) is not None: + setv(to_object, ['name'], getv(from_object, ['name'])) + + if getv(from_object, ['partial_args']) is not None: + raise ValueError('partial_args parameter is not supported in Gemini API.') + + if getv(from_object, ['will_continue']) is not None: + raise ValueError('will_continue parameter is not supported in Gemini API.') + + return to_object + + +def _FunctionCallingConfig_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['allowed_function_names']) is not None: + setv( + to_object, + ['allowedFunctionNames'], + getv(from_object, ['allowed_function_names']), + ) + + if getv(from_object, ['mode']) is not None: + setv(to_object, ['mode'], getv(from_object, ['mode'])) + + if getv(from_object, ['stream_function_call_arguments']) is not None: + raise ValueError( + 'stream_function_call_arguments parameter is not supported in Gemini' + ' API.' + ) + + return to_object + + +def _FunctionDeclaration_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['description']) is not None: + setv(to_object, ['description'], getv(from_object, ['description'])) + + if getv(from_object, ['name']) is not None: + setv(to_object, ['name'], getv(from_object, ['name'])) + + if getv(from_object, ['parameters']) is not None: + setv(to_object, ['parameters'], getv(from_object, ['parameters'])) + + if getv(from_object, ['parameters_json_schema']) is not None: + setv( + to_object, + ['parametersJsonSchema'], + getv(from_object, ['parameters_json_schema']), + ) + + if getv(from_object, ['response']) is not None: + setv(to_object, ['response'], getv(from_object, ['response'])) + + if getv(from_object, ['response_json_schema']) is not None: + setv( + to_object, + ['responseJsonSchema'], + getv(from_object, ['response_json_schema']), + ) + + if getv(from_object, ['behavior']) is not None: + raise ValueError('behavior parameter is not supported in Vertex AI.') + + return to_object + + +def _GenerateContentConfig_to_mldev( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['system_instruction']) is not None: + setv( + parent_object, + ['systemInstruction'], + _Content_to_mldev( + t.t_content(getv(from_object, ['system_instruction'])), + to_object, + root_object, + ), + ) + + if getv(from_object, ['temperature']) is not None: + setv(to_object, ['temperature'], getv(from_object, ['temperature'])) + + if getv(from_object, ['top_p']) is not None: + setv(to_object, ['topP'], getv(from_object, ['top_p'])) + + if getv(from_object, ['top_k']) is not None: + setv(to_object, ['topK'], getv(from_object, ['top_k'])) + + if getv(from_object, ['candidate_count']) is not None: + setv(to_object, ['candidateCount'], getv(from_object, ['candidate_count'])) + + if getv(from_object, ['max_output_tokens']) is not None: + setv( + to_object, ['maxOutputTokens'], getv(from_object, ['max_output_tokens']) + ) + + if getv(from_object, ['stop_sequences']) is not None: + setv(to_object, ['stopSequences'], getv(from_object, ['stop_sequences'])) + + if getv(from_object, ['response_logprobs']) is not None: + setv( + to_object, + ['responseLogprobs'], + getv(from_object, ['response_logprobs']), + ) + + if getv(from_object, ['logprobs']) is not None: + setv(to_object, ['logprobs'], getv(from_object, ['logprobs'])) + + if getv(from_object, ['presence_penalty']) is not None: + setv( + to_object, ['presencePenalty'], getv(from_object, ['presence_penalty']) + ) + + if getv(from_object, ['frequency_penalty']) is not None: + setv( + to_object, + ['frequencyPenalty'], + getv(from_object, ['frequency_penalty']), + ) + + if getv(from_object, ['seed']) is not None: + setv(to_object, ['seed'], getv(from_object, ['seed'])) + + if getv(from_object, ['response_mime_type']) is not None: + setv( + to_object, + ['responseMimeType'], + getv(from_object, ['response_mime_type']), + ) + + if getv(from_object, ['response_schema']) is not None: + setv( + to_object, + ['responseSchema'], + t.t_schema(api_client, getv(from_object, ['response_schema'])), + ) + + if getv(from_object, ['response_json_schema']) is not None: + setv( + to_object, + ['responseJsonSchema'], + getv(from_object, ['response_json_schema']), + ) + + if getv(from_object, ['routing_config']) is not None: + raise ValueError('routing_config parameter is not supported in Gemini API.') + + if getv(from_object, ['model_selection_config']) is not None: + raise ValueError( + 'model_selection_config parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['safety_settings']) is not None: + setv( + parent_object, + ['safetySettings'], + [ + _SafetySetting_to_mldev(item, to_object, root_object) + for item in getv(from_object, ['safety_settings']) + ], + ) + + if getv(from_object, ['tools']) is not None: + setv( + parent_object, + ['tools'], + [ + _Tool_to_mldev(t.t_tool(api_client, item), to_object, root_object) + for item in t.t_tools(api_client, getv(from_object, ['tools'])) + ], + ) + + if getv(from_object, ['tool_config']) is not None: + setv( + parent_object, + ['toolConfig'], + _ToolConfig_to_mldev( + getv(from_object, ['tool_config']), to_object, root_object + ), + ) + + if getv(from_object, ['labels']) is not None: + raise ValueError('labels parameter is not supported in Gemini API.') + + if getv(from_object, ['cached_content']) is not None: + setv( + parent_object, + ['cachedContent'], + t.t_cached_content_name( + api_client, getv(from_object, ['cached_content']) + ), + ) + + if getv(from_object, ['response_modalities']) is not None: + setv( + to_object, + ['responseModalities'], + getv(from_object, ['response_modalities']), + ) + + if getv(from_object, ['media_resolution']) is not None: + setv( + to_object, ['mediaResolution'], getv(from_object, ['media_resolution']) + ) + + if getv(from_object, ['speech_config']) is not None: + setv( + to_object, + ['speechConfig'], + t.t_speech_config(getv(from_object, ['speech_config'])), + ) + + if getv(from_object, ['audio_timestamp']) is not None: + raise ValueError( + 'audio_timestamp parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['thinking_config']) is not None: + setv(to_object, ['thinkingConfig'], getv(from_object, ['thinking_config'])) + + if getv(from_object, ['image_config']) is not None: + setv( + to_object, + ['imageConfig'], + _ImageConfig_to_mldev( + getv(from_object, ['image_config']), to_object, root_object + ), + ) + + if getv(from_object, ['enable_enhanced_civic_answers']) is not None: + setv( + to_object, + ['enableEnhancedCivicAnswers'], + getv(from_object, ['enable_enhanced_civic_answers']), + ) + + if getv(from_object, ['model_armor_config']) is not None: + raise ValueError( + 'model_armor_config parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['service_tier']) is not None: + setv(parent_object, ['serviceTier'], getv(from_object, ['service_tier'])) + + return to_object + + +def _GenerateContentConfig_to_vertex( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['system_instruction']) is not None: + setv( + parent_object, + ['systemInstruction'], + _Content_to_vertex( + t.t_content(getv(from_object, ['system_instruction'])), + to_object, + root_object, + ), + ) + + if getv(from_object, ['temperature']) is not None: + setv(to_object, ['temperature'], getv(from_object, ['temperature'])) + + if getv(from_object, ['top_p']) is not None: + setv(to_object, ['topP'], getv(from_object, ['top_p'])) + + if getv(from_object, ['top_k']) is not None: + setv(to_object, ['topK'], getv(from_object, ['top_k'])) + + if getv(from_object, ['candidate_count']) is not None: + setv(to_object, ['candidateCount'], getv(from_object, ['candidate_count'])) + + if getv(from_object, ['max_output_tokens']) is not None: + setv( + to_object, ['maxOutputTokens'], getv(from_object, ['max_output_tokens']) + ) + + if getv(from_object, ['stop_sequences']) is not None: + setv(to_object, ['stopSequences'], getv(from_object, ['stop_sequences'])) + + if getv(from_object, ['response_logprobs']) is not None: + setv( + to_object, + ['responseLogprobs'], + getv(from_object, ['response_logprobs']), + ) + + if getv(from_object, ['logprobs']) is not None: + setv(to_object, ['logprobs'], getv(from_object, ['logprobs'])) + + if getv(from_object, ['presence_penalty']) is not None: + setv( + to_object, ['presencePenalty'], getv(from_object, ['presence_penalty']) + ) + + if getv(from_object, ['frequency_penalty']) is not None: + setv( + to_object, + ['frequencyPenalty'], + getv(from_object, ['frequency_penalty']), + ) + + if getv(from_object, ['seed']) is not None: + setv(to_object, ['seed'], getv(from_object, ['seed'])) + + if getv(from_object, ['response_mime_type']) is not None: + setv( + to_object, + ['responseMimeType'], + getv(from_object, ['response_mime_type']), + ) + + if getv(from_object, ['response_schema']) is not None: + setv( + to_object, + ['responseSchema'], + t.t_schema(api_client, getv(from_object, ['response_schema'])), + ) + + if getv(from_object, ['response_json_schema']) is not None: + setv( + to_object, + ['responseJsonSchema'], + getv(from_object, ['response_json_schema']), + ) + + if getv(from_object, ['routing_config']) is not None: + setv(to_object, ['routingConfig'], getv(from_object, ['routing_config'])) + + if getv(from_object, ['model_selection_config']) is not None: + setv( + to_object, + ['modelConfig'], + getv(from_object, ['model_selection_config']), + ) + + if getv(from_object, ['safety_settings']) is not None: + setv( + parent_object, + ['safetySettings'], + [item for item in getv(from_object, ['safety_settings'])], + ) + + if getv(from_object, ['tools']) is not None: + setv( + parent_object, + ['tools'], + [ + _Tool_to_vertex(t.t_tool(api_client, item), to_object, root_object) + for item in t.t_tools(api_client, getv(from_object, ['tools'])) + ], + ) + + if getv(from_object, ['tool_config']) is not None: + setv( + parent_object, + ['toolConfig'], + _ToolConfig_to_vertex( + getv(from_object, ['tool_config']), to_object, root_object + ), + ) + + if getv(from_object, ['labels']) is not None: + setv(parent_object, ['labels'], getv(from_object, ['labels'])) + + if getv(from_object, ['cached_content']) is not None: + setv( + parent_object, + ['cachedContent'], + t.t_cached_content_name( + api_client, getv(from_object, ['cached_content']) + ), + ) + + if getv(from_object, ['response_modalities']) is not None: + setv( + to_object, + ['responseModalities'], + getv(from_object, ['response_modalities']), + ) + + if getv(from_object, ['media_resolution']) is not None: + setv( + to_object, ['mediaResolution'], getv(from_object, ['media_resolution']) + ) + + if getv(from_object, ['speech_config']) is not None: + setv( + to_object, + ['speechConfig'], + _SpeechConfig_to_vertex( + t.t_speech_config(getv(from_object, ['speech_config'])), + to_object, + root_object, + ), + ) + + if getv(from_object, ['audio_timestamp']) is not None: + setv(to_object, ['audioTimestamp'], getv(from_object, ['audio_timestamp'])) + + if getv(from_object, ['thinking_config']) is not None: + setv(to_object, ['thinkingConfig'], getv(from_object, ['thinking_config'])) + + if getv(from_object, ['image_config']) is not None: + setv( + to_object, + ['imageConfig'], + _ImageConfig_to_vertex( + getv(from_object, ['image_config']), to_object, root_object + ), + ) + + if getv(from_object, ['enable_enhanced_civic_answers']) is not None: + raise ValueError( + 'enable_enhanced_civic_answers parameter is not supported in Vertex AI.' + ) + + if getv(from_object, ['model_armor_config']) is not None: + setv( + parent_object, + ['modelArmorConfig'], + getv(from_object, ['model_armor_config']), + ) + + if getv(from_object, ['service_tier']) is not None: + setv(parent_object, ['serviceTier'], getv(from_object, ['service_tier'])) + + return to_object + + +def _GenerateContentParameters_to_mldev( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['model']) is not None: + setv( + to_object, + ['_url', 'model'], + t.t_model(api_client, getv(from_object, ['model'])), + ) + + if getv(from_object, ['contents']) is not None: + setv( + to_object, + ['contents'], + [ + _Content_to_mldev(item, to_object, root_object) + for item in t.t_contents(getv(from_object, ['contents'])) + ], + ) + + if getv(from_object, ['config']) is not None: + setv( + to_object, + ['generationConfig'], + _GenerateContentConfig_to_mldev( + api_client, getv(from_object, ['config']), to_object, root_object + ), + ) + + return to_object + + +def _GenerateContentParameters_to_vertex( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['model']) is not None: + setv( + to_object, + ['_url', 'model'], + t.t_model(api_client, getv(from_object, ['model'])), + ) + + if getv(from_object, ['contents']) is not None: + setv( + to_object, + ['contents'], + [ + _Content_to_vertex(item, to_object, root_object) + for item in t.t_contents(getv(from_object, ['contents'])) + ], + ) + + if getv(from_object, ['config']) is not None: + setv( + to_object, + ['generationConfig'], + _GenerateContentConfig_to_vertex( + api_client, getv(from_object, ['config']), to_object, root_object + ), + ) + + return to_object + + +def _GenerateContentResponse_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['sdkHttpResponse']) is not None: + setv( + to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse']) + ) + + if getv(from_object, ['candidates']) is not None: + setv( + to_object, + ['candidates'], + [ + _Candidate_from_mldev(item, to_object, root_object) + for item in getv(from_object, ['candidates']) + ], + ) + + if getv(from_object, ['modelVersion']) is not None: + setv(to_object, ['model_version'], getv(from_object, ['modelVersion'])) + + if getv(from_object, ['promptFeedback']) is not None: + setv(to_object, ['prompt_feedback'], getv(from_object, ['promptFeedback'])) + + if getv(from_object, ['responseId']) is not None: + setv(to_object, ['response_id'], getv(from_object, ['responseId'])) + + if getv(from_object, ['usageMetadata']) is not None: + setv(to_object, ['usage_metadata'], getv(from_object, ['usageMetadata'])) + + if getv(from_object, ['modelStatus']) is not None: + setv(to_object, ['model_status'], getv(from_object, ['modelStatus'])) + + return to_object + + +def _GenerateContentResponse_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['sdkHttpResponse']) is not None: + setv( + to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse']) + ) + + if getv(from_object, ['candidates']) is not None: + setv( + to_object, + ['candidates'], + [item for item in getv(from_object, ['candidates'])], + ) + + if getv(from_object, ['createTime']) is not None: + setv(to_object, ['create_time'], getv(from_object, ['createTime'])) + + if getv(from_object, ['modelVersion']) is not None: + setv(to_object, ['model_version'], getv(from_object, ['modelVersion'])) + + if getv(from_object, ['promptFeedback']) is not None: + setv(to_object, ['prompt_feedback'], getv(from_object, ['promptFeedback'])) + + if getv(from_object, ['responseId']) is not None: + setv(to_object, ['response_id'], getv(from_object, ['responseId'])) + + if getv(from_object, ['usageMetadata']) is not None: + setv(to_object, ['usage_metadata'], getv(from_object, ['usageMetadata'])) + + return to_object + + +def _GenerateImagesConfig_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['output_gcs_uri']) is not None: + raise ValueError('output_gcs_uri parameter is not supported in Gemini API.') + + if getv(from_object, ['negative_prompt']) is not None: + raise ValueError( + 'negative_prompt parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['number_of_images']) is not None: + setv( + parent_object, + ['parameters', 'sampleCount'], + getv(from_object, ['number_of_images']), + ) + + if getv(from_object, ['aspect_ratio']) is not None: + setv( + parent_object, + ['parameters', 'aspectRatio'], + getv(from_object, ['aspect_ratio']), + ) + + if getv(from_object, ['guidance_scale']) is not None: + setv( + parent_object, + ['parameters', 'guidanceScale'], + getv(from_object, ['guidance_scale']), + ) + + if getv(from_object, ['seed']) is not None: + raise ValueError('seed parameter is not supported in Gemini API.') + + if getv(from_object, ['safety_filter_level']) is not None: + _SafetyFilterLevel_to_mldev_enum_validate( + getv(from_object, ['safety_filter_level']) + ) + setv( + parent_object, + ['parameters', 'safetySetting'], + getv(from_object, ['safety_filter_level']), + ) + + if getv(from_object, ['person_generation']) is not None: + _PersonGeneration_to_mldev_enum_validate( + getv(from_object, ['person_generation']) + ) + setv( + parent_object, + ['parameters', 'personGeneration'], + getv(from_object, ['person_generation']), + ) + + if getv(from_object, ['include_safety_attributes']) is not None: + setv( + parent_object, + ['parameters', 'includeSafetyAttributes'], + getv(from_object, ['include_safety_attributes']), + ) + + if getv(from_object, ['include_rai_reason']) is not None: + setv( + parent_object, + ['parameters', 'includeRaiReason'], + getv(from_object, ['include_rai_reason']), + ) + + if getv(from_object, ['language']) is not None: + setv( + parent_object, + ['parameters', 'language'], + getv(from_object, ['language']), + ) + + if getv(from_object, ['output_mime_type']) is not None: + setv( + parent_object, + ['parameters', 'outputOptions', 'mimeType'], + getv(from_object, ['output_mime_type']), + ) + + if getv(from_object, ['output_compression_quality']) is not None: + setv( + parent_object, + ['parameters', 'outputOptions', 'compressionQuality'], + getv(from_object, ['output_compression_quality']), + ) + + if getv(from_object, ['add_watermark']) is not None: + raise ValueError('add_watermark parameter is not supported in Gemini API.') + + if getv(from_object, ['labels']) is not None: + raise ValueError('labels parameter is not supported in Gemini API.') + + if getv(from_object, ['image_size']) is not None: + setv( + parent_object, + ['parameters', 'sampleImageSize'], + getv(from_object, ['image_size']), + ) + + if getv(from_object, ['enhance_prompt']) is not None: + raise ValueError('enhance_prompt parameter is not supported in Gemini API.') + + return to_object + + +def _GenerateImagesConfig_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['output_gcs_uri']) is not None: + setv( + parent_object, + ['parameters', 'storageUri'], + getv(from_object, ['output_gcs_uri']), + ) + + if getv(from_object, ['negative_prompt']) is not None: + setv( + parent_object, + ['parameters', 'negativePrompt'], + getv(from_object, ['negative_prompt']), + ) + + if getv(from_object, ['number_of_images']) is not None: + setv( + parent_object, + ['parameters', 'sampleCount'], + getv(from_object, ['number_of_images']), + ) + + if getv(from_object, ['aspect_ratio']) is not None: + setv( + parent_object, + ['parameters', 'aspectRatio'], + getv(from_object, ['aspect_ratio']), + ) + + if getv(from_object, ['guidance_scale']) is not None: + setv( + parent_object, + ['parameters', 'guidanceScale'], + getv(from_object, ['guidance_scale']), + ) + + if getv(from_object, ['seed']) is not None: + setv(parent_object, ['parameters', 'seed'], getv(from_object, ['seed'])) + + if getv(from_object, ['safety_filter_level']) is not None: + setv( + parent_object, + ['parameters', 'safetySetting'], + getv(from_object, ['safety_filter_level']), + ) + + if getv(from_object, ['person_generation']) is not None: + setv( + parent_object, + ['parameters', 'personGeneration'], + getv(from_object, ['person_generation']), + ) + + if getv(from_object, ['include_safety_attributes']) is not None: + setv( + parent_object, + ['parameters', 'includeSafetyAttributes'], + getv(from_object, ['include_safety_attributes']), + ) + + if getv(from_object, ['include_rai_reason']) is not None: + setv( + parent_object, + ['parameters', 'includeRaiReason'], + getv(from_object, ['include_rai_reason']), + ) + + if getv(from_object, ['language']) is not None: + setv( + parent_object, + ['parameters', 'language'], + getv(from_object, ['language']), + ) + + if getv(from_object, ['output_mime_type']) is not None: + setv( + parent_object, + ['parameters', 'outputOptions', 'mimeType'], + getv(from_object, ['output_mime_type']), + ) + + if getv(from_object, ['output_compression_quality']) is not None: + setv( + parent_object, + ['parameters', 'outputOptions', 'compressionQuality'], + getv(from_object, ['output_compression_quality']), + ) + + if getv(from_object, ['add_watermark']) is not None: + setv( + parent_object, + ['parameters', 'addWatermark'], + getv(from_object, ['add_watermark']), + ) + + if getv(from_object, ['labels']) is not None: + setv(parent_object, ['labels'], getv(from_object, ['labels'])) + + if getv(from_object, ['image_size']) is not None: + setv( + parent_object, + ['parameters', 'sampleImageSize'], + getv(from_object, ['image_size']), + ) + + if getv(from_object, ['enhance_prompt']) is not None: + setv( + parent_object, + ['parameters', 'enhancePrompt'], + getv(from_object, ['enhance_prompt']), + ) + + return to_object + + +def _GenerateImagesParameters_to_mldev( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['model']) is not None: + setv( + to_object, + ['_url', 'model'], + t.t_model(api_client, getv(from_object, ['model'])), + ) + + if getv(from_object, ['prompt']) is not None: + setv(to_object, ['instances[0]', 'prompt'], getv(from_object, ['prompt'])) + + if getv(from_object, ['config']) is not None: + _GenerateImagesConfig_to_mldev( + getv(from_object, ['config']), to_object, root_object + ) + + return to_object + + +def _GenerateImagesParameters_to_vertex( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['model']) is not None: + setv( + to_object, + ['_url', 'model'], + t.t_model(api_client, getv(from_object, ['model'])), + ) + + if getv(from_object, ['prompt']) is not None: + setv(to_object, ['instances[0]', 'prompt'], getv(from_object, ['prompt'])) + + if getv(from_object, ['config']) is not None: + _GenerateImagesConfig_to_vertex( + getv(from_object, ['config']), to_object, root_object + ) + + return to_object + + +def _GenerateImagesResponse_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['sdkHttpResponse']) is not None: + setv( + to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse']) + ) + + if getv(from_object, ['predictions']) is not None: + setv( + to_object, + ['generated_images'], + [ + _GeneratedImage_from_mldev(item, to_object, root_object) + for item in getv(from_object, ['predictions']) + ], + ) + + if getv(from_object, ['positivePromptSafetyAttributes']) is not None: + setv( + to_object, + ['positive_prompt_safety_attributes'], + _SafetyAttributes_from_mldev( + getv(from_object, ['positivePromptSafetyAttributes']), + to_object, + root_object, + ), + ) + + return to_object + + +def _GenerateImagesResponse_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['sdkHttpResponse']) is not None: + setv( + to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse']) + ) + + if getv(from_object, ['predictions']) is not None: + setv( + to_object, + ['generated_images'], + [ + _GeneratedImage_from_vertex(item, to_object, root_object) + for item in getv(from_object, ['predictions']) + ], + ) + + if getv(from_object, ['positivePromptSafetyAttributes']) is not None: + setv( + to_object, + ['positive_prompt_safety_attributes'], + _SafetyAttributes_from_vertex( + getv(from_object, ['positivePromptSafetyAttributes']), + to_object, + root_object, + ), + ) + + return to_object + + +def _GenerateVideosConfig_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['number_of_videos']) is not None: + setv( + parent_object, + ['parameters', 'sampleCount'], + getv(from_object, ['number_of_videos']), + ) + + if getv(from_object, ['output_gcs_uri']) is not None: + raise ValueError('output_gcs_uri parameter is not supported in Gemini API.') + + if getv(from_object, ['fps']) is not None: + raise ValueError('fps parameter is not supported in Gemini API.') + + if getv(from_object, ['duration_seconds']) is not None: + setv( + parent_object, + ['parameters', 'durationSeconds'], + getv(from_object, ['duration_seconds']), + ) + + if getv(from_object, ['seed']) is not None: + raise ValueError('seed parameter is not supported in Gemini API.') + + if getv(from_object, ['aspect_ratio']) is not None: + setv( + parent_object, + ['parameters', 'aspectRatio'], + getv(from_object, ['aspect_ratio']), + ) + + if getv(from_object, ['resolution']) is not None: + setv( + parent_object, + ['parameters', 'resolution'], + getv(from_object, ['resolution']), + ) + + if getv(from_object, ['person_generation']) is not None: + setv( + parent_object, + ['parameters', 'personGeneration'], + getv(from_object, ['person_generation']), + ) + + if getv(from_object, ['pubsub_topic']) is not None: + raise ValueError('pubsub_topic parameter is not supported in Gemini API.') + + if getv(from_object, ['negative_prompt']) is not None: + setv( + parent_object, + ['parameters', 'negativePrompt'], + getv(from_object, ['negative_prompt']), + ) + + if getv(from_object, ['enhance_prompt']) is not None: + setv( + parent_object, + ['parameters', 'enhancePrompt'], + getv(from_object, ['enhance_prompt']), + ) + + if getv(from_object, ['generate_audio']) is not None: + raise ValueError('generate_audio parameter is not supported in Gemini API.') + + if getv(from_object, ['last_frame']) is not None: + setv( + parent_object, + ['instances[0]', 'lastFrame'], + _Image_to_mldev( + getv(from_object, ['last_frame']), to_object, root_object + ), + ) + + if getv(from_object, ['reference_images']) is not None: + setv( + parent_object, + ['instances[0]', 'referenceImages'], + [ + _VideoGenerationReferenceImage_to_mldev( + item, to_object, root_object + ) + for item in getv(from_object, ['reference_images']) + ], + ) + + if getv(from_object, ['mask']) is not None: + raise ValueError('mask parameter is not supported in Gemini API.') + + if getv(from_object, ['compression_quality']) is not None: + raise ValueError( + 'compression_quality parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['labels']) is not None: + raise ValueError('labels parameter is not supported in Gemini API.') + + if getv(from_object, ['webhook_config']) is not None: + setv( + parent_object, ['webhookConfig'], getv(from_object, ['webhook_config']) + ) + + return to_object + + +def _GenerateVideosConfig_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['number_of_videos']) is not None: + setv( + parent_object, + ['parameters', 'sampleCount'], + getv(from_object, ['number_of_videos']), + ) + + if getv(from_object, ['output_gcs_uri']) is not None: + setv( + parent_object, + ['parameters', 'storageUri'], + getv(from_object, ['output_gcs_uri']), + ) + + if getv(from_object, ['fps']) is not None: + setv(parent_object, ['parameters', 'fps'], getv(from_object, ['fps'])) + + if getv(from_object, ['duration_seconds']) is not None: + setv( + parent_object, + ['parameters', 'durationSeconds'], + getv(from_object, ['duration_seconds']), + ) + + if getv(from_object, ['seed']) is not None: + setv(parent_object, ['parameters', 'seed'], getv(from_object, ['seed'])) + + if getv(from_object, ['aspect_ratio']) is not None: + setv( + parent_object, + ['parameters', 'aspectRatio'], + getv(from_object, ['aspect_ratio']), + ) + + if getv(from_object, ['resolution']) is not None: + setv( + parent_object, + ['parameters', 'resolution'], + getv(from_object, ['resolution']), + ) + + if getv(from_object, ['person_generation']) is not None: + setv( + parent_object, + ['parameters', 'personGeneration'], + getv(from_object, ['person_generation']), + ) + + if getv(from_object, ['pubsub_topic']) is not None: + setv( + parent_object, + ['parameters', 'pubsubTopic'], + getv(from_object, ['pubsub_topic']), + ) + + if getv(from_object, ['negative_prompt']) is not None: + setv( + parent_object, + ['parameters', 'negativePrompt'], + getv(from_object, ['negative_prompt']), + ) + + if getv(from_object, ['enhance_prompt']) is not None: + setv( + parent_object, + ['parameters', 'enhancePrompt'], + getv(from_object, ['enhance_prompt']), + ) + + if getv(from_object, ['generate_audio']) is not None: + setv( + parent_object, + ['parameters', 'generateAudio'], + getv(from_object, ['generate_audio']), + ) + + if getv(from_object, ['last_frame']) is not None: + setv( + parent_object, + ['instances[0]', 'lastFrame'], + _Image_to_vertex( + getv(from_object, ['last_frame']), to_object, root_object + ), + ) + + if getv(from_object, ['reference_images']) is not None: + setv( + parent_object, + ['instances[0]', 'referenceImages'], + [ + _VideoGenerationReferenceImage_to_vertex( + item, to_object, root_object + ) + for item in getv(from_object, ['reference_images']) + ], + ) + + if getv(from_object, ['mask']) is not None: + setv( + parent_object, + ['instances[0]', 'mask'], + _VideoGenerationMask_to_vertex( + getv(from_object, ['mask']), to_object, root_object + ), + ) + + if getv(from_object, ['compression_quality']) is not None: + setv( + parent_object, + ['parameters', 'compressionQuality'], + getv(from_object, ['compression_quality']), + ) + + if getv(from_object, ['labels']) is not None: + setv(parent_object, ['labels'], getv(from_object, ['labels'])) + + if getv(from_object, ['webhook_config']) is not None: + raise ValueError('webhook_config parameter is not supported in Vertex AI.') + + return to_object + + +def _GenerateVideosOperation_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['name']) is not None: + setv(to_object, ['name'], getv(from_object, ['name'])) + + if getv(from_object, ['metadata']) is not None: + setv(to_object, ['metadata'], getv(from_object, ['metadata'])) + + if getv(from_object, ['done']) is not None: + setv(to_object, ['done'], getv(from_object, ['done'])) + + if getv(from_object, ['error']) is not None: + setv(to_object, ['error'], getv(from_object, ['error'])) + + if getv(from_object, ['response', 'generateVideoResponse']) is not None: + setv( + to_object, + ['response'], + _GenerateVideosResponse_from_mldev( + getv(from_object, ['response', 'generateVideoResponse']), + to_object, + root_object, + ), + ) + + if getv(from_object, ['response', 'generateVideoResponse']) is not None: + setv( + to_object, + ['result'], + _GenerateVideosResponse_from_mldev( + getv(from_object, ['response', 'generateVideoResponse']), + to_object, + root_object, + ), + ) + + return to_object + + +def _GenerateVideosOperation_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['name']) is not None: + setv(to_object, ['name'], getv(from_object, ['name'])) + + if getv(from_object, ['metadata']) is not None: + setv(to_object, ['metadata'], getv(from_object, ['metadata'])) + + if getv(from_object, ['done']) is not None: + setv(to_object, ['done'], getv(from_object, ['done'])) + + if getv(from_object, ['error']) is not None: + setv(to_object, ['error'], getv(from_object, ['error'])) + + if getv(from_object, ['response']) is not None: + setv( + to_object, + ['response'], + _GenerateVideosResponse_from_vertex( + getv(from_object, ['response']), to_object, root_object + ), + ) + + if getv(from_object, ['response']) is not None: + setv( + to_object, + ['result'], + _GenerateVideosResponse_from_vertex( + getv(from_object, ['response']), to_object, root_object + ), + ) + + return to_object + + +def _GenerateVideosParameters_to_mldev( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['model']) is not None: + setv( + to_object, + ['_url', 'model'], + t.t_model(api_client, getv(from_object, ['model'])), + ) + + if getv(from_object, ['prompt']) is not None: + setv(to_object, ['instances[0]', 'prompt'], getv(from_object, ['prompt'])) + + if getv(from_object, ['image']) is not None: + setv( + to_object, + ['instances[0]', 'image'], + _Image_to_mldev(getv(from_object, ['image']), to_object, root_object), + ) + + if getv(from_object, ['video']) is not None: + setv( + to_object, + ['instances[0]', 'video'], + _Video_to_mldev(getv(from_object, ['video']), to_object, root_object), + ) + + if getv(from_object, ['source']) is not None: + _GenerateVideosSource_to_mldev( + getv(from_object, ['source']), to_object, root_object + ) + + if getv(from_object, ['config']) is not None: + _GenerateVideosConfig_to_mldev( + getv(from_object, ['config']), to_object, root_object + ) + + return to_object + + +def _GenerateVideosParameters_to_vertex( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['model']) is not None: + setv( + to_object, + ['_url', 'model'], + t.t_model(api_client, getv(from_object, ['model'])), + ) + + if getv(from_object, ['prompt']) is not None: + setv(to_object, ['instances[0]', 'prompt'], getv(from_object, ['prompt'])) + + if getv(from_object, ['image']) is not None: + setv( + to_object, + ['instances[0]', 'image'], + _Image_to_vertex(getv(from_object, ['image']), to_object, root_object), + ) + + if getv(from_object, ['video']) is not None: + setv( + to_object, + ['instances[0]', 'video'], + _Video_to_vertex(getv(from_object, ['video']), to_object, root_object), + ) + + if getv(from_object, ['source']) is not None: + _GenerateVideosSource_to_vertex( + getv(from_object, ['source']), to_object, root_object + ) + + if getv(from_object, ['config']) is not None: + _GenerateVideosConfig_to_vertex( + getv(from_object, ['config']), to_object, root_object + ) + + return to_object + + +def _GenerateVideosResponse_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['generatedSamples']) is not None: + setv( + to_object, + ['generated_videos'], + [ + _GeneratedVideo_from_mldev(item, to_object, root_object) + for item in getv(from_object, ['generatedSamples']) + ], + ) + + if getv(from_object, ['raiMediaFilteredCount']) is not None: + setv( + to_object, + ['rai_media_filtered_count'], + getv(from_object, ['raiMediaFilteredCount']), + ) + + if getv(from_object, ['raiMediaFilteredReasons']) is not None: + setv( + to_object, + ['rai_media_filtered_reasons'], + getv(from_object, ['raiMediaFilteredReasons']), + ) + + return to_object + + +def _GenerateVideosResponse_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['videos']) is not None: + setv( + to_object, + ['generated_videos'], + [ + _GeneratedVideo_from_vertex(item, to_object, root_object) + for item in getv(from_object, ['videos']) + ], + ) + + if getv(from_object, ['raiMediaFilteredCount']) is not None: + setv( + to_object, + ['rai_media_filtered_count'], + getv(from_object, ['raiMediaFilteredCount']), + ) + + if getv(from_object, ['raiMediaFilteredReasons']) is not None: + setv( + to_object, + ['rai_media_filtered_reasons'], + getv(from_object, ['raiMediaFilteredReasons']), + ) + + return to_object + + +def _GenerateVideosSource_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['prompt']) is not None: + setv( + parent_object, ['instances[0]', 'prompt'], getv(from_object, ['prompt']) + ) + + if getv(from_object, ['image']) is not None: + setv( + parent_object, + ['instances[0]', 'image'], + _Image_to_mldev(getv(from_object, ['image']), to_object, root_object), + ) + + if getv(from_object, ['video']) is not None: + setv( + parent_object, + ['instances[0]', 'video'], + _Video_to_mldev(getv(from_object, ['video']), to_object, root_object), + ) + + return to_object + + +def _GenerateVideosSource_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['prompt']) is not None: + setv( + parent_object, ['instances[0]', 'prompt'], getv(from_object, ['prompt']) + ) + + if getv(from_object, ['image']) is not None: + setv( + parent_object, + ['instances[0]', 'image'], + _Image_to_vertex(getv(from_object, ['image']), to_object, root_object), + ) + + if getv(from_object, ['video']) is not None: + setv( + parent_object, + ['instances[0]', 'video'], + _Video_to_vertex(getv(from_object, ['video']), to_object, root_object), + ) + + return to_object + + +def _GeneratedImageMask_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['_self']) is not None: + setv( + to_object, + ['mask'], + _Image_from_vertex( + getv(from_object, ['_self']), to_object, root_object + ), + ) + + if getv(from_object, ['labels']) is not None: + setv( + to_object, ['labels'], [item for item in getv(from_object, ['labels'])] + ) + + return to_object + + +def _GeneratedImage_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['_self']) is not None: + setv( + to_object, + ['image'], + _Image_from_mldev(getv(from_object, ['_self']), to_object, root_object), + ) + + if getv(from_object, ['raiFilteredReason']) is not None: + setv( + to_object, + ['rai_filtered_reason'], + getv(from_object, ['raiFilteredReason']), + ) + + if getv(from_object, ['_self']) is not None: + setv( + to_object, + ['safety_attributes'], + _SafetyAttributes_from_mldev( + getv(from_object, ['_self']), to_object, root_object + ), + ) + + return to_object + + +def _GeneratedImage_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['_self']) is not None: + setv( + to_object, + ['image'], + _Image_from_vertex( + getv(from_object, ['_self']), to_object, root_object + ), + ) + + if getv(from_object, ['raiFilteredReason']) is not None: + setv( + to_object, + ['rai_filtered_reason'], + getv(from_object, ['raiFilteredReason']), + ) + + if getv(from_object, ['_self']) is not None: + setv( + to_object, + ['safety_attributes'], + _SafetyAttributes_from_vertex( + getv(from_object, ['_self']), to_object, root_object + ), + ) + + if getv(from_object, ['prompt']) is not None: + setv(to_object, ['enhanced_prompt'], getv(from_object, ['prompt'])) + + return to_object + + +def _GeneratedVideo_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['video']) is not None: + setv( + to_object, + ['video'], + _Video_from_mldev(getv(from_object, ['video']), to_object, root_object), + ) + + return to_object + + +def _GeneratedVideo_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['_self']) is not None: + setv( + to_object, + ['video'], + _Video_from_vertex( + getv(from_object, ['_self']), to_object, root_object + ), + ) + + return to_object + + +def _GenerationConfig_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['model_selection_config']) is not None: + setv( + to_object, + ['modelConfig'], + getv(from_object, ['model_selection_config']), + ) + + if getv(from_object, ['response_json_schema']) is not None: + setv( + to_object, + ['responseJsonSchema'], + getv(from_object, ['response_json_schema']), + ) + + if getv(from_object, ['audio_timestamp']) is not None: + setv(to_object, ['audioTimestamp'], getv(from_object, ['audio_timestamp'])) + + if getv(from_object, ['candidate_count']) is not None: + setv(to_object, ['candidateCount'], getv(from_object, ['candidate_count'])) + + if getv(from_object, ['enable_affective_dialog']) is not None: + setv( + to_object, + ['enableAffectiveDialog'], + getv(from_object, ['enable_affective_dialog']), + ) + + if getv(from_object, ['frequency_penalty']) is not None: + setv( + to_object, + ['frequencyPenalty'], + getv(from_object, ['frequency_penalty']), + ) + + if getv(from_object, ['logprobs']) is not None: + setv(to_object, ['logprobs'], getv(from_object, ['logprobs'])) + + if getv(from_object, ['max_output_tokens']) is not None: + setv( + to_object, ['maxOutputTokens'], getv(from_object, ['max_output_tokens']) + ) + + if getv(from_object, ['media_resolution']) is not None: + setv( + to_object, ['mediaResolution'], getv(from_object, ['media_resolution']) + ) + + if getv(from_object, ['presence_penalty']) is not None: + setv( + to_object, ['presencePenalty'], getv(from_object, ['presence_penalty']) + ) + + if getv(from_object, ['response_logprobs']) is not None: + setv( + to_object, + ['responseLogprobs'], + getv(from_object, ['response_logprobs']), + ) + + if getv(from_object, ['response_mime_type']) is not None: + setv( + to_object, + ['responseMimeType'], + getv(from_object, ['response_mime_type']), + ) + + if getv(from_object, ['response_modalities']) is not None: + setv( + to_object, + ['responseModalities'], + getv(from_object, ['response_modalities']), + ) + + if getv(from_object, ['response_schema']) is not None: + setv(to_object, ['responseSchema'], getv(from_object, ['response_schema'])) + + if getv(from_object, ['routing_config']) is not None: + setv(to_object, ['routingConfig'], getv(from_object, ['routing_config'])) + + if getv(from_object, ['seed']) is not None: + setv(to_object, ['seed'], getv(from_object, ['seed'])) + + if getv(from_object, ['speech_config']) is not None: + setv( + to_object, + ['speechConfig'], + _SpeechConfig_to_vertex( + getv(from_object, ['speech_config']), to_object, root_object + ), + ) + + if getv(from_object, ['stop_sequences']) is not None: + setv(to_object, ['stopSequences'], getv(from_object, ['stop_sequences'])) + + if getv(from_object, ['temperature']) is not None: + setv(to_object, ['temperature'], getv(from_object, ['temperature'])) + + if getv(from_object, ['thinking_config']) is not None: + setv(to_object, ['thinkingConfig'], getv(from_object, ['thinking_config'])) + + if getv(from_object, ['top_k']) is not None: + setv(to_object, ['topK'], getv(from_object, ['top_k'])) + + if getv(from_object, ['top_p']) is not None: + setv(to_object, ['topP'], getv(from_object, ['top_p'])) + + if getv(from_object, ['enable_enhanced_civic_answers']) is not None: + raise ValueError( + 'enable_enhanced_civic_answers parameter is not supported in Vertex AI.' + ) + + return to_object + + +def _GetModelParameters_to_mldev( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['model']) is not None: + setv( + to_object, + ['_url', 'name'], + t.t_model(api_client, getv(from_object, ['model'])), + ) + + return to_object + + +def _GetModelParameters_to_vertex( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['model']) is not None: + setv( + to_object, + ['_url', 'name'], + t.t_model(api_client, getv(from_object, ['model'])), + ) + + return to_object + + +def _GoogleMaps_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['auth_config']) is not None: + setv( + to_object, + ['authConfig'], + _AuthConfig_to_mldev( + getv(from_object, ['auth_config']), to_object, root_object + ), + ) + + if getv(from_object, ['enable_widget']) is not None: + setv(to_object, ['enableWidget'], getv(from_object, ['enable_widget'])) + + return to_object + + +def _GoogleSearch_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['search_types']) is not None: + setv(to_object, ['searchTypes'], getv(from_object, ['search_types'])) + + if getv(from_object, ['blocking_confidence']) is not None: + raise ValueError( + 'blocking_confidence parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['exclude_domains']) is not None: + raise ValueError( + 'exclude_domains parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['time_range_filter']) is not None: + setv( + to_object, ['timeRangeFilter'], getv(from_object, ['time_range_filter']) + ) + + return to_object + + +def _ImageConfig_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['aspect_ratio']) is not None: + setv(to_object, ['aspectRatio'], getv(from_object, ['aspect_ratio'])) + + if getv(from_object, ['image_size']) is not None: + setv(to_object, ['imageSize'], getv(from_object, ['image_size'])) + + if getv(from_object, ['person_generation']) is not None: + raise ValueError( + 'person_generation parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['prominent_people']) is not None: + raise ValueError( + 'prominent_people parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['output_mime_type']) is not None: + raise ValueError( + 'output_mime_type parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['output_compression_quality']) is not None: + raise ValueError( + 'output_compression_quality parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['image_output_options']) is not None: + raise ValueError( + 'image_output_options parameter is not supported in Gemini API.' + ) + + return to_object + + +def _ImageConfig_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['aspect_ratio']) is not None: + setv(to_object, ['aspectRatio'], getv(from_object, ['aspect_ratio'])) + + if getv(from_object, ['image_size']) is not None: + setv(to_object, ['imageSize'], getv(from_object, ['image_size'])) + + if getv(from_object, ['person_generation']) is not None: + setv( + to_object, + ['personGeneration'], + getv(from_object, ['person_generation']), + ) + + if getv(from_object, ['prominent_people']) is not None: + setv( + to_object, ['prominentPeople'], getv(from_object, ['prominent_people']) + ) + + if getv(from_object, ['output_mime_type']) is not None: + setv( + to_object, + ['imageOutputOptions', 'mimeType'], + getv(from_object, ['output_mime_type']), + ) + + if getv(from_object, ['output_compression_quality']) is not None: + setv( + to_object, + ['imageOutputOptions', 'compressionQuality'], + getv(from_object, ['output_compression_quality']), + ) + + if getv(from_object, ['image_output_options']) is not None: + setv( + to_object, + ['imageOutputOptions'], + getv(from_object, ['image_output_options']), + ) + + return to_object + + +def _Image_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['bytesBase64Encoded']) is not None: + setv( + to_object, + ['image_bytes'], + base_t.t_bytes(getv(from_object, ['bytesBase64Encoded'])), + ) + + if getv(from_object, ['mimeType']) is not None: + setv(to_object, ['mime_type'], getv(from_object, ['mimeType'])) + + return to_object + + +def _Image_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['gcsUri']) is not None: + setv(to_object, ['gcs_uri'], getv(from_object, ['gcsUri'])) + + if getv(from_object, ['bytesBase64Encoded']) is not None: + setv( + to_object, + ['image_bytes'], + base_t.t_bytes(getv(from_object, ['bytesBase64Encoded'])), + ) + + if getv(from_object, ['mimeType']) is not None: + setv(to_object, ['mime_type'], getv(from_object, ['mimeType'])) + + return to_object + + +def _Image_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['gcs_uri']) is not None: + raise ValueError('gcs_uri parameter is not supported in Gemini API.') + + if getv(from_object, ['image_bytes']) is not None: + setv( + to_object, + ['bytesBase64Encoded'], + base_t.t_bytes(getv(from_object, ['image_bytes'])), + ) + + if getv(from_object, ['mime_type']) is not None: + setv(to_object, ['mimeType'], getv(from_object, ['mime_type'])) + + return to_object + + +def _Image_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['gcs_uri']) is not None: + setv(to_object, ['gcsUri'], getv(from_object, ['gcs_uri'])) + + if getv(from_object, ['image_bytes']) is not None: + setv( + to_object, + ['bytesBase64Encoded'], + base_t.t_bytes(getv(from_object, ['image_bytes'])), + ) + + if getv(from_object, ['mime_type']) is not None: + setv(to_object, ['mimeType'], getv(from_object, ['mime_type'])) + + return to_object + + +def _ListModelsConfig_to_mldev( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['page_size']) is not None: + setv( + parent_object, ['_query', 'pageSize'], getv(from_object, ['page_size']) + ) + + if getv(from_object, ['page_token']) is not None: + setv( + parent_object, + ['_query', 'pageToken'], + getv(from_object, ['page_token']), + ) + + if getv(from_object, ['filter']) is not None: + setv(parent_object, ['_query', 'filter'], getv(from_object, ['filter'])) + + if getv(from_object, ['query_base']) is not None: + setv( + parent_object, + ['_url', 'models_url'], + t.t_models_url(api_client, getv(from_object, ['query_base'])), + ) + + return to_object + + +def _ListModelsConfig_to_vertex( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['page_size']) is not None: + setv( + parent_object, ['_query', 'pageSize'], getv(from_object, ['page_size']) + ) + + if getv(from_object, ['page_token']) is not None: + setv( + parent_object, + ['_query', 'pageToken'], + getv(from_object, ['page_token']), + ) + + if getv(from_object, ['filter']) is not None: + setv(parent_object, ['_query', 'filter'], getv(from_object, ['filter'])) + + if getv(from_object, ['query_base']) is not None: + setv( + parent_object, + ['_url', 'models_url'], + t.t_models_url(api_client, getv(from_object, ['query_base'])), + ) + + return to_object + + +def _ListModelsParameters_to_mldev( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['config']) is not None: + _ListModelsConfig_to_mldev( + api_client, getv(from_object, ['config']), to_object, root_object + ) + + return to_object + + +def _ListModelsParameters_to_vertex( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['config']) is not None: + _ListModelsConfig_to_vertex( + api_client, getv(from_object, ['config']), to_object, root_object + ) + + return to_object + + +def _ListModelsResponse_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['sdkHttpResponse']) is not None: + setv( + to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse']) + ) + + if getv(from_object, ['nextPageToken']) is not None: + setv(to_object, ['next_page_token'], getv(from_object, ['nextPageToken'])) + + if getv(from_object, ['_self']) is not None: + setv( + to_object, + ['models'], + [ + _Model_from_mldev(item, to_object, root_object) + for item in t.t_extract_models(getv(from_object, ['_self'])) + ], + ) + + return to_object + + +def _ListModelsResponse_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['sdkHttpResponse']) is not None: + setv( + to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse']) + ) + + if getv(from_object, ['nextPageToken']) is not None: + setv(to_object, ['next_page_token'], getv(from_object, ['nextPageToken'])) + + if getv(from_object, ['_self']) is not None: + setv( + to_object, + ['models'], + [ + _Model_from_vertex(item, to_object, root_object) + for item in t.t_extract_models(getv(from_object, ['_self'])) + ], + ) + + return to_object + + +def _MaskReferenceConfig_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['mask_mode']) is not None: + setv(to_object, ['maskMode'], getv(from_object, ['mask_mode'])) + + if getv(from_object, ['segmentation_classes']) is not None: + setv( + to_object, ['maskClasses'], getv(from_object, ['segmentation_classes']) + ) + + if getv(from_object, ['mask_dilation']) is not None: + setv(to_object, ['dilation'], getv(from_object, ['mask_dilation'])) + + return to_object + + +def _Model_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['name']) is not None: + setv(to_object, ['name'], getv(from_object, ['name'])) + + if getv(from_object, ['displayName']) is not None: + setv(to_object, ['display_name'], getv(from_object, ['displayName'])) + + if getv(from_object, ['description']) is not None: + setv(to_object, ['description'], getv(from_object, ['description'])) + + if getv(from_object, ['version']) is not None: + setv(to_object, ['version'], getv(from_object, ['version'])) + + if getv(from_object, ['_self']) is not None: + setv(to_object, ['tuned_model_info'], getv(from_object, ['_self'])) + + if getv(from_object, ['inputTokenLimit']) is not None: + setv( + to_object, ['input_token_limit'], getv(from_object, ['inputTokenLimit']) + ) + + if getv(from_object, ['outputTokenLimit']) is not None: + setv( + to_object, + ['output_token_limit'], + getv(from_object, ['outputTokenLimit']), + ) + + if getv(from_object, ['supportedGenerationMethods']) is not None: + setv( + to_object, + ['supported_actions'], + getv(from_object, ['supportedGenerationMethods']), + ) + + if getv(from_object, ['temperature']) is not None: + setv(to_object, ['temperature'], getv(from_object, ['temperature'])) + + if getv(from_object, ['maxTemperature']) is not None: + setv(to_object, ['max_temperature'], getv(from_object, ['maxTemperature'])) + + if getv(from_object, ['topP']) is not None: + setv(to_object, ['top_p'], getv(from_object, ['topP'])) + + if getv(from_object, ['topK']) is not None: + setv(to_object, ['top_k'], getv(from_object, ['topK'])) + + if getv(from_object, ['thinking']) is not None: + setv(to_object, ['thinking'], getv(from_object, ['thinking'])) + + return to_object + + +def _Model_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['name']) is not None: + setv(to_object, ['name'], getv(from_object, ['name'])) + + if getv(from_object, ['displayName']) is not None: + setv(to_object, ['display_name'], getv(from_object, ['displayName'])) + + if getv(from_object, ['description']) is not None: + setv(to_object, ['description'], getv(from_object, ['description'])) + + if getv(from_object, ['versionId']) is not None: + setv(to_object, ['version'], getv(from_object, ['versionId'])) + + if getv(from_object, ['deployedModels']) is not None: + setv( + to_object, + ['endpoints'], + [ + _Endpoint_from_vertex(item, to_object, root_object) + for item in getv(from_object, ['deployedModels']) + ], + ) + + if getv(from_object, ['labels']) is not None: + setv(to_object, ['labels'], getv(from_object, ['labels'])) + + if getv(from_object, ['_self']) is not None: + setv( + to_object, + ['tuned_model_info'], + _TunedModelInfo_from_vertex( + getv(from_object, ['_self']), to_object, root_object + ), + ) + + if getv(from_object, ['defaultCheckpointId']) is not None: + setv( + to_object, + ['default_checkpoint_id'], + getv(from_object, ['defaultCheckpointId']), + ) + + if getv(from_object, ['checkpoints']) is not None: + setv( + to_object, + ['checkpoints'], + [item for item in getv(from_object, ['checkpoints'])], + ) + + return to_object + + +def _MultiSpeakerVoiceConfig_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['speaker_voice_configs']) is not None: + setv( + to_object, + ['speakerVoiceConfigs'], + [ + _SpeakerVoiceConfig_to_vertex(item, to_object, root_object) + for item in getv(from_object, ['speaker_voice_configs']) + ], + ) + + return to_object + + +def _Part_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['media_resolution']) is not None: + setv( + to_object, ['mediaResolution'], getv(from_object, ['media_resolution']) + ) + + if getv(from_object, ['code_execution_result']) is not None: + setv( + to_object, + ['codeExecutionResult'], + getv(from_object, ['code_execution_result']), + ) + + if getv(from_object, ['executable_code']) is not None: + setv(to_object, ['executableCode'], getv(from_object, ['executable_code'])) + + if getv(from_object, ['file_data']) is not None: + setv( + to_object, + ['fileData'], + _FileData_to_mldev( + getv(from_object, ['file_data']), to_object, root_object + ), + ) + + if getv(from_object, ['function_call']) is not None: + setv( + to_object, + ['functionCall'], + _FunctionCall_to_mldev( + getv(from_object, ['function_call']), to_object, root_object + ), + ) + + if getv(from_object, ['function_response']) is not None: + setv( + to_object, + ['functionResponse'], + getv(from_object, ['function_response']), + ) + + if getv(from_object, ['inline_data']) is not None: + setv( + to_object, + ['inlineData'], + _Blob_to_mldev( + getv(from_object, ['inline_data']), to_object, root_object + ), + ) + + if getv(from_object, ['text']) is not None: + setv(to_object, ['text'], getv(from_object, ['text'])) + + if getv(from_object, ['thought']) is not None: + setv(to_object, ['thought'], getv(from_object, ['thought'])) + + if getv(from_object, ['thought_signature']) is not None: + setv( + to_object, + ['thoughtSignature'], + getv(from_object, ['thought_signature']), + ) + + if getv(from_object, ['video_metadata']) is not None: + setv(to_object, ['videoMetadata'], getv(from_object, ['video_metadata'])) + + if getv(from_object, ['tool_call']) is not None: + setv(to_object, ['toolCall'], getv(from_object, ['tool_call'])) + + if getv(from_object, ['tool_response']) is not None: + setv(to_object, ['toolResponse'], getv(from_object, ['tool_response'])) + + if getv(from_object, ['part_metadata']) is not None: + setv(to_object, ['partMetadata'], getv(from_object, ['part_metadata'])) + + return to_object + + +def _Part_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['media_resolution']) is not None: + setv( + to_object, ['mediaResolution'], getv(from_object, ['media_resolution']) + ) + + if getv(from_object, ['code_execution_result']) is not None: + setv( + to_object, + ['codeExecutionResult'], + getv(from_object, ['code_execution_result']), + ) + + if getv(from_object, ['executable_code']) is not None: + setv(to_object, ['executableCode'], getv(from_object, ['executable_code'])) + + if getv(from_object, ['file_data']) is not None: + setv(to_object, ['fileData'], getv(from_object, ['file_data'])) + + if getv(from_object, ['function_call']) is not None: + setv(to_object, ['functionCall'], getv(from_object, ['function_call'])) + + if getv(from_object, ['function_response']) is not None: + setv( + to_object, + ['functionResponse'], + getv(from_object, ['function_response']), + ) + + if getv(from_object, ['inline_data']) is not None: + setv(to_object, ['inlineData'], getv(from_object, ['inline_data'])) + + if getv(from_object, ['text']) is not None: + setv(to_object, ['text'], getv(from_object, ['text'])) + + if getv(from_object, ['thought']) is not None: + setv(to_object, ['thought'], getv(from_object, ['thought'])) + + if getv(from_object, ['thought_signature']) is not None: + setv( + to_object, + ['thoughtSignature'], + getv(from_object, ['thought_signature']), + ) + + if getv(from_object, ['video_metadata']) is not None: + setv(to_object, ['videoMetadata'], getv(from_object, ['video_metadata'])) + + if getv(from_object, ['tool_call']) is not None: + raise ValueError('tool_call parameter is not supported in Vertex AI.') + + if getv(from_object, ['tool_response']) is not None: + raise ValueError('tool_response parameter is not supported in Vertex AI.') + + if getv(from_object, ['part_metadata']) is not None: + raise ValueError('part_metadata parameter is not supported in Vertex AI.') + + return to_object + + +def _ProductImage_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['product_image']) is not None: + setv( + to_object, + ['image'], + _Image_to_vertex( + getv(from_object, ['product_image']), to_object, root_object + ), + ) + + return to_object + + +def _RecontextImageConfig_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['number_of_images']) is not None: + setv( + parent_object, + ['parameters', 'sampleCount'], + getv(from_object, ['number_of_images']), + ) + + if getv(from_object, ['base_steps']) is not None: + setv( + parent_object, + ['parameters', 'baseSteps'], + getv(from_object, ['base_steps']), + ) + + if getv(from_object, ['output_gcs_uri']) is not None: + setv( + parent_object, + ['parameters', 'storageUri'], + getv(from_object, ['output_gcs_uri']), + ) + + if getv(from_object, ['seed']) is not None: + setv(parent_object, ['parameters', 'seed'], getv(from_object, ['seed'])) + + if getv(from_object, ['safety_filter_level']) is not None: + setv( + parent_object, + ['parameters', 'safetySetting'], + getv(from_object, ['safety_filter_level']), + ) + + if getv(from_object, ['person_generation']) is not None: + setv( + parent_object, + ['parameters', 'personGeneration'], + getv(from_object, ['person_generation']), + ) + + if getv(from_object, ['add_watermark']) is not None: + setv( + parent_object, + ['parameters', 'addWatermark'], + getv(from_object, ['add_watermark']), + ) + + if getv(from_object, ['output_mime_type']) is not None: + setv( + parent_object, + ['parameters', 'outputOptions', 'mimeType'], + getv(from_object, ['output_mime_type']), + ) + + if getv(from_object, ['output_compression_quality']) is not None: + setv( + parent_object, + ['parameters', 'outputOptions', 'compressionQuality'], + getv(from_object, ['output_compression_quality']), + ) + + if getv(from_object, ['enhance_prompt']) is not None: + setv( + parent_object, + ['parameters', 'enhancePrompt'], + getv(from_object, ['enhance_prompt']), + ) + + if getv(from_object, ['labels']) is not None: + setv(parent_object, ['labels'], getv(from_object, ['labels'])) + + return to_object + + +def _RecontextImageParameters_to_vertex( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['model']) is not None: + setv( + to_object, + ['_url', 'model'], + t.t_model(api_client, getv(from_object, ['model'])), + ) + + if getv(from_object, ['source']) is not None: + _RecontextImageSource_to_vertex( + getv(from_object, ['source']), to_object, root_object + ) + + if getv(from_object, ['config']) is not None: + _RecontextImageConfig_to_vertex( + getv(from_object, ['config']), to_object, root_object + ) + + return to_object + + +def _RecontextImageResponse_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['predictions']) is not None: + setv( + to_object, + ['generated_images'], + [ + _GeneratedImage_from_vertex(item, to_object, root_object) + for item in getv(from_object, ['predictions']) + ], + ) + + return to_object + + +def _RecontextImageSource_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['prompt']) is not None: + setv( + parent_object, ['instances[0]', 'prompt'], getv(from_object, ['prompt']) + ) + + if getv(from_object, ['person_image']) is not None: + setv( + parent_object, + ['instances[0]', 'personImage', 'image'], + _Image_to_vertex( + getv(from_object, ['person_image']), to_object, root_object + ), + ) + + if getv(from_object, ['product_images']) is not None: + setv( + parent_object, + ['instances[0]', 'productImages'], + [ + _ProductImage_to_vertex(item, to_object, root_object) + for item in getv(from_object, ['product_images']) + ], + ) + + return to_object + + +def _ReferenceImageAPI_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['reference_image']) is not None: + setv( + to_object, + ['referenceImage'], + _Image_to_vertex( + getv(from_object, ['reference_image']), to_object, root_object + ), + ) + + if getv(from_object, ['reference_id']) is not None: + setv(to_object, ['referenceId'], getv(from_object, ['reference_id'])) + + if getv(from_object, ['reference_type']) is not None: + setv(to_object, ['referenceType'], getv(from_object, ['reference_type'])) + + if getv(from_object, ['mask_image_config']) is not None: + setv( + to_object, + ['maskImageConfig'], + _MaskReferenceConfig_to_vertex( + getv(from_object, ['mask_image_config']), to_object, root_object + ), + ) + + if getv(from_object, ['control_image_config']) is not None: + setv( + to_object, + ['controlImageConfig'], + _ControlReferenceConfig_to_vertex( + getv(from_object, ['control_image_config']), to_object, root_object + ), + ) + + if getv(from_object, ['style_image_config']) is not None: + setv( + to_object, + ['styleImageConfig'], + getv(from_object, ['style_image_config']), + ) + + if getv(from_object, ['subject_image_config']) is not None: + setv( + to_object, + ['subjectImageConfig'], + getv(from_object, ['subject_image_config']), + ) + + return to_object + + +def _ReplicatedVoiceConfig_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['mime_type']) is not None: + setv(to_object, ['mimeType'], getv(from_object, ['mime_type'])) + + if getv(from_object, ['voice_sample_audio']) is not None: + setv( + to_object, + ['voiceSampleAudio'], + getv(from_object, ['voice_sample_audio']), + ) + + if getv(from_object, ['consent_audio']) is not None: + raise ValueError('consent_audio parameter is not supported in Vertex AI.') + + if getv(from_object, ['voice_consent_signature']) is not None: + raise ValueError( + 'voice_consent_signature parameter is not supported in Vertex AI.' + ) + + return to_object + + +def _SafetyAttributes_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['safetyAttributes', 'categories']) is not None: + setv( + to_object, + ['categories'], + getv(from_object, ['safetyAttributes', 'categories']), + ) + + if getv(from_object, ['safetyAttributes', 'scores']) is not None: + setv( + to_object, ['scores'], getv(from_object, ['safetyAttributes', 'scores']) + ) + + if getv(from_object, ['contentType']) is not None: + setv(to_object, ['content_type'], getv(from_object, ['contentType'])) + + return to_object + + +def _SafetyAttributes_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['safetyAttributes', 'categories']) is not None: + setv( + to_object, + ['categories'], + getv(from_object, ['safetyAttributes', 'categories']), + ) + + if getv(from_object, ['safetyAttributes', 'scores']) is not None: + setv( + to_object, ['scores'], getv(from_object, ['safetyAttributes', 'scores']) + ) + + if getv(from_object, ['contentType']) is not None: + setv(to_object, ['content_type'], getv(from_object, ['contentType'])) + + return to_object + + +def _SafetySetting_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['category']) is not None: + setv(to_object, ['category'], getv(from_object, ['category'])) + + if getv(from_object, ['method']) is not None: + raise ValueError('method parameter is not supported in Gemini API.') + + if getv(from_object, ['threshold']) is not None: + setv(to_object, ['threshold'], getv(from_object, ['threshold'])) + + return to_object + + +def _ScribbleImage_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['image']) is not None: + setv( + to_object, + ['image'], + _Image_to_vertex(getv(from_object, ['image']), to_object, root_object), + ) + + return to_object + + +def _SegmentImageConfig_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['mode']) is not None: + setv(parent_object, ['parameters', 'mode'], getv(from_object, ['mode'])) + + if getv(from_object, ['max_predictions']) is not None: + setv( + parent_object, + ['parameters', 'maxPredictions'], + getv(from_object, ['max_predictions']), + ) + + if getv(from_object, ['confidence_threshold']) is not None: + setv( + parent_object, + ['parameters', 'confidenceThreshold'], + getv(from_object, ['confidence_threshold']), + ) + + if getv(from_object, ['mask_dilation']) is not None: + setv( + parent_object, + ['parameters', 'maskDilation'], + getv(from_object, ['mask_dilation']), + ) + + if getv(from_object, ['binary_color_threshold']) is not None: + setv( + parent_object, + ['parameters', 'binaryColorThreshold'], + getv(from_object, ['binary_color_threshold']), + ) + + if getv(from_object, ['labels']) is not None: + setv(parent_object, ['labels'], getv(from_object, ['labels'])) + + return to_object + + +def _SegmentImageParameters_to_vertex( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['model']) is not None: + setv( + to_object, + ['_url', 'model'], + t.t_model(api_client, getv(from_object, ['model'])), + ) + + if getv(from_object, ['source']) is not None: + _SegmentImageSource_to_vertex( + getv(from_object, ['source']), to_object, root_object + ) + + if getv(from_object, ['config']) is not None: + _SegmentImageConfig_to_vertex( + getv(from_object, ['config']), to_object, root_object + ) + + return to_object + + +def _SegmentImageResponse_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['predictions']) is not None: + setv( + to_object, + ['generated_masks'], + [ + _GeneratedImageMask_from_vertex(item, to_object, root_object) + for item in getv(from_object, ['predictions']) + ], + ) + + return to_object + + +def _SegmentImageSource_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['prompt']) is not None: + setv( + parent_object, ['instances[0]', 'prompt'], getv(from_object, ['prompt']) + ) + + if getv(from_object, ['image']) is not None: + setv( + parent_object, + ['instances[0]', 'image'], + _Image_to_vertex(getv(from_object, ['image']), to_object, root_object), + ) + + if getv(from_object, ['scribble_image']) is not None: + setv( + parent_object, + ['instances[0]', 'scribble'], + _ScribbleImage_to_vertex( + getv(from_object, ['scribble_image']), to_object, root_object + ), + ) + + return to_object + + +def _SpeakerVoiceConfig_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['speaker']) is not None: + setv(to_object, ['speaker'], getv(from_object, ['speaker'])) + + if getv(from_object, ['voice_config']) is not None: + setv( + to_object, + ['voiceConfig'], + _VoiceConfig_to_vertex( + getv(from_object, ['voice_config']), to_object, root_object + ), + ) + + return to_object + + +def _SpeechConfig_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['voice_config']) is not None: + setv( + to_object, + ['voiceConfig'], + _VoiceConfig_to_vertex( + getv(from_object, ['voice_config']), to_object, root_object + ), + ) + + if getv(from_object, ['language_code']) is not None: + setv(to_object, ['languageCode'], getv(from_object, ['language_code'])) + + if getv(from_object, ['multi_speaker_voice_config']) is not None: + setv( + to_object, + ['multiSpeakerVoiceConfig'], + _MultiSpeakerVoiceConfig_to_vertex( + getv(from_object, ['multi_speaker_voice_config']), + to_object, + root_object, + ), + ) + + return to_object + + +def _ToolConfig_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['retrieval_config']) is not None: + setv( + to_object, ['retrievalConfig'], getv(from_object, ['retrieval_config']) + ) + + if getv(from_object, ['function_calling_config']) is not None: + setv( + to_object, + ['functionCallingConfig'], + _FunctionCallingConfig_to_mldev( + getv(from_object, ['function_calling_config']), + to_object, + root_object, + ), + ) + + if getv(from_object, ['include_server_side_tool_invocations']) is not None: + setv( + to_object, + ['includeServerSideToolInvocations'], + getv(from_object, ['include_server_side_tool_invocations']), + ) + + return to_object + + +def _ToolConfig_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['retrieval_config']) is not None: + setv( + to_object, ['retrievalConfig'], getv(from_object, ['retrieval_config']) + ) + + if getv(from_object, ['function_calling_config']) is not None: + setv( + to_object, + ['functionCallingConfig'], + getv(from_object, ['function_calling_config']), + ) + + if getv(from_object, ['include_server_side_tool_invocations']) is not None: + raise ValueError( + 'include_server_side_tool_invocations parameter is not supported in' + ' Vertex AI.' + ) + + return to_object + + +def _Tool_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['retrieval']) is not None: + raise ValueError('retrieval parameter is not supported in Gemini API.') + + if getv(from_object, ['computer_use']) is not None: + setv(to_object, ['computerUse'], getv(from_object, ['computer_use'])) + + if getv(from_object, ['file_search']) is not None: + setv(to_object, ['fileSearch'], getv(from_object, ['file_search'])) + + if getv(from_object, ['google_search']) is not None: + setv( + to_object, + ['googleSearch'], + _GoogleSearch_to_mldev( + getv(from_object, ['google_search']), to_object, root_object + ), + ) + + if getv(from_object, ['google_maps']) is not None: + setv( + to_object, + ['googleMaps'], + _GoogleMaps_to_mldev( + getv(from_object, ['google_maps']), to_object, root_object + ), + ) + + if getv(from_object, ['code_execution']) is not None: + setv(to_object, ['codeExecution'], getv(from_object, ['code_execution'])) + + if getv(from_object, ['enterprise_web_search']) is not None: + raise ValueError( + 'enterprise_web_search parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['function_declarations']) is not None: + setv( + to_object, + ['functionDeclarations'], + [item for item in getv(from_object, ['function_declarations'])], + ) + + if getv(from_object, ['google_search_retrieval']) is not None: + setv( + to_object, + ['googleSearchRetrieval'], + getv(from_object, ['google_search_retrieval']), + ) + + if getv(from_object, ['parallel_ai_search']) is not None: + raise ValueError( + 'parallel_ai_search parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['url_context']) is not None: + setv(to_object, ['urlContext'], getv(from_object, ['url_context'])) + + if getv(from_object, ['mcp_servers']) is not None: + setv( + to_object, + ['mcpServers'], + [item for item in getv(from_object, ['mcp_servers'])], + ) + + return to_object + + +def _Tool_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['retrieval']) is not None: + setv(to_object, ['retrieval'], getv(from_object, ['retrieval'])) + + if getv(from_object, ['computer_use']) is not None: + setv(to_object, ['computerUse'], getv(from_object, ['computer_use'])) + + if getv(from_object, ['file_search']) is not None: + raise ValueError('file_search parameter is not supported in Vertex AI.') + + if getv(from_object, ['google_search']) is not None: + setv(to_object, ['googleSearch'], getv(from_object, ['google_search'])) + + if getv(from_object, ['google_maps']) is not None: + setv(to_object, ['googleMaps'], getv(from_object, ['google_maps'])) + + if getv(from_object, ['code_execution']) is not None: + setv(to_object, ['codeExecution'], getv(from_object, ['code_execution'])) + + if getv(from_object, ['enterprise_web_search']) is not None: + setv( + to_object, + ['enterpriseWebSearch'], + getv(from_object, ['enterprise_web_search']), + ) + + if getv(from_object, ['function_declarations']) is not None: + setv( + to_object, + ['functionDeclarations'], + [ + _FunctionDeclaration_to_vertex(item, to_object, root_object) + for item in getv(from_object, ['function_declarations']) + ], + ) + + if getv(from_object, ['google_search_retrieval']) is not None: + setv( + to_object, + ['googleSearchRetrieval'], + getv(from_object, ['google_search_retrieval']), + ) + + if getv(from_object, ['parallel_ai_search']) is not None: + setv( + to_object, + ['parallelAiSearch'], + getv(from_object, ['parallel_ai_search']), + ) + + if getv(from_object, ['url_context']) is not None: + setv(to_object, ['urlContext'], getv(from_object, ['url_context'])) + + if getv(from_object, ['mcp_servers']) is not None: + raise ValueError('mcp_servers parameter is not supported in Vertex AI.') + + return to_object + + +def _TunedModelInfo_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if ( + getv(from_object, ['labels', 'google-vertex-llm-tuning-base-model-id']) + is not None + ): + setv( + to_object, + ['base_model'], + getv(from_object, ['labels', 'google-vertex-llm-tuning-base-model-id']), + ) + + if getv(from_object, ['createTime']) is not None: + setv(to_object, ['create_time'], getv(from_object, ['createTime'])) + + if getv(from_object, ['updateTime']) is not None: + setv(to_object, ['update_time'], getv(from_object, ['updateTime'])) + + return to_object + + +def _UpdateModelConfig_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['display_name']) is not None: + setv(parent_object, ['displayName'], getv(from_object, ['display_name'])) + + if getv(from_object, ['description']) is not None: + setv(parent_object, ['description'], getv(from_object, ['description'])) + + if getv(from_object, ['default_checkpoint_id']) is not None: + setv( + parent_object, + ['defaultCheckpointId'], + getv(from_object, ['default_checkpoint_id']), + ) + + return to_object + + +def _UpdateModelConfig_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['display_name']) is not None: + setv(parent_object, ['displayName'], getv(from_object, ['display_name'])) + + if getv(from_object, ['description']) is not None: + setv(parent_object, ['description'], getv(from_object, ['description'])) + + if getv(from_object, ['default_checkpoint_id']) is not None: + setv( + parent_object, + ['defaultCheckpointId'], + getv(from_object, ['default_checkpoint_id']), + ) + + return to_object + + +def _UpdateModelParameters_to_mldev( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['model']) is not None: + setv( + to_object, + ['_url', 'name'], + t.t_model(api_client, getv(from_object, ['model'])), + ) + + if getv(from_object, ['config']) is not None: + _UpdateModelConfig_to_mldev( + getv(from_object, ['config']), to_object, root_object + ) + + return to_object + + +def _UpdateModelParameters_to_vertex( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['model']) is not None: + setv( + to_object, + ['_url', 'model'], + t.t_model(api_client, getv(from_object, ['model'])), + ) + + if getv(from_object, ['config']) is not None: + _UpdateModelConfig_to_vertex( + getv(from_object, ['config']), to_object, root_object + ) + + return to_object + + +def _UpscaleImageAPIConfig_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['output_gcs_uri']) is not None: + setv( + parent_object, + ['parameters', 'storageUri'], + getv(from_object, ['output_gcs_uri']), + ) + + if getv(from_object, ['safety_filter_level']) is not None: + setv( + parent_object, + ['parameters', 'safetySetting'], + getv(from_object, ['safety_filter_level']), + ) + + if getv(from_object, ['person_generation']) is not None: + setv( + parent_object, + ['parameters', 'personGeneration'], + getv(from_object, ['person_generation']), + ) + + if getv(from_object, ['include_rai_reason']) is not None: + setv( + parent_object, + ['parameters', 'includeRaiReason'], + getv(from_object, ['include_rai_reason']), + ) + + if getv(from_object, ['output_mime_type']) is not None: + setv( + parent_object, + ['parameters', 'outputOptions', 'mimeType'], + getv(from_object, ['output_mime_type']), + ) + + if getv(from_object, ['output_compression_quality']) is not None: + setv( + parent_object, + ['parameters', 'outputOptions', 'compressionQuality'], + getv(from_object, ['output_compression_quality']), + ) + + if getv(from_object, ['enhance_input_image']) is not None: + setv( + parent_object, + ['parameters', 'upscaleConfig', 'enhanceInputImage'], + getv(from_object, ['enhance_input_image']), + ) + + if getv(from_object, ['image_preservation_factor']) is not None: + setv( + parent_object, + ['parameters', 'upscaleConfig', 'imagePreservationFactor'], + getv(from_object, ['image_preservation_factor']), + ) + + if getv(from_object, ['labels']) is not None: + setv(parent_object, ['labels'], getv(from_object, ['labels'])) + + if getv(from_object, ['number_of_images']) is not None: + setv( + parent_object, + ['parameters', 'sampleCount'], + getv(from_object, ['number_of_images']), + ) + + if getv(from_object, ['mode']) is not None: + setv(parent_object, ['parameters', 'mode'], getv(from_object, ['mode'])) + + return to_object + + +def _UpscaleImageAPIParameters_to_vertex( + api_client: BaseApiClient, + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['model']) is not None: + setv( + to_object, + ['_url', 'model'], + t.t_model(api_client, getv(from_object, ['model'])), + ) + + if getv(from_object, ['image']) is not None: + setv( + to_object, + ['instances[0]', 'image'], + _Image_to_vertex(getv(from_object, ['image']), to_object, root_object), + ) + + if getv(from_object, ['upscale_factor']) is not None: + setv( + to_object, + ['parameters', 'upscaleConfig', 'upscaleFactor'], + getv(from_object, ['upscale_factor']), + ) + + if getv(from_object, ['config']) is not None: + _UpscaleImageAPIConfig_to_vertex( + getv(from_object, ['config']), to_object, root_object + ) + + return to_object + + +def _UpscaleImageResponse_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['sdkHttpResponse']) is not None: + setv( + to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse']) + ) + + if getv(from_object, ['predictions']) is not None: + setv( + to_object, + ['generated_images'], + [ + _GeneratedImage_from_vertex(item, to_object, root_object) + for item in getv(from_object, ['predictions']) + ], + ) + + return to_object + + +def _VideoGenerationMask_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['image']) is not None: + setv( + to_object, + ['_self'], + _Image_to_vertex(getv(from_object, ['image']), to_object, root_object), + ) + + if getv(from_object, ['mask_mode']) is not None: + setv(to_object, ['maskMode'], getv(from_object, ['mask_mode'])) + + return to_object + + +def _VideoGenerationReferenceImage_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['image']) is not None: + setv( + to_object, + ['image'], + _Image_to_mldev(getv(from_object, ['image']), to_object, root_object), + ) + + if getv(from_object, ['reference_type']) is not None: + _VideoGenerationReferenceType_to_mldev_enum_validate( + getv(from_object, ['reference_type']) + ) + setv(to_object, ['referenceType'], getv(from_object, ['reference_type'])) + + return to_object + + +def _VideoGenerationReferenceImage_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['image']) is not None: + setv( + to_object, + ['image'], + _Image_to_vertex(getv(from_object, ['image']), to_object, root_object), + ) + + if getv(from_object, ['reference_type']) is not None: + setv(to_object, ['referenceType'], getv(from_object, ['reference_type'])) + + return to_object + + +def _Video_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['uri']) is not None: + setv(to_object, ['uri'], getv(from_object, ['uri'])) + + if getv(from_object, ['encodedVideo']) is not None: + setv( + to_object, + ['video_bytes'], + base_t.t_bytes(getv(from_object, ['encodedVideo'])), + ) + + if getv(from_object, ['encoding']) is not None: + setv(to_object, ['mime_type'], getv(from_object, ['encoding'])) + + return to_object + + +def _Video_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['gcsUri']) is not None: + setv(to_object, ['uri'], getv(from_object, ['gcsUri'])) + + if getv(from_object, ['bytesBase64Encoded']) is not None: + setv( + to_object, + ['video_bytes'], + base_t.t_bytes(getv(from_object, ['bytesBase64Encoded'])), + ) + + if getv(from_object, ['mimeType']) is not None: + setv(to_object, ['mime_type'], getv(from_object, ['mimeType'])) + + return to_object + + +def _Video_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['uri']) is not None: + setv(to_object, ['uri'], getv(from_object, ['uri'])) + + if getv(from_object, ['video_bytes']) is not None: + setv( + to_object, + ['encodedVideo'], + base_t.t_bytes(getv(from_object, ['video_bytes'])), + ) + + if getv(from_object, ['mime_type']) is not None: + setv(to_object, ['encoding'], getv(from_object, ['mime_type'])) + + return to_object + + +def _Video_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['uri']) is not None: + setv(to_object, ['gcsUri'], getv(from_object, ['uri'])) + + if getv(from_object, ['video_bytes']) is not None: + setv( + to_object, + ['bytesBase64Encoded'], + base_t.t_bytes(getv(from_object, ['video_bytes'])), + ) + + if getv(from_object, ['mime_type']) is not None: + setv(to_object, ['mimeType'], getv(from_object, ['mime_type'])) + + return to_object + + +def _VoiceConfig_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['replicated_voice_config']) is not None: + setv( + to_object, + ['replicatedVoiceConfig'], + _ReplicatedVoiceConfig_to_vertex( + getv(from_object, ['replicated_voice_config']), + to_object, + root_object, + ), + ) + + if getv(from_object, ['prebuilt_voice_config']) is not None: + setv( + to_object, + ['prebuiltVoiceConfig'], + getv(from_object, ['prebuilt_voice_config']), + ) + + return to_object + + +class Models(_api_module.BaseModule): + + def _generate_content( + self, + *, + model: str, + contents: Union[types.ContentListUnion, types.ContentListUnionDict], + config: Optional[types.GenerateContentConfigOrDict] = None, + ) -> types.GenerateContentResponse: + parameter_model = types._GenerateContentParameters( + model=model, + contents=contents, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _GenerateContentParameters_to_vertex( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{model}:generateContent'.format_map(request_url_dict) + else: + path = '{model}:generateContent' + else: + request_dict = _GenerateContentParameters_to_mldev( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{model}:generateContent'.format_map(request_url_dict) + else: + path = '{model}:generateContent' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request( + 'post', path, request_dict, http_options + ) + + if config is not None and getattr( + config, 'should_return_http_response', None + ): + return_value = types.GenerateContentResponse(sdk_http_response=response) + self._api_client._verify_response(return_value) + return return_value + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _GenerateContentResponse_from_vertex( + response_dict, None, parameter_model + ) + + if not self._api_client.vertexai: + response_dict = _GenerateContentResponse_from_mldev( + response_dict, None, parameter_model + ) + + return_value = types.GenerateContentResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + return_value.sdk_http_response = types.HttpResponse( + headers=response.headers + ) + self._api_client._verify_response(return_value) + return return_value + + def _generate_content_stream( + self, + *, + model: str, + contents: Union[types.ContentListUnion, types.ContentListUnionDict], + config: Optional[types.GenerateContentConfigOrDict] = None, + ) -> Iterator[types.GenerateContentResponse]: + parameter_model = types._GenerateContentParameters( + model=model, + contents=contents, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _GenerateContentParameters_to_vertex( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{model}:streamGenerateContent?alt=sse'.format_map( + request_url_dict + ) + else: + path = '{model}:streamGenerateContent?alt=sse' + else: + request_dict = _GenerateContentParameters_to_mldev( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{model}:streamGenerateContent?alt=sse'.format_map( + request_url_dict + ) + else: + path = '{model}:streamGenerateContent?alt=sse' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + if config is not None and getattr( + config, 'should_return_http_response', None + ): + raise ValueError( + 'Accessing the raw HTTP response is not supported in streaming' + ' methods.' + ) + + for response in self._api_client.request_streamed( + 'post', path, request_dict, http_options + ): + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _GenerateContentResponse_from_vertex( + response_dict, None, parameter_model + ) + + if not self._api_client.vertexai: + response_dict = _GenerateContentResponse_from_mldev( + response_dict, None, parameter_model + ) + + return_value = types.GenerateContentResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + return_value.sdk_http_response = types.HttpResponse( + headers=response.headers + ) + self._api_client._verify_response(return_value) + yield return_value + + def _embed_content( + self, + *, + model: str, + contents: Optional[ + Union[types.ContentListUnion, types.ContentListUnionDict] + ] = None, + content: Optional[ + Union[types.ContentUnion, types.ContentUnionDict] + ] = None, + embedding_api_type: Optional[types.EmbeddingApiType] = None, + config: Optional[types.EmbedContentConfigOrDict] = None, + ) -> types.EmbedContentResponse: + """Calculates embeddings for the given contents. Only text is supported. + + Args: + model (str): The model to use. + contents (list[Content]): The contents to embed. + config (EmbedContentConfig): Optional configuration for embeddings. + + Usage: + + .. code-block:: python + + embeddings = client.models.embed_content( + model= 'text-embedding-004', + contents=[ + 'What is your name?', + 'What is your favorite color?', + ], + config={ + 'output_dimensionality': 64 + }, + ) + """ + + parameter_model = types._EmbedContentParametersPrivate( + model=model, + contents=contents, + content=content, + embedding_api_type=embedding_api_type, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _EmbedContentParametersPrivate_to_vertex( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + endpoint_url = '{model}:embedContent' if t.t_is_vertex_embed_content_model(parameter_model.model) else '{model}:predict' # type: ignore[arg-type] + if request_url_dict: + path = endpoint_url.format_map(request_url_dict) + else: + path = endpoint_url + else: + request_dict = _EmbedContentParametersPrivate_to_mldev( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{model}:batchEmbedContents'.format_map(request_url_dict) + else: + path = '{model}:batchEmbedContents' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request( + 'post', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _EmbedContentResponse_from_vertex( + response_dict, None, parameter_model + ) + + if not self._api_client.vertexai: + response_dict = _EmbedContentResponse_from_mldev( + response_dict, None, parameter_model + ) + + return_value = types.EmbedContentResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + return_value.sdk_http_response = types.HttpResponse( + headers=response.headers + ) + self._api_client._verify_response(return_value) + return return_value + + def _generate_images( + self, + *, + model: str, + prompt: str, + config: Optional[types.GenerateImagesConfigOrDict] = None, + ) -> types.GenerateImagesResponse: + """Private method for generating images.""" + + parameter_model = types._GenerateImagesParameters( + model=model, + prompt=prompt, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _GenerateImagesParameters_to_vertex( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{model}:predict'.format_map(request_url_dict) + else: + path = '{model}:predict' + else: + request_dict = _GenerateImagesParameters_to_mldev( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{model}:predict'.format_map(request_url_dict) + else: + path = '{model}:predict' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request( + 'post', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _GenerateImagesResponse_from_vertex( + response_dict, None, parameter_model + ) + + if not self._api_client.vertexai: + response_dict = _GenerateImagesResponse_from_mldev( + response_dict, None, parameter_model + ) + + return_value = types.GenerateImagesResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + return_value.sdk_http_response = types.HttpResponse( + headers=response.headers + ) + self._api_client._verify_response(return_value) + return return_value + + def _edit_image( + self, + *, + model: str, + prompt: str, + reference_images: list[types._ReferenceImageAPIOrDict], + config: Optional[types.EditImageConfigOrDict] = None, + ) -> types.EditImageResponse: + """Private method for editing an image.""" + + parameter_model = types._EditImageParameters( + model=model, + prompt=prompt, + reference_images=reference_images, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if not self._api_client.vertexai: + raise ValueError('This method is only supported in the Vertex AI client.') + else: + request_dict = _EditImageParameters_to_vertex( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{model}:predict'.format_map(request_url_dict) + else: + path = '{model}:predict' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request( + 'post', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _EditImageResponse_from_vertex( + response_dict, None, parameter_model + ) + + return_value = types.EditImageResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + return_value.sdk_http_response = types.HttpResponse( + headers=response.headers + ) + self._api_client._verify_response(return_value) + return return_value + + def _upscale_image( + self, + *, + model: str, + image: types.ImageOrDict, + upscale_factor: str, + config: Optional[types._UpscaleImageAPIConfigOrDict] = None, + ) -> types.UpscaleImageResponse: + """Private method for upscaling an image.""" + + parameter_model = types._UpscaleImageAPIParameters( + model=model, + image=image, + upscale_factor=upscale_factor, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if not self._api_client.vertexai: + raise ValueError('This method is only supported in the Vertex AI client.') + else: + request_dict = _UpscaleImageAPIParameters_to_vertex( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{model}:predict'.format_map(request_url_dict) + else: + path = '{model}:predict' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request( + 'post', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _UpscaleImageResponse_from_vertex( + response_dict, None, parameter_model + ) + + return_value = types.UpscaleImageResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + return_value.sdk_http_response = types.HttpResponse( + headers=response.headers + ) + self._api_client._verify_response(return_value) + return return_value + + def recontext_image( + self, + *, + model: str, + source: types.RecontextImageSourceOrDict, + config: Optional[types.RecontextImageConfigOrDict] = None, + ) -> types.RecontextImageResponse: + """Recontextualizes an image. + + There is one type of recontextualization currently supported: + 1) Virtual Try-On: Generate images of persons modeling fashion products. + + Args: + model (str): The model to use. + source (RecontextImageSource): An object containing the source inputs + (prompt, person_image, product_images) for image recontext. prompt is + behind an allowlist. person_image is required. product_images is + required. Only one product image is supported currently. + config (RecontextImageConfig): Configuration for recontextualization. + + Usage: + + ``` + virtual_try_on_response = client.models.recontext_image( + model="virtual-try-on-001", + source=types.RecontextImageSource( + person_image=types.Image.from_file(IMAGE1_FILE_PATH), + product_images=[types.ProductImage.from_file(IMAGE2_FILE_PATH)], + ), + config=types.RecontextImageConfig( + number_of_images=1, + ), + ) + image = virtual_try_on_response.generated_images[0].image + ``` + """ + + parameter_model = types._RecontextImageParameters( + model=model, + source=source, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if not self._api_client.vertexai: + raise ValueError('This method is only supported in the Vertex AI client.') + else: + request_dict = _RecontextImageParameters_to_vertex( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{model}:predict'.format_map(request_url_dict) + else: + path = '{model}:predict' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request( + 'post', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _RecontextImageResponse_from_vertex( + response_dict, None, parameter_model + ) + + return_value = types.RecontextImageResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + + self._api_client._verify_response(return_value) + return return_value + + def segment_image( + self, + *, + model: str, + source: types.SegmentImageSourceOrDict, + config: Optional[types.SegmentImageConfigOrDict] = None, + ) -> types.SegmentImageResponse: + """Segments an image, creating a mask of a specified area. + + Args: + model (str): The model to use. + source (SegmentImageSource): An object containing the source inputs + (prompt, image, scribble_image) for image segmentation. The prompt is + required for prompt mode and semantic mode, disallowed for other modes. + scribble_image is required for the interactive mode, disallowed for + other modes. + config (SegmentImageConfig): Configuration for segmentation. + + Usage: + + ``` + response = client.models.segment_image( + model="image-segmentation-001", + source=types.SegmentImageSource( + image=types.Image.from_file(IMAGE_FILE_PATH), + ), + ) + + mask_image = response.generated_masks[0].mask + ``` + """ + + parameter_model = types._SegmentImageParameters( + model=model, + source=source, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if not self._api_client.vertexai: + raise ValueError('This method is only supported in the Vertex AI client.') + else: + request_dict = _SegmentImageParameters_to_vertex( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{model}:predict'.format_map(request_url_dict) + else: + path = '{model}:predict' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request( + 'post', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _SegmentImageResponse_from_vertex( + response_dict, None, parameter_model + ) + + return_value = types.SegmentImageResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + + self._api_client._verify_response(return_value) + return return_value + + def get( + self, *, model: str, config: Optional[types.GetModelConfigOrDict] = None + ) -> types.Model: + parameter_model = types._GetModelParameters( + model=model, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _GetModelParameters_to_vertex( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{name}'.format_map(request_url_dict) + else: + path = '{name}' + else: + request_dict = _GetModelParameters_to_mldev( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{name}'.format_map(request_url_dict) + else: + path = '{name}' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request('get', path, request_dict, http_options) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _Model_from_vertex(response_dict, None, parameter_model) + + if not self._api_client.vertexai: + response_dict = _Model_from_mldev(response_dict, None, parameter_model) + + return_value = types.Model._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + + self._api_client._verify_response(return_value) + return return_value + + def _list( + self, *, config: Optional[types.ListModelsConfigOrDict] = None + ) -> types.ListModelsResponse: + parameter_model = types._ListModelsParameters( + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _ListModelsParameters_to_vertex( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{models_url}'.format_map(request_url_dict) + else: + path = '{models_url}' + else: + request_dict = _ListModelsParameters_to_mldev( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{models_url}'.format_map(request_url_dict) + else: + path = '{models_url}' + query_params = request_dict.get('_query') + if query_params and query_params.get('filter'): + query_param_filter = query_params.pop('filter') + path = f'{path}?filter={query_param_filter}' + if query_params: + path += f'&{urlencode(query_params)}' + elif query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request('get', path, request_dict, http_options) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _ListModelsResponse_from_vertex( + response_dict, None, parameter_model + ) + + if not self._api_client.vertexai: + response_dict = _ListModelsResponse_from_mldev( + response_dict, None, parameter_model + ) + + return_value = types.ListModelsResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + return_value.sdk_http_response = types.HttpResponse( + headers=response.headers + ) + self._api_client._verify_response(return_value) + return return_value + + def update( + self, + *, + model: str, + config: Optional[types.UpdateModelConfigOrDict] = None, + ) -> types.Model: + parameter_model = types._UpdateModelParameters( + model=model, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _UpdateModelParameters_to_vertex( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{model}'.format_map(request_url_dict) + else: + path = '{model}' + else: + request_dict = _UpdateModelParameters_to_mldev( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{name}'.format_map(request_url_dict) + else: + path = '{name}' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request( + 'patch', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _Model_from_vertex(response_dict, None, parameter_model) + + if not self._api_client.vertexai: + response_dict = _Model_from_mldev(response_dict, None, parameter_model) + + return_value = types.Model._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + + self._api_client._verify_response(return_value) + return return_value + + def delete( + self, + *, + model: str, + config: Optional[types.DeleteModelConfigOrDict] = None, + ) -> types.DeleteModelResponse: + parameter_model = types._DeleteModelParameters( + model=model, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _DeleteModelParameters_to_vertex( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{name}'.format_map(request_url_dict) + else: + path = '{name}' + else: + request_dict = _DeleteModelParameters_to_mldev( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{name}'.format_map(request_url_dict) + else: + path = '{name}' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request( + 'delete', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _DeleteModelResponse_from_vertex( + response_dict, None, parameter_model + ) + + if not self._api_client.vertexai: + response_dict = _DeleteModelResponse_from_mldev( + response_dict, None, parameter_model + ) + + return_value = types.DeleteModelResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + return_value.sdk_http_response = types.HttpResponse( + headers=response.headers + ) + self._api_client._verify_response(return_value) + return return_value + + def count_tokens( + self, + *, + model: str, + contents: Union[types.ContentListUnion, types.ContentListUnionDict], + config: Optional[types.CountTokensConfigOrDict] = None, + ) -> types.CountTokensResponse: + """Counts the number of tokens in the given content. + + Multimodal input is supported for Gemini models. + + Args: + model (str): The model to use for counting tokens. + contents (list[types.Content]): The content to count tokens for. + config (CountTokensConfig): The configuration for counting tokens. + + Usage: + + .. code-block:: python + + response = client.models.count_tokens( + model='gemini-2.0-flash', + contents='What is your name?', + ) + print(response) + # total_tokens=5 cached_content_token_count=None + """ + + parameter_model = types._CountTokensParameters( + model=model, + contents=contents, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _CountTokensParameters_to_vertex( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{model}:countTokens'.format_map(request_url_dict) + else: + path = '{model}:countTokens' + else: + request_dict = _CountTokensParameters_to_mldev( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{model}:countTokens'.format_map(request_url_dict) + else: + path = '{model}:countTokens' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request( + 'post', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _CountTokensResponse_from_vertex( + response_dict, None, parameter_model + ) + + if not self._api_client.vertexai: + response_dict = _CountTokensResponse_from_mldev( + response_dict, None, parameter_model + ) + + return_value = types.CountTokensResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + return_value.sdk_http_response = types.HttpResponse( + headers=response.headers + ) + self._api_client._verify_response(return_value) + return return_value + + def compute_tokens( + self, + *, + model: str, + contents: Union[types.ContentListUnion, types.ContentListUnionDict], + config: Optional[types.ComputeTokensConfigOrDict] = None, + ) -> types.ComputeTokensResponse: + """Given a list of contents, returns a corresponding TokensInfo containing the + + list of tokens and list of token ids. + + This method is not supported by the Gemini Developer API. + + Args: + model (str): The model to use. + contents (list[shared.Content]): The content to compute tokens for. + + Usage: + + .. code-block:: python + + response = client.models.compute_tokens( + model='gemini-2.0-flash', + contents='What is your name?', + ) + print(response) + # tokens_info=[TokensInfo(role='user', token_ids=['1841', ...], + # tokens=[b'What', b' is', b' your', b' name', b'?'])] + """ + + parameter_model = types._ComputeTokensParameters( + model=model, + contents=contents, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if not self._api_client.vertexai: + raise ValueError('This method is only supported in the Vertex AI client.') + else: + request_dict = _ComputeTokensParameters_to_vertex( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{model}:computeTokens'.format_map(request_url_dict) + else: + path = '{model}:computeTokens' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request( + 'post', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _ComputeTokensResponse_from_vertex( + response_dict, None, parameter_model + ) + + return_value = types.ComputeTokensResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + return_value.sdk_http_response = types.HttpResponse( + headers=response.headers + ) + self._api_client._verify_response(return_value) + return return_value + + def _generate_videos( + self, + *, + model: str, + prompt: Optional[str] = None, + image: Optional[types.ImageOrDict] = None, + video: Optional[types.VideoOrDict] = None, + source: Optional[types.GenerateVideosSourceOrDict] = None, + config: Optional[types.GenerateVideosConfigOrDict] = None, + ) -> types.GenerateVideosOperation: + """Private method for generating videos.""" + + parameter_model = types._GenerateVideosParameters( + model=model, + prompt=prompt, + image=image, + video=video, + source=source, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _GenerateVideosParameters_to_vertex( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{model}:predictLongRunning'.format_map(request_url_dict) + else: + path = '{model}:predictLongRunning' + else: + request_dict = _GenerateVideosParameters_to_mldev( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{model}:predictLongRunning'.format_map(request_url_dict) + else: + path = '{model}:predictLongRunning' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request( + 'post', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _GenerateVideosOperation_from_vertex( + response_dict, None, parameter_model + ) + + if not self._api_client.vertexai: + response_dict = _GenerateVideosOperation_from_mldev( + response_dict, None, parameter_model + ) + + return_value = types.GenerateVideosOperation._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + + self._api_client._verify_response(return_value) + return return_value + + def embed_content( + self, + *, + model: str, + contents: Union[types.ContentListUnion, types.ContentListUnionDict], + config: Optional[types.EmbedContentConfigOrDict] = None, + ) -> types.EmbedContentResponse: + """Calculates embeddings for the given contents. + + Args: + model (str): The model to use. + contents (list[Content]): The contents to embed. + config (EmbedContentConfig): Optional configuration for embeddings. + + Usage: + + .. code-block:: python + + embeddings = client.models.embed_content( + model= 'text-embedding-004', + contents=[ + 'What is your name?', + 'What is your favorite color?', + ], + config={ + 'output_dimensionality': 64 + }, + ) + + multimodal_embeddings = client.models.embed_content( + model='gemini-embedding-2-preview', + contents=[ + types.Part.from_uri( + file_uri='gs://generativeai-downloads/images/scones.jpg', + mime_type='image/jpeg', + ), + ], + config={ + 'output_dimensionality': 64 + }, + ) + """ + if not self._api_client.vertexai: + if 'gemini-embedding-2' in model: + contents = t.t_contents(contents) # type: ignore[assignment] + return self._embed_content(model=model, contents=contents, config=config) + + if t.t_is_vertex_embed_content_model(model): + normalized_contents = t.t_contents(contents) + if len(normalized_contents) > 1: + raise ValueError( + 'The embedContent API for this model only supports one content at a' + ' time.' + ) + return self._embed_content( + model=model, + contents=None, + content=normalized_contents[0], + embedding_api_type=types.EmbeddingApiType.EMBED_CONTENT, + config=config, + ) + else: + return self._embed_content( + model=model, + content=None, + contents=contents, + embedding_api_type=types.EmbeddingApiType.PREDICT, + config=config, + ) + + def generate_content( + self, + *, + model: str, + contents: types.ContentListUnionDict, + config: Optional[types.GenerateContentConfigOrDict] = None, + ) -> types.GenerateContentResponse: + """Makes an API request to generate content using a model. + + For the `model` parameter, supported formats for Vertex AI API include: + - The Gemini model ID, for example: 'gemini-2.0-flash' + - The full resource name starts with 'projects/', for example: + 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + - The partial resource name with 'publishers/', for example: + 'publishers/google/models/gemini-2.0-flash' or + - `/` separated publisher and model name, for example: + 'google/gemini-2.0-flash' + + For the `model` parameter, supported formats for Gemini API include: + - The Gemini model ID, for example: 'gemini-2.0-flash' + - The model name starts with 'models/', for example: + 'models/gemini-2.0-flash' + - For tuned models, the model name starts with 'tunedModels/', + for example: + 'tunedModels/1234567890123456789' + + Some models support multimodal input and output. + + Built-in MCP support is an experimental feature. + + Usage: + + .. code-block:: python + + from google.genai import types + from google import genai + + client = genai.Client( + vertexai=True, project='my-project-id', location='us-central1' + ) + + response = client.models.generate_content( + model='gemini-2.0-flash', + contents='''What is a good name for a flower shop that specializes in + selling bouquets of dried flowers?''' + ) + print(response.text) + # **Elegant & Classic:** + # * The Dried Bloom + # * Everlasting Florals + # * Timeless Petals + + response = client.models.generate_content( + model='gemini-2.0-flash', + contents=[ + types.Part.from_text(text='What is shown in this image?'), + types.Part.from_uri(file_uri='gs://generativeai-downloads/images/scones.jpg', + mime_type='image/jpeg') + ] + ) + print(response.text) + # The image shows a flat lay arrangement of freshly baked blueberry + # scones. + """ + + incompatible_tools_indexes = ( + _extra_utils.find_afc_incompatible_tool_indexes(config) + ) + parsed_config = _extra_utils.parse_config_for_mcp_usage(config) + if ( + parsed_config + and parsed_config.tools + and _mcp_utils.has_mcp_session_usage(parsed_config.tools) + ): + raise errors.UnsupportedFunctionError( + 'MCP sessions are not supported in synchronous methods.' + ) + if _extra_utils.should_disable_afc(parsed_config): + return self._generate_content( + model=model, contents=contents, config=parsed_config + ) + if incompatible_tools_indexes: + original_tools_length = 0 + if isinstance(config, types.GenerateContentConfig): + if config.tools: + original_tools_length = len(config.tools) + elif isinstance(config, dict): + tools = config.get('tools', []) + if tools: + original_tools_length = len(tools) + if len(incompatible_tools_indexes) != original_tools_length: + indices_str = ', '.join(map(str, incompatible_tools_indexes)) + logger.warning( + 'Tools at indices [%s] are not compatible with automatic function ' + 'calling (AFC). AFC is disabled. If AFC is intended, please ' + 'include python callables in the tool list, and do not include ' + 'function declaration and MCP server in the tool list.', + indices_str, + ) + return self._generate_content( + model=model, contents=contents, config=parsed_config + ) + + remaining_remote_calls_afc = _extra_utils.get_max_remote_calls_afc( + parsed_config + ) + logger.info( + f'AFC is enabled with max remote calls: {remaining_remote_calls_afc}.' + ) + automatic_function_calling_history: list[types.Content] = [] + response = types.GenerateContentResponse() + i = 0 + while remaining_remote_calls_afc > 0: + i += 1 + response = self._generate_content( + model=model, contents=contents, config=parsed_config + ) + + function_map = _extra_utils.get_function_map(parsed_config) + if not function_map: + break + if not response: + break + if ( + not response.candidates + or not response.candidates[0].content + or not response.candidates[0].content.parts + ): + break + func_response_parts = _extra_utils.get_function_response_parts( + response, function_map + ) + if not func_response_parts: + break + logger.info(f'AFC remote call {i} is done.') + remaining_remote_calls_afc -= 1 + if remaining_remote_calls_afc == 0: + logger.info('Reached max remote calls for automatic function calling.') + + func_call_content = response.candidates[0].content + func_response_content = types.Content( + role='user', + parts=func_response_parts, + ) + contents = t.t_contents(contents) # type: ignore[assignment] + if not automatic_function_calling_history: + automatic_function_calling_history.extend(contents) # type: ignore[arg-type] + if isinstance(contents, list): + contents.append(func_call_content) # type: ignore[arg-type] + contents.append(func_response_content) # type: ignore[arg-type] + automatic_function_calling_history.append(func_call_content) + automatic_function_calling_history.append(func_response_content) + if ( + _extra_utils.should_append_afc_history(parsed_config) + and response is not None + ): + response.automatic_function_calling_history = ( + automatic_function_calling_history + ) + return response + + def generate_content_stream( + self, + *, + model: str, + contents: types.ContentListUnionDict, + config: Optional[types.GenerateContentConfigOrDict] = None, + ) -> Iterator[types.GenerateContentResponse]: + """Makes an API request to generate content using a model and yields the model's response in chunks. + + For the `model` parameter, supported formats for Vertex AI API include: + - The Gemini model ID, for example: 'gemini-2.0-flash' + - The full resource name starts with 'projects/', for example: + 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + - The partial resource name with 'publishers/', for example: + 'publishers/google/models/gemini-2.0-flash' or + - `/` separated publisher and model name, for example: + 'google/gemini-2.0-flash' + + For the `model` parameter, supported formats for Gemini API include: + - The Gemini model ID, for example: 'gemini-2.0-flash' + - The model name starts with 'models/', for example: + 'models/gemini-2.0-flash' + - For tuned models, the model name starts with 'tunedModels/', + for example: + 'tunedModels/1234567890123456789' + + Some models support multimodal input and output. + + Built-in MCP support is an experimental feature. + + Usage: + + .. code-block:: python + + from google.genai import types + from google import genai + + client = genai.Client( + vertexai=True, project='my-project-id', location='us-central1' + ) + + for chunk in client.models.generate_content_stream( + model='gemini-2.0-flash', + contents='''What is a good name for a flower shop that specializes in + selling bouquets of dried flowers?''' + ): + print(chunk.text) + # **Elegant & Classic:** + # * The Dried Bloom + # * Everlasting Florals + # * Timeless Petals + + for chunk in client.models.generate_content_stream( + model='gemini-2.0-flash', + contents=[ + types.Part.from_text('What is shown in this image?'), + types.Part.from_uri('gs://generativeai-downloads/images/scones.jpg', + 'image/jpeg') + ] + ): + print(chunk.text) + # The image shows a flat lay arrangement of freshly baked blueberry + # scones. + """ + + incompatible_tools_indexes = ( + _extra_utils.find_afc_incompatible_tool_indexes(config) + ) + parsed_config = _extra_utils.parse_config_for_mcp_usage(config) + if ( + parsed_config + and parsed_config.tools + and _mcp_utils.has_mcp_session_usage(parsed_config.tools) + ): + raise errors.UnsupportedFunctionError( + 'MCP sessions are not supported in synchronous methods.' + ) + if _extra_utils.should_disable_afc(parsed_config): + yield from self._generate_content_stream( + model=model, contents=contents, config=parsed_config + ) + return + + if incompatible_tools_indexes: + original_tools_length = 0 + if isinstance(config, types.GenerateContentConfig): + if config.tools: + original_tools_length = len(config.tools) + elif isinstance(config, dict): + tools = config.get('tools', []) + if tools: + original_tools_length = len(tools) + if len(incompatible_tools_indexes) != original_tools_length: + indices_str = ', '.join(map(str, incompatible_tools_indexes)) + logger.warning( + 'Tools at indices [%s] are not compatible with automatic function ' + 'calling. AFC will be disabled.', + indices_str, + ) + yield from self._generate_content_stream( + model=model, contents=contents, config=parsed_config + ) + return + + # With tool compatibility confirmed, validate that the configuration are + # compatible with each other and raise an error if invalid. + _extra_utils.raise_error_for_afc_incompatible_config(parsed_config) + + remaining_remote_calls_afc = _extra_utils.get_max_remote_calls_afc( + parsed_config + ) + logger.info( + f'AFC is enabled with max remote calls: {remaining_remote_calls_afc}.' + ) + automatic_function_calling_history: list[types.Content] = [] + chunk = None + func_response_parts = None + i = 0 + while remaining_remote_calls_afc > 0: + i += 1 + response = self._generate_content_stream( + model=model, contents=contents, config=parsed_config + ) + + function_map = _extra_utils.get_function_map(parsed_config) + + if i == 1: + # First request gets a function call. + # Then get function response parts. + # Yield chunks only if there's no function response parts. + for chunk in response: + if not function_map: + contents = _extra_utils.append_chunk_contents(contents, chunk) # type: ignore[assignment] + yield chunk + else: + if ( + not chunk.candidates + or not chunk.candidates[0].content + or not chunk.candidates[0].content.parts + ): + break + func_response_parts = _extra_utils.get_function_response_parts( + chunk, function_map + ) + if not func_response_parts: + contents = _extra_utils.append_chunk_contents(contents, chunk) # type: ignore[assignment] + yield chunk + + else: + # Second request and beyond, yield chunks. + for chunk in response: + if _extra_utils.should_append_afc_history(parsed_config): + chunk.automatic_function_calling_history = ( + automatic_function_calling_history + ) + contents = _extra_utils.append_chunk_contents(contents, chunk) # type: ignore[assignment] + yield chunk + if ( + chunk is None + or not chunk.candidates + or not chunk.candidates[0].content + or not chunk.candidates[0].content.parts + ): + break + func_response_parts = _extra_utils.get_function_response_parts( + chunk, function_map + ) + + if not function_map: + break + if not func_response_parts: + break + logger.info(f'AFC remote call {i} is done.') + remaining_remote_calls_afc -= 1 + if remaining_remote_calls_afc == 0: + logger.info('Reached max remote calls for automatic function calling.') + + # Append function response parts to contents for the next request. + if chunk is not None and chunk.candidates is not None: + func_call_content = chunk.candidates[0].content + func_response_content = types.Content( + role='user', + parts=func_response_parts, + ) + contents = t.t_contents(contents) # type: ignore[assignment] + if not automatic_function_calling_history: + automatic_function_calling_history.extend(contents) # type: ignore[arg-type] + if isinstance(contents, list) and func_call_content is not None: + contents.append(func_call_content) # type: ignore[arg-type] + contents.append(func_response_content) # type: ignore[arg-type] + if func_call_content is not None: + automatic_function_calling_history.append(func_call_content) + automatic_function_calling_history.append(func_response_content) + + def generate_images( + self, + *, + model: str, + prompt: str, + config: Optional[types.GenerateImagesConfigOrDict] = None, + ) -> types.GenerateImagesResponse: + """Generates images based on a text description and configuration. + + Args: + model (str): The model to use. + prompt (str): A text description of the images to generate. + config (GenerateImagesConfig): Configuration for generation. + + Usage: + + .. code-block:: python + + response = client.models.generate_images( + model='imagen-3.0-generate-002', + prompt='Man with a dog', + config=types.GenerateImagesConfig( + number_of_images= 1, + include_rai_reason= True, + ) + ) + response.generated_images[0].image.show() + # Shows a man with a dog. + """ + api_response = self._generate_images( + model=model, + prompt=prompt, + config=config, + ) + positive_prompt_safety_attributes = None + generated_images = [] + if not api_response or not api_response.generated_images: + return api_response + + for generated_image in api_response.generated_images: + if ( + generated_image.safety_attributes + and generated_image.safety_attributes.content_type + == 'Positive Prompt' + ): + positive_prompt_safety_attributes = generated_image.safety_attributes + else: + generated_images.append(generated_image) + + response = types.GenerateImagesResponse( + generated_images=generated_images, + positive_prompt_safety_attributes=positive_prompt_safety_attributes, + ) + return response + + def edit_image( + self, + *, + model: str, + prompt: str, + reference_images: list[types._ReferenceImageAPIOrDict], + config: Optional[types.EditImageConfigOrDict] = None, + ) -> types.EditImageResponse: + """Edits an image based on a text description and configuration. + + Args: + model (str): The model to use. + prompt (str): A text description of the edit to apply to the image. + reference_images (list[Union[RawReferenceImage, MaskReferenceImage, + ControlReferenceImage, StyleReferenceImage, SubjectReferenceImage]): The + reference images for editing. + config (EditImageConfig): Configuration for editing. + + Usage: + + .. code-block:: python + + from google.genai.types import RawReferenceImage, MaskReferenceImage + + raw_ref_image = RawReferenceImage( + reference_id=1, + reference_image=types.Image.from_file(IMAGE_FILE_PATH), + ) + + mask_ref_image = MaskReferenceImage( + reference_id=2, + config=types.MaskReferenceConfig( + mask_mode='MASK_MODE_FOREGROUND', + mask_dilation=0.06, + ), + ) + response = client.models.edit_image( + model='imagen-3.0-capability-001', + prompt='man with dog', + reference_images=[raw_ref_image, mask_ref_image], + config=types.EditImageConfig( + edit_mode= "EDIT_MODE_INPAINT_INSERTION", + number_of_images= 1, + include_rai_reason= True, + ) + ) + response.generated_images[0].image.show() + # Shows a man with a dog instead of a cat. + """ + return self._edit_image( + model=model, + prompt=prompt, + reference_images=reference_images, + config=config, + ) + + def upscale_image( + self, + *, + model: str, + image: types.ImageOrDict, + upscale_factor: str, + config: Optional[types.UpscaleImageConfigOrDict] = None, + ) -> types.UpscaleImageResponse: + """Makes an API request to upscale a provided image. + + Args: + model (str): The model to use. + image (Image): The input image for upscaling. + upscale_factor (str): The factor to upscale the image (x2 or x4). + config (UpscaleImageConfig): Configuration for upscaling. + + Usage: + + .. code-block:: python + + from google.genai.types import Image + + IMAGE_FILE_PATH="my-image.png" + response=client.models.upscale_image( + model='imagen-3.0-generate-001', + image=types.Image.from_file(IMAGE_FILE_PATH), + upscale_factor='x2', + ) + response.generated_images[0].image.show() + # Opens my-image.png which is upscaled by a factor of 2. + """ + + # Validate config. + types.UpscaleImageParameters( + model=model, + image=image, + upscale_factor=upscale_factor, + config=config, + ) + + # Convert to API config. + config = config or {} + if isinstance(config, types.UpscaleImageConfig): + config_dct = config.model_dump() + else: + config_dct = dict(config) + api_config = types._UpscaleImageAPIConfigDict( + http_options=config_dct.get('http_options', None), + output_gcs_uri=config_dct.get('output_gcs_uri', None), + safety_filter_level=config_dct.get('safety_filter_level', None), + person_generation=config_dct.get('person_generation', None), + include_rai_reason=config_dct.get('include_rai_reason', None), + output_mime_type=config_dct.get('output_mime_type', None), + output_compression_quality=config_dct.get( + 'output_compression_quality', None + ), + enhance_input_image=config_dct.get('enhance_input_image', None), + image_preservation_factor=config_dct.get( + 'image_preservation_factor', None + ), + labels=config_dct.get('labels', None), + ) # pylint: disable=protected-access + + # Provide default values through API config. + api_config['mode'] = 'upscale' + api_config['number_of_images'] = 1 + + return self._upscale_image( + model=model, + image=image, + upscale_factor=upscale_factor, + config=api_config, + ) + + def generate_videos( + self, + *, + model: str, + prompt: Optional[str] = None, + image: Optional[types.ImageOrDict] = None, + video: Optional[types.VideoOrDict] = None, + source: Optional[types.GenerateVideosSourceOrDict] = None, + config: Optional[types.GenerateVideosConfigOrDict] = None, + ) -> types.GenerateVideosOperation: + """Generates videos based on an input (text, image, or video) and configuration. + + The following use cases are supported: + 1. Text to video generation. + 2a. Image to video generation (additional text prompt is optional). + 2b. Image to video generation with frame interpolation (specify last_frame + in config). + 3. Video extension (additional text prompt is optional) + + Args: + model: The model to use. + prompt: The text prompt for generating the videos. Optional for image to + video and video extension use cases. This argument is deprecated, please + use source instead. + image: The input image for generating the videos. Optional if prompt is + provided. This argument is deprecated, please use source instead. + video: The input video for video extension use cases. Optional if prompt + or image is provided. This argument is deprecated, please use source + instead. + source: The input source for generating the videos (prompt, image, and/or + video) + config: Configuration for generation. + + Usage: + + ``` + operation = client.models.generate_videos( + model="veo-2.0-generate-001", + source=types.GenerateVideosSource( + prompt="A neon hologram of a cat driving at top speed", + ), + ) + while not operation.done: + time.sleep(10) + operation = client.operations.get(operation) + + operation.result.generated_videos[0].video.uri + ``` + """ + if (prompt or image or video) and source: + raise ValueError( + 'Source and prompt/image/video are mutually exclusive.' + + ' Please only use source.' + ) + # Gemini Developer API does not support video bytes. + video_dct: dict[str, Any] = {} + if not self._api_client.vertexai and video: + if isinstance(video, types.Video): + video_dct = video.model_dump() + else: + video_dct = dict(video) + + if video_dct.get('uri') and video_dct.get('video_bytes'): + video = types.Video( + uri=video_dct.get('uri'), mime_type=video_dct.get('mime_type') + ) + elif not self._api_client.vertexai and source: + if isinstance(source, types.GenerateVideosSource): + source_dct = source.model_dump() + video_dct = source_dct.get('video', {}) + else: + source_dct = dict(source) + if isinstance(source_dct.get('video'), types.Video): + video_obj: types.Video = source_dct.get('video', types.Video()) + video_dct = video_obj.model_dump() + if video_dct and video_dct.get('uri') and video_dct.get('video_bytes'): + source = types.GenerateVideosSource( + prompt=source_dct.get('prompt'), + image=source_dct.get('image'), + video=types.Video( + uri=video_dct.get('uri'), + mime_type=video_dct.get('mime_type'), + ), + ) + return self._generate_videos( + model=model, + prompt=prompt, + image=image, + video=video, + source=source, + config=config, + ) + + def list( + self, + *, + config: Optional[types.ListModelsConfigOrDict] = None, + ) -> Pager[types.Model]: + """Makes an API request to list the available models. + + If `query_base` is set to True in the config or not set (default), the + API will return all available base models. If set to False, it will return + all tuned models. + + Args: + config (ListModelsConfigOrDict): Configuration for retrieving models. + + Usage: + + .. code-block:: python + + response=client.models.list(config={'page_size': 5}) + print(response.page) + # [Model(name='projects/./locations/./models/123', display_name='my_model' + + response=client.models.list(config={'page_size': 5, 'query_base': True}) + print(response.page) + # [Model(name='publishers/google/models/gemini-2.0-flash-exp' ... + """ + + config = ( + types._ListModelsParameters(config=config).config + or types.ListModelsConfig() + ) + if config.query_base is None: + config.query_base = True + if self._api_client.vertexai: + config = config.copy() + if not config.query_base: + # Filter for tuning jobs artifacts by labels. + filter_value = config.filter + config.filter = ( + filter_value + '&filter=labels.tune-type:*' + if filter_value + else 'labels.tune-type:*' + ) + return Pager( + 'models', + self._list, + self._list(config=config), + config, + ) + + +class AsyncModels(_api_module.BaseModule): + + async def _generate_content( + self, + *, + model: str, + contents: Union[types.ContentListUnion, types.ContentListUnionDict], + config: Optional[types.GenerateContentConfigOrDict] = None, + ) -> types.GenerateContentResponse: + parameter_model = types._GenerateContentParameters( + model=model, + contents=contents, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _GenerateContentParameters_to_vertex( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{model}:generateContent'.format_map(request_url_dict) + else: + path = '{model}:generateContent' + else: + request_dict = _GenerateContentParameters_to_mldev( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{model}:generateContent'.format_map(request_url_dict) + else: + path = '{model}:generateContent' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'post', path, request_dict, http_options + ) + + if config is not None and getattr( + config, 'should_return_http_response', None + ): + return_value = types.GenerateContentResponse(sdk_http_response=response) + self._api_client._verify_response(return_value) + return return_value + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _GenerateContentResponse_from_vertex( + response_dict, None, parameter_model + ) + + if not self._api_client.vertexai: + response_dict = _GenerateContentResponse_from_mldev( + response_dict, None, parameter_model + ) + + return_value = types.GenerateContentResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + return_value.sdk_http_response = types.HttpResponse( + headers=response.headers + ) + self._api_client._verify_response(return_value) + return return_value + + async def _generate_content_stream( + self, + *, + model: str, + contents: Union[types.ContentListUnion, types.ContentListUnionDict], + config: Optional[types.GenerateContentConfigOrDict] = None, + ) -> Awaitable[AsyncIterator[types.GenerateContentResponse]]: + parameter_model = types._GenerateContentParameters( + model=model, + contents=contents, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _GenerateContentParameters_to_vertex( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{model}:streamGenerateContent?alt=sse'.format_map( + request_url_dict + ) + else: + path = '{model}:streamGenerateContent?alt=sse' + else: + request_dict = _GenerateContentParameters_to_mldev( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{model}:streamGenerateContent?alt=sse'.format_map( + request_url_dict + ) + else: + path = '{model}:streamGenerateContent?alt=sse' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + if config is not None and getattr( + config, 'should_return_http_response', None + ): + raise ValueError( + 'Accessing the raw HTTP response is not supported in streaming' + ' methods.' + ) + + response_stream = await self._api_client.async_request_streamed( + 'post', path, request_dict, http_options + ) + + async def async_generator(): # type: ignore[no-untyped-def] + async for response in response_stream: + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _GenerateContentResponse_from_vertex( + response_dict, None, parameter_model + ) + + if not self._api_client.vertexai: + response_dict = _GenerateContentResponse_from_mldev( + response_dict, None, parameter_model + ) + + return_value = types.GenerateContentResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + return_value.sdk_http_response = types.HttpResponse( + headers=response.headers + ) + self._api_client._verify_response(return_value) + yield return_value + + return async_generator() # type: ignore[no-untyped-call, no-any-return] + + async def _embed_content( + self, + *, + model: str, + contents: Optional[ + Union[types.ContentListUnion, types.ContentListUnionDict] + ] = None, + content: Optional[ + Union[types.ContentUnion, types.ContentUnionDict] + ] = None, + embedding_api_type: Optional[types.EmbeddingApiType] = None, + config: Optional[types.EmbedContentConfigOrDict] = None, + ) -> types.EmbedContentResponse: + """Calculates embeddings for the given contents. Only text is supported. + + Args: + model (str): The model to use. + contents (list[Content]): The contents to embed. + config (EmbedContentConfig): Optional configuration for embeddings. + + Usage: + + .. code-block:: python + + embeddings = await client.aio.models.embed_content( + model= 'text-embedding-004', + contents=[ + 'What is your name?', + 'What is your favorite color?', + ], + config={ + 'output_dimensionality': 64 + }, + ) + """ + + parameter_model = types._EmbedContentParametersPrivate( + model=model, + contents=contents, + content=content, + embedding_api_type=embedding_api_type, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _EmbedContentParametersPrivate_to_vertex( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + endpoint_url = '{model}:embedContent' if t.t_is_vertex_embed_content_model(parameter_model.model) else '{model}:predict' # type: ignore[arg-type] + if request_url_dict: + path = endpoint_url.format_map(request_url_dict) + else: + path = endpoint_url + else: + request_dict = _EmbedContentParametersPrivate_to_mldev( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{model}:batchEmbedContents'.format_map(request_url_dict) + else: + path = '{model}:batchEmbedContents' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'post', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _EmbedContentResponse_from_vertex( + response_dict, None, parameter_model + ) + + if not self._api_client.vertexai: + response_dict = _EmbedContentResponse_from_mldev( + response_dict, None, parameter_model + ) + + return_value = types.EmbedContentResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + return_value.sdk_http_response = types.HttpResponse( + headers=response.headers + ) + self._api_client._verify_response(return_value) + return return_value + + async def _generate_images( + self, + *, + model: str, + prompt: str, + config: Optional[types.GenerateImagesConfigOrDict] = None, + ) -> types.GenerateImagesResponse: + """Private method for generating images asynchronously.""" + + parameter_model = types._GenerateImagesParameters( + model=model, + prompt=prompt, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _GenerateImagesParameters_to_vertex( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{model}:predict'.format_map(request_url_dict) + else: + path = '{model}:predict' + else: + request_dict = _GenerateImagesParameters_to_mldev( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{model}:predict'.format_map(request_url_dict) + else: + path = '{model}:predict' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'post', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _GenerateImagesResponse_from_vertex( + response_dict, None, parameter_model + ) + + if not self._api_client.vertexai: + response_dict = _GenerateImagesResponse_from_mldev( + response_dict, None, parameter_model + ) + + return_value = types.GenerateImagesResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + return_value.sdk_http_response = types.HttpResponse( + headers=response.headers + ) + self._api_client._verify_response(return_value) + return return_value + + async def _edit_image( + self, + *, + model: str, + prompt: str, + reference_images: list[types._ReferenceImageAPIOrDict], + config: Optional[types.EditImageConfigOrDict] = None, + ) -> types.EditImageResponse: + """Private method for editing an image asynchronously.""" + + parameter_model = types._EditImageParameters( + model=model, + prompt=prompt, + reference_images=reference_images, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if not self._api_client.vertexai: + raise ValueError('This method is only supported in the Vertex AI client.') + else: + request_dict = _EditImageParameters_to_vertex( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{model}:predict'.format_map(request_url_dict) + else: + path = '{model}:predict' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'post', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _EditImageResponse_from_vertex( + response_dict, None, parameter_model + ) + + return_value = types.EditImageResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + return_value.sdk_http_response = types.HttpResponse( + headers=response.headers + ) + self._api_client._verify_response(return_value) + return return_value + + async def _upscale_image( + self, + *, + model: str, + image: types.ImageOrDict, + upscale_factor: str, + config: Optional[types._UpscaleImageAPIConfigOrDict] = None, + ) -> types.UpscaleImageResponse: + """Private method for upscaling an image asynchronously.""" + + parameter_model = types._UpscaleImageAPIParameters( + model=model, + image=image, + upscale_factor=upscale_factor, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if not self._api_client.vertexai: + raise ValueError('This method is only supported in the Vertex AI client.') + else: + request_dict = _UpscaleImageAPIParameters_to_vertex( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{model}:predict'.format_map(request_url_dict) + else: + path = '{model}:predict' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'post', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _UpscaleImageResponse_from_vertex( + response_dict, None, parameter_model + ) + + return_value = types.UpscaleImageResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + return_value.sdk_http_response = types.HttpResponse( + headers=response.headers + ) + self._api_client._verify_response(return_value) + return return_value + + async def recontext_image( + self, + *, + model: str, + source: types.RecontextImageSourceOrDict, + config: Optional[types.RecontextImageConfigOrDict] = None, + ) -> types.RecontextImageResponse: + """Recontextualizes an image. + + There is one type of recontextualization currently supported: + 1) Virtual Try-On: Generate images of persons modeling fashion products. + + Args: + model (str): The model to use. + source (RecontextImageSource): An object containing the source inputs + (prompt, person_image, product_images) for image recontext. prompt is + behind an allowlist. person_image is required. product_images is + required. Only one product image is supported currently. + config (RecontextImageConfig): Configuration for recontextualization. + + Usage: + + ``` + virtual_try_on_response = await client.aio.models.recontext_image( + model="virtual-try-on-001", + source=types.RecontextImageSource( + person_image=types.Image.from_file(IMAGE1_FILE_PATH), + product_images=[types.ProductImage.from_file(IMAGE2_FILE_PATH)], + ), + config=types.RecontextImageConfig( + number_of_images=1, + ), + ) + image = virtual_try_on_response.generated_images[0].image + ``` + """ + + parameter_model = types._RecontextImageParameters( + model=model, + source=source, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if not self._api_client.vertexai: + raise ValueError('This method is only supported in the Vertex AI client.') + else: + request_dict = _RecontextImageParameters_to_vertex( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{model}:predict'.format_map(request_url_dict) + else: + path = '{model}:predict' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'post', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _RecontextImageResponse_from_vertex( + response_dict, None, parameter_model + ) + + return_value = types.RecontextImageResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + + self._api_client._verify_response(return_value) + return return_value + + async def segment_image( + self, + *, + model: str, + source: types.SegmentImageSourceOrDict, + config: Optional[types.SegmentImageConfigOrDict] = None, + ) -> types.SegmentImageResponse: + """Segments an image, creating a mask of a specified area. + + Args: + model (str): The model to use. + source (SegmentImageSource): An object containing the source inputs + (prompt, image, scribble_image) for image segmentation. The prompt is + required for prompt mode and semantic mode, disallowed for other modes. + scribble_image is required for the interactive mode, disallowed for + other modes. + config (SegmentImageConfig): Configuration for segmentation. + + Usage: + + ``` + response = client.models.segment_image( + model="image-segmentation-001", + source=types.SegmentImageSource( + image=types.Image.from_file(IMAGE_FILE_PATH), + ), + config=types.SegmentImageConfig( + mode=types.SegmentMode.foreground, + ), + ) + + mask_image = response.generated_masks[0].mask + ``` + """ + + parameter_model = types._SegmentImageParameters( + model=model, + source=source, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if not self._api_client.vertexai: + raise ValueError('This method is only supported in the Vertex AI client.') + else: + request_dict = _SegmentImageParameters_to_vertex( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{model}:predict'.format_map(request_url_dict) + else: + path = '{model}:predict' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'post', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _SegmentImageResponse_from_vertex( + response_dict, None, parameter_model + ) + + return_value = types.SegmentImageResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + + self._api_client._verify_response(return_value) + return return_value + + async def get( + self, *, model: str, config: Optional[types.GetModelConfigOrDict] = None + ) -> types.Model: + parameter_model = types._GetModelParameters( + model=model, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _GetModelParameters_to_vertex( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{name}'.format_map(request_url_dict) + else: + path = '{name}' + else: + request_dict = _GetModelParameters_to_mldev( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{name}'.format_map(request_url_dict) + else: + path = '{name}' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'get', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _Model_from_vertex(response_dict, None, parameter_model) + + if not self._api_client.vertexai: + response_dict = _Model_from_mldev(response_dict, None, parameter_model) + + return_value = types.Model._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + + self._api_client._verify_response(return_value) + return return_value + + async def _list( + self, *, config: Optional[types.ListModelsConfigOrDict] = None + ) -> types.ListModelsResponse: + parameter_model = types._ListModelsParameters( + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _ListModelsParameters_to_vertex( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{models_url}'.format_map(request_url_dict) + else: + path = '{models_url}' + else: + request_dict = _ListModelsParameters_to_mldev( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{models_url}'.format_map(request_url_dict) + else: + path = '{models_url}' + query_params = request_dict.get('_query') + if query_params and query_params.get('filter'): + query_param_filter = query_params.pop('filter') + path = f'{path}?filter={query_param_filter}' + if query_params: + path += f'&{urlencode(query_params)}' + elif query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'get', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _ListModelsResponse_from_vertex( + response_dict, None, parameter_model + ) + + if not self._api_client.vertexai: + response_dict = _ListModelsResponse_from_mldev( + response_dict, None, parameter_model + ) + + return_value = types.ListModelsResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + return_value.sdk_http_response = types.HttpResponse( + headers=response.headers + ) + self._api_client._verify_response(return_value) + return return_value + + async def update( + self, + *, + model: str, + config: Optional[types.UpdateModelConfigOrDict] = None, + ) -> types.Model: + parameter_model = types._UpdateModelParameters( + model=model, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _UpdateModelParameters_to_vertex( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{model}'.format_map(request_url_dict) + else: + path = '{model}' + else: + request_dict = _UpdateModelParameters_to_mldev( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{name}'.format_map(request_url_dict) + else: + path = '{name}' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'patch', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _Model_from_vertex(response_dict, None, parameter_model) + + if not self._api_client.vertexai: + response_dict = _Model_from_mldev(response_dict, None, parameter_model) + + return_value = types.Model._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + + self._api_client._verify_response(return_value) + return return_value + + async def delete( + self, + *, + model: str, + config: Optional[types.DeleteModelConfigOrDict] = None, + ) -> types.DeleteModelResponse: + parameter_model = types._DeleteModelParameters( + model=model, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _DeleteModelParameters_to_vertex( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{name}'.format_map(request_url_dict) + else: + path = '{name}' + else: + request_dict = _DeleteModelParameters_to_mldev( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{name}'.format_map(request_url_dict) + else: + path = '{name}' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'delete', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _DeleteModelResponse_from_vertex( + response_dict, None, parameter_model + ) + + if not self._api_client.vertexai: + response_dict = _DeleteModelResponse_from_mldev( + response_dict, None, parameter_model + ) + + return_value = types.DeleteModelResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + return_value.sdk_http_response = types.HttpResponse( + headers=response.headers + ) + self._api_client._verify_response(return_value) + return return_value + + async def count_tokens( + self, + *, + model: str, + contents: Union[types.ContentListUnion, types.ContentListUnionDict], + config: Optional[types.CountTokensConfigOrDict] = None, + ) -> types.CountTokensResponse: + """Counts the number of tokens in the given content. + + Multimodal input is supported for Gemini models. + + Args: + model (str): The model to use for counting tokens. + contents (list[types.Content]): The content to count tokens for. + config (CountTokensConfig): The configuration for counting tokens. + + Usage: + + .. code-block:: python + + response = await client.aio.models.count_tokens( + model='gemini-2.0-flash', + contents='What is your name?', + ) + print(response) + # total_tokens=5 cached_content_token_count=None + """ + + parameter_model = types._CountTokensParameters( + model=model, + contents=contents, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _CountTokensParameters_to_vertex( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{model}:countTokens'.format_map(request_url_dict) + else: + path = '{model}:countTokens' + else: + request_dict = _CountTokensParameters_to_mldev( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{model}:countTokens'.format_map(request_url_dict) + else: + path = '{model}:countTokens' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'post', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _CountTokensResponse_from_vertex( + response_dict, None, parameter_model + ) + + if not self._api_client.vertexai: + response_dict = _CountTokensResponse_from_mldev( + response_dict, None, parameter_model + ) + + return_value = types.CountTokensResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + return_value.sdk_http_response = types.HttpResponse( + headers=response.headers + ) + self._api_client._verify_response(return_value) + return return_value + + async def compute_tokens( + self, + *, + model: str, + contents: Union[types.ContentListUnion, types.ContentListUnionDict], + config: Optional[types.ComputeTokensConfigOrDict] = None, + ) -> types.ComputeTokensResponse: + """Given a list of contents, returns a corresponding TokensInfo containing the + + list of tokens and list of token ids. + + + Args: + model (str): The model to use. + contents (list[shared.Content]): The content to compute tokens for. + + Usage: + + .. code-block:: python + + response = await client.aio.models.compute_tokens( + model='gemini-2.0-flash', + contents='What is your name?', + ) + print(response) + # tokens_info=[TokensInfo(role='user', token_ids=['1841', ...], + # tokens=[b'What', b' is', b' your', b' name', b'?'])] + """ + + parameter_model = types._ComputeTokensParameters( + model=model, + contents=contents, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if not self._api_client.vertexai: + raise ValueError('This method is only supported in the Vertex AI client.') + else: + request_dict = _ComputeTokensParameters_to_vertex( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{model}:computeTokens'.format_map(request_url_dict) + else: + path = '{model}:computeTokens' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'post', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _ComputeTokensResponse_from_vertex( + response_dict, None, parameter_model + ) + + return_value = types.ComputeTokensResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + return_value.sdk_http_response = types.HttpResponse( + headers=response.headers + ) + self._api_client._verify_response(return_value) + return return_value + + async def _generate_videos( + self, + *, + model: str, + prompt: Optional[str] = None, + image: Optional[types.ImageOrDict] = None, + video: Optional[types.VideoOrDict] = None, + source: Optional[types.GenerateVideosSourceOrDict] = None, + config: Optional[types.GenerateVideosConfigOrDict] = None, + ) -> types.GenerateVideosOperation: + """Private method for generating videos asynchronously.""" + + parameter_model = types._GenerateVideosParameters( + model=model, + prompt=prompt, + image=image, + video=video, + source=source, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _GenerateVideosParameters_to_vertex( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{model}:predictLongRunning'.format_map(request_url_dict) + else: + path = '{model}:predictLongRunning' + else: + request_dict = _GenerateVideosParameters_to_mldev( + self._api_client, parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{model}:predictLongRunning'.format_map(request_url_dict) + else: + path = '{model}:predictLongRunning' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'post', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _GenerateVideosOperation_from_vertex( + response_dict, None, parameter_model + ) + + if not self._api_client.vertexai: + response_dict = _GenerateVideosOperation_from_mldev( + response_dict, None, parameter_model + ) + + return_value = types.GenerateVideosOperation._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + + self._api_client._verify_response(return_value) + return return_value + + async def generate_content( + self, + *, + model: str, + contents: Union[types.ContentListUnion, types.ContentListUnionDict], + config: Optional[types.GenerateContentConfigOrDict] = None, + ) -> types.GenerateContentResponse: + """Makes an API request to generate content using a model. + + Some models support multimodal input and output. + + Built-in MCP support is an experimental feature. + + Usage: + + .. code-block:: python + + from google.genai import types + from google import genai + + client = genai.Client( + vertexai=True, project='my-project-id', location='us-central1' + ) + + response = await client.aio.models.generate_content( + model='gemini-2.0-flash', + contents='User input: I like bagels. Answer:', + config=types.GenerateContentConfig( + system_instruction= + [ + 'You are a helpful language translator.', + 'Your mission is to translate text in English to French.' + ] + ), + ) + print(response.text) + # J'aime les bagels. + """ + # Retrieve and cache any MCP sessions if provided. + incompatible_tools_indexes = ( + _extra_utils.find_afc_incompatible_tool_indexes(config) + ) + parsed_config, mcp_to_genai_tool_adapters = ( + await _extra_utils.parse_config_for_mcp_sessions(config) + ) + if _extra_utils.should_disable_afc(parsed_config): + return await self._generate_content( + model=model, contents=contents, config=parsed_config + ) + if incompatible_tools_indexes: + original_tools_length = 0 + if isinstance(config, types.GenerateContentConfig): + if config.tools: + original_tools_length = len(config.tools) + elif isinstance(config, dict): + tools = config.get('tools', []) + if tools: + original_tools_length = len(tools) + if len(incompatible_tools_indexes) != original_tools_length: + indices_str = ', '.join(map(str, incompatible_tools_indexes)) + logger.warning( + 'Tools at indices [%s] are not compatible with automatic function ' + 'calling (AFC). AFC is disabled. If AFC is intended, please ' + 'include python callables in the tool list, and do not include ' + 'function declaration and MCP server in the tool list.', + indices_str, + ) + return await self._generate_content( + model=model, contents=contents, config=parsed_config + ) + remaining_remote_calls_afc = _extra_utils.get_max_remote_calls_afc( + parsed_config + ) + logger.info( + f'AFC is enabled with max remote calls: {remaining_remote_calls_afc}.' + ) + automatic_function_calling_history: list[types.Content] = [] + response = types.GenerateContentResponse() + while remaining_remote_calls_afc > 0: + response = await self._generate_content( + model=model, contents=contents, config=parsed_config + ) + remaining_remote_calls_afc -= 1 + if remaining_remote_calls_afc == 0: + logger.info('Reached max remote calls for automatic function calling.') + + function_map = _extra_utils.get_function_map( + parsed_config, mcp_to_genai_tool_adapters, is_caller_method_async=True + ) + if not function_map: + break + if not response: + break + if ( + not response.candidates + or not response.candidates[0].content + or not response.candidates[0].content.parts + ): + break + func_response_parts = ( + await _extra_utils.get_function_response_parts_async( + response, function_map + ) + ) + if not func_response_parts: + break + func_call_content = response.candidates[0].content + func_response_content = types.Content( + role='user', + parts=func_response_parts, + ) + contents = t.t_contents(contents) # type: ignore[assignment] + if not automatic_function_calling_history: + automatic_function_calling_history.extend(contents) # type: ignore[arg-type] + if isinstance(contents, list): + contents.append(func_call_content) # type: ignore[arg-type] + contents.append(func_response_content) # type: ignore[arg-type] + automatic_function_calling_history.append(func_call_content) + automatic_function_calling_history.append(func_response_content) + + if ( + _extra_utils.should_append_afc_history(parsed_config) + and response is not None + ): + response.automatic_function_calling_history = ( + automatic_function_calling_history + ) + return response + + async def generate_content_stream( + self, + *, + model: str, + contents: Union[types.ContentListUnion, types.ContentListUnionDict], + config: Optional[types.GenerateContentConfigOrDict] = None, + ) -> AsyncIterator[types.GenerateContentResponse]: + """Makes an API request to generate content using a model and yields the model's response in chunks. + + For the `model` parameter, supported formats for Vertex AI API include: + - The Gemini model ID, for example: 'gemini-2.0-flash' + - The full resource name starts with 'projects/', for example: + 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + - The partial resource name with 'publishers/', for example: + 'publishers/google/models/gemini-2.0-flash' or + - `/` separated publisher and model name, for example: + 'google/gemini-2.0-flash' + + For the `model` parameter, supported formats for Gemini API include: + - The Gemini model ID, for example: 'gemini-2.0-flash' + - The model name starts with 'models/', for example: + 'models/gemini-2.0-flash' + - For tuned models, the model name starts with 'tunedModels/', + for example: + 'tunedModels/1234567890123456789' + + Some models support multimodal input and output. + + Built-in MCP support is an experimental feature. + + Usage: + + .. code-block:: python + + from google.genai import types + from google import genai + + client = genai.Client( + vertexai=True, project='my-project-id', location='us-central1' + ) + + async for chunk in await client.aio.models.generate_content_stream( + model='gemini-2.0-flash', + contents='''What is a good name for a flower shop that specializes in + selling bouquets of dried flowers?''' + ): + print(chunk.text) + # **Elegant & Classic:** + # * The Dried Bloom + # * Everlasting Florals + # * Timeless Petals + + async for chunk in await client.aio.models.generate_content_stream( + model='gemini-2.0-flash', + contents=[ + types.Part.from_text('What is shown in this image?'), + types.Part.from_uri('gs://generativeai-downloads/images/scones.jpg', + 'image/jpeg') + ] + ): + print(chunk.text) + # The image shows a flat lay arrangement of freshly baked blueberry + # scones. + """ + + # Retrieve and cache any MCP sessions if provided. + incompatible_tools_indexes = ( + _extra_utils.find_afc_incompatible_tool_indexes(config) + ) + # Retrieve and cache any MCP sessions if provided. + parsed_config, mcp_to_genai_tool_adapters = ( + await _extra_utils.parse_config_for_mcp_sessions(config) + ) + if _extra_utils.should_disable_afc(parsed_config): + response = await self._generate_content_stream( + model=model, contents=contents, config=parsed_config + ) + + async def base_async_generator(model, contents, config): # type: ignore[no-untyped-def] + async for chunk in response: # type: ignore[attr-defined] + yield chunk + + return base_async_generator(model, contents, parsed_config) # type: ignore[no-untyped-call, no-any-return] + + if incompatible_tools_indexes: + original_tools_length = 0 + if isinstance(config, types.GenerateContentConfig): + if config.tools: + original_tools_length = len(config.tools) + elif isinstance(config, dict): + tools = config.get('tools', []) + if tools: + original_tools_length = len(tools) + if len(incompatible_tools_indexes) != original_tools_length: + indices_str = ', '.join(map(str, incompatible_tools_indexes)) + logger.warning( + 'Tools at indices [%s] are not compatible with automatic function ' + 'calling (AFC). AFC is disabled. If AFC is intended, please ' + 'include python callables in the tool list, and do not include ' + 'function declaration and MCP server in the tool list.', + indices_str, + ) + response = await self._generate_content_stream( + model=model, contents=contents, config=parsed_config + ) + + async def base_async_generator(model, contents, config): # type: ignore[no-untyped-def] + async for chunk in response: # type: ignore[attr-defined] + yield chunk + + return base_async_generator(model, contents, parsed_config) # type: ignore[no-untyped-call, no-any-return] + + # With tool compatibility confirmed, validate that the configuration are + # compatible with each other and raise an error if invalid. + _extra_utils.raise_error_for_afc_incompatible_config(parsed_config) + + async def async_generator(model, contents, config): # type: ignore[no-untyped-def] + remaining_remote_calls_afc = _extra_utils.get_max_remote_calls_afc(config) + logger.info( + f'AFC is enabled with max remote calls: {remaining_remote_calls_afc}.' + ) + automatic_function_calling_history: list[types.Content] = [] + func_response_parts = None + chunk = None + i = 0 + while remaining_remote_calls_afc > 0: + i += 1 + response = await self._generate_content_stream( + model=model, contents=contents, config=config + ) + # TODO: b/453739108 - make AFC logic more robust like the other 3 methods. + if i > 1: + logger.info(f'AFC remote call {i} is done.') + remaining_remote_calls_afc -= 1 + if i > 1 and remaining_remote_calls_afc == 0: + logger.info( + 'Reached max remote calls for automatic function calling.' + ) + + function_map = _extra_utils.get_function_map( + config, mcp_to_genai_tool_adapters, is_caller_method_async=True + ) + + if i == 1: + # First request gets a function call. + # Then get function response parts. + # Yield chunks only if there's no function response parts. + async for chunk in response: # type: ignore[attr-defined] + if not function_map: + contents = _extra_utils.append_chunk_contents(contents, chunk) + yield chunk + else: + if ( + not chunk.candidates + or not chunk.candidates[0].content + or not chunk.candidates[0].content.parts + ): + break + func_response_parts = ( + await _extra_utils.get_function_response_parts_async( + chunk, function_map + ) + ) + if not func_response_parts: + contents = _extra_utils.append_chunk_contents(contents, chunk) + yield chunk + + else: + # Second request and beyond, yield chunks. + async for chunk in response: # type: ignore[attr-defined] + + if _extra_utils.should_append_afc_history(config): + chunk.automatic_function_calling_history = ( + automatic_function_calling_history + ) + contents = _extra_utils.append_chunk_contents(contents, chunk) + yield chunk + if ( + chunk is None + or not chunk.candidates + or not chunk.candidates[0].content + or not chunk.candidates[0].content.parts + ): + break + func_response_parts = ( + await _extra_utils.get_function_response_parts_async( + chunk, function_map + ) + ) + if not function_map: + break + + if not func_response_parts: + break + + if chunk is None: + continue + # Append function response parts to contents for the next request. + func_call_content = chunk.candidates[0].content + func_response_content = types.Content( + role='user', + parts=func_response_parts, + ) + contents = t.t_contents(contents) + if not automatic_function_calling_history: + automatic_function_calling_history.extend(contents) + if isinstance(contents, list) and func_call_content is not None: + contents.append(func_call_content) + contents.append(func_response_content) + if func_call_content is not None: + automatic_function_calling_history.append(func_call_content) + automatic_function_calling_history.append(func_response_content) + + return async_generator(model, contents, parsed_config) # type: ignore[no-untyped-call, no-any-return] + + async def edit_image( + self, + *, + model: str, + prompt: str, + reference_images: list[types._ReferenceImageAPIOrDict], + config: Optional[types.EditImageConfigOrDict] = None, + ) -> types.EditImageResponse: + """Edits an image based on a text description and configuration. + + Args: + model (str): The model to use. + prompt (str): A text description of the edit to apply to the image. + reference_images (list[Union[RawReferenceImage, MaskReferenceImage, + ControlReferenceImage, StyleReferenceImage, SubjectReferenceImage]): The + reference images for editing. + config (EditImageConfig): Configuration for editing. + + Usage: + + .. code-block:: python + + from google.genai.types import RawReferenceImage, MaskReferenceImage + + raw_ref_image = RawReferenceImage( + reference_id=1, + reference_image=types.Image.from_file(IMAGE_FILE_PATH), + ) + + mask_ref_image = MaskReferenceImage( + reference_id=2, + config=types.MaskReferenceConfig( + mask_mode='MASK_MODE_FOREGROUND', + mask_dilation=0.06, + ), + ) + response = await client.aio.models.edit_image( + model='imagen-3.0-capability-001', + prompt='man with dog', + reference_images=[raw_ref_image, mask_ref_image], + config=types.EditImageConfig( + edit_mode= "EDIT_MODE_INPAINT_INSERTION", + number_of_images= 1, + include_rai_reason= True, + ) + ) + response.generated_images[0].image.show() + # Shows a man with a dog instead of a cat. + """ + return await self._edit_image( + model=model, + prompt=prompt, + reference_images=reference_images, + config=config, + ) + + async def list( + self, + *, + config: Optional[types.ListModelsConfigOrDict] = None, + ) -> AsyncPager[types.Model]: + """Makes an API request to list the available models. + + If `query_base` is set to True in the config or not set (default), the + API will return all available base models. If set to False, it will return + all tuned models. + + Args: + config (ListModelsConfigOrDict): Configuration for retrieving models. + + Usage: + + .. code-block:: python + + response = await client.aio.models.list(config={'page_size': 5}) + print(response.page) + # [Model(name='projects/./locations/./models/123', display_name='my_model' + + response = await client.aio.models.list( + config={'page_size': 5, 'query_base': True} + ) + print(response.page) + # [Model(name='publishers/google/models/gemini-2.0-flash-exp' ... + """ + + config = ( + types._ListModelsParameters(config=config).config + or types.ListModelsConfig() + ) + if config.query_base is None: + config.query_base = True + if self._api_client.vertexai: + config = config.copy() + if not config.query_base: + # Filter for tuning jobs artifacts by labels. + filter_value = config.filter + config.filter = ( + filter_value + '&filter=labels.tune-type:*' + if filter_value + else 'labels.tune-type:*' + ) + return AsyncPager( + 'models', + self._list, + await self._list(config=config), + config, + ) + + async def generate_images( + self, + *, + model: str, + prompt: str, + config: Optional[types.GenerateImagesConfigOrDict] = None, + ) -> types.GenerateImagesResponse: + """Generates images based on a text description and configuration. + + Args: + model (str): The model to use. + prompt (str): A text description of the images to generate. + config (GenerateImagesConfig): Configuration for generation. + + Usage: + + .. code-block:: python + + response = await client.aio.models.generate_images( + model='imagen-3.0-generate-002', + prompt='Man with a dog', + config=types.GenerateImagesConfig( + number_of_images= 1, + include_rai_reason= True, + ) + ) + response.generated_images[0].image.show() + # Shows a man with a dog. + """ + api_response = await self._generate_images( + model=model, + prompt=prompt, + config=config, + ) + positive_prompt_safety_attributes = None + generated_images = [] + if not api_response or not api_response.generated_images: + return api_response + + for generated_image in api_response.generated_images: + if ( + generated_image.safety_attributes + and generated_image.safety_attributes.content_type + == 'Positive Prompt' + ): + positive_prompt_safety_attributes = generated_image.safety_attributes + else: + generated_images.append(generated_image) + + response = types.GenerateImagesResponse( + generated_images=generated_images, + positive_prompt_safety_attributes=positive_prompt_safety_attributes, + ) + return response + + async def upscale_image( + self, + *, + model: str, + image: types.ImageOrDict, + upscale_factor: str, + config: Optional[types.UpscaleImageConfigOrDict] = None, + ) -> types.UpscaleImageResponse: + """Makes an API request to upscale a provided image. + + Args: + model (str): The model to use. + image (Image): The input image for upscaling. + upscale_factor (str): The factor to upscale the image (x2 or x4). + config (UpscaleImageConfig): Configuration for upscaling. + + Usage: + + .. code-block:: python + + from google.genai.types import Image + + IMAGE_FILE_PATH="my-image.png" + response = await client.aio.models.upscale_image( + model='imagen-3.0-generate-001', + image=types.Image.from_file(IMAGE_FILE_PATH), + upscale_factor='x2', + ) + response.generated_images[0].image.show() + # Opens my-image.png which is upscaled by a factor of 2. + """ + + # Validate config. + types.UpscaleImageParameters( + model=model, + image=image, + upscale_factor=upscale_factor, + config=config, + ) + + # Convert to API config. + config = config or {} + if isinstance(config, types.UpscaleImageConfig): + config_dct = config.model_dump() + else: + config_dct = dict(config) + api_config = types._UpscaleImageAPIConfigDict( + http_options=config_dct.get('http_options', None), + output_gcs_uri=config_dct.get('output_gcs_uri', None), + safety_filter_level=config_dct.get('safety_filter_level', None), + person_generation=config_dct.get('person_generation', None), + include_rai_reason=config_dct.get('include_rai_reason', None), + output_mime_type=config_dct.get('output_mime_type', None), + output_compression_quality=config_dct.get( + 'output_compression_quality', None + ), + enhance_input_image=config_dct.get('enhance_input_image', None), + image_preservation_factor=config_dct.get( + 'image_preservation_factor', None + ), + labels=config_dct.get('labels', None), + ) # pylint: disable=protected-access + + # Provide default values through API config. + api_config['mode'] = 'upscale' + api_config['number_of_images'] = 1 + + return await self._upscale_image( + model=model, + image=image, + upscale_factor=upscale_factor, + config=api_config, + ) + + async def generate_videos( + self, + *, + model: str, + prompt: Optional[str] = None, + image: Optional[types.ImageOrDict] = None, + video: Optional[types.VideoOrDict] = None, + source: Optional[types.GenerateVideosSourceOrDict] = None, + config: Optional[types.GenerateVideosConfigOrDict] = None, + ) -> types.GenerateVideosOperation: + """Generates videos based on an input (text, image, or video) and configuration. + + The following use cases are supported: + 1. Text to video generation. + 2a. Image to video generation (additional text prompt is optional). + 2b. Image to video generation with frame interpolation (specify last_frame + in config). + 3. Video extension (additional text prompt is optional) + + Args: + model: The model to use. + prompt: The text prompt for generating the videos. Optional for image to + video and video extension use cases. This argument is deprecated, please + use source instead. + image: The input image for generating the videos. Optional if prompt is + provided. This argument is deprecated, please use source instead. + video: The input video for video extension use cases. Optional if prompt + or image is provided. This argument is deprecated, please use source + instead. + source: The input source for generating the videos (prompt, image, and/or + video) + config: Configuration for generation. + + Usage: + + ``` + operation = client.models.generate_videos( + model="veo-2.0-generate-001", + source=types.GenerateVideosSource( + prompt="A neon hologram of a cat driving at top speed", + ), + ) + while not operation.done: + time.sleep(10) + operation = client.operations.get(operation) + + operation.result.generated_videos[0].video.uri + ``` + """ + if (prompt or image or video) and source: + raise ValueError( + 'Source and prompt/image/video are mutually exclusive.' + + ' Please only use source.' + ) + # Gemini Developer API does not support video bytes. + video_dct: dict[str, Any] = {} + if not self._api_client.vertexai and video: + if isinstance(video, types.Video): + video_dct = video.model_dump() + else: + video_dct = dict(video) + + if video_dct.get('uri') and video_dct.get('video_bytes'): + video = types.Video( + uri=video_dct.get('uri'), mime_type=video_dct.get('mime_type') + ) + elif not self._api_client.vertexai and source: + if isinstance(source, types.GenerateVideosSource): + source_dct = source.model_dump() + video_dct = source_dct.get('video', {}) + else: + source_dct = dict(source) + if isinstance(source_dct.get('video'), types.Video): + video_obj: types.Video = source_dct.get('video', types.Video()) + video_dct = video_obj.model_dump() + if video_dct and video_dct.get('uri') and video_dct.get('video_bytes'): + source = types.GenerateVideosSource( + prompt=source_dct.get('prompt'), + image=source_dct.get('image'), + video=types.Video( + uri=video_dct.get('uri'), + mime_type=video_dct.get('mime_type'), + ), + ) + return await self._generate_videos( + model=model, + prompt=prompt, + image=image, + video=video, + source=source, + config=config, + ) + + async def embed_content( + self, + *, + model: str, + contents: Union[types.ContentListUnion, types.ContentListUnionDict], + config: Optional[types.EmbedContentConfigOrDict] = None, + ) -> types.EmbedContentResponse: + """Calculates embeddings for the given contents. + + Args: + model (str): The model to use. + contents (list[Content]): The contents to embed. + config (EmbedContentConfig): Optional configuration for embeddings. + + Usage: + + .. code-block:: python + + embeddings = await client.aio.models.embed_content( + model= 'text-embedding-004', + contents=[ + 'What is your name?', + 'What is your favorite color?', + ], + config={ + 'output_dimensionality': 64 + }, + ) + + multimodal_embeddings = await client.aio.models.embed_content( + model='gemini-embedding-2-preview', + contents=[ + types.Part.from_uri( + file_uri='gs://generativeai-downloads/images/scones.jpg', + mime_type='image/jpeg', + ), + ], + config={ + 'output_dimensionality': 64 + }, + ) + """ + if not self._api_client.vertexai: + if 'gemini-embedding-2' in model: + contents = t.t_contents(contents) # type: ignore[assignment] + return await self._embed_content( + model=model, contents=contents, config=config + ) + if t.t_is_vertex_embed_content_model(model): + normalized_contents = t.t_contents(contents) + if len(normalized_contents) > 1: + raise ValueError( + 'The embedContent API for this model only supports one content at a' + ' time.' + ) + return await self._embed_content( + model=model, + contents=contents, + content=normalized_contents[0], + embedding_api_type=types.EmbeddingApiType.EMBED_CONTENT, + config=config, + ) + else: + return await self._embed_content( + model=model, + contents=contents, + embedding_api_type=types.EmbeddingApiType.PREDICT, + config=config, + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/operations.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/operations.py new file mode 100644 index 0000000000000000000000000000000000000000..223338adb852c22dcd4845db9c007111baff456e --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/operations.py @@ -0,0 +1,585 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# Code generated by the Google Gen AI SDK generator DO NOT EDIT. + +import json +import logging +from typing import Any, Optional, TypeVar, Union +from urllib.parse import urlencode + +from . import _api_module +from . import _common +from . import types +from ._common import get_value_by_path as getv +from ._common import set_value_by_path as setv + +logger = logging.getLogger('google_genai.operations') + + +def _FetchPredictOperationParameters_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['operation_name']) is not None: + setv(to_object, ['operationName'], getv(from_object, ['operation_name'])) + + if getv(from_object, ['resource_name']) is not None: + setv( + to_object, + ['_url', 'resourceName'], + getv(from_object, ['resource_name']), + ) + + return to_object + + +def _GetOperationParameters_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['operation_name']) is not None: + setv( + to_object, + ['_url', 'operationName'], + getv(from_object, ['operation_name']), + ) + + return to_object + + +def _GetOperationParameters_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['operation_name']) is not None: + setv( + to_object, + ['_url', 'operationName'], + getv(from_object, ['operation_name']), + ) + + return to_object + + +def _GetProjectOperationParameters_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['operation_id']) is not None: + setv( + to_object, ['_url', 'operation_id'], getv(from_object, ['operation_id']) + ) + + return to_object + + +class Operations(_api_module.BaseModule): + + def _get_videos_operation( + self, + *, + operation_name: str, + config: Optional[types.GetOperationConfigOrDict] = None, + ) -> Any: + parameter_model = types._GetOperationParameters( + operation_name=operation_name, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _GetOperationParameters_to_vertex(parameter_model) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{operationName}'.format_map(request_url_dict) + else: + path = '{operationName}' + else: + request_dict = _GetOperationParameters_to_mldev(parameter_model) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{operationName}'.format_map(request_url_dict) + else: + path = '{operationName}' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request('get', path, request_dict, http_options) + + response_dict = {} if not response.body else json.loads(response.body) + + return response_dict + + def _fetch_predict_videos_operation( + self, + *, + operation_name: str, + resource_name: str, + config: Optional[types.FetchPredictOperationConfigOrDict] = None, + ) -> Any: + parameter_model = types._FetchPredictOperationParameters( + operation_name=operation_name, + resource_name=resource_name, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if not self._api_client.vertexai: + raise ValueError('This method is only supported in the Vertex AI client.') + else: + request_dict = _FetchPredictOperationParameters_to_vertex(parameter_model) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{resourceName}:fetchPredictOperation'.format_map( + request_url_dict + ) + else: + path = '{resourceName}:fetchPredictOperation' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request( + 'post', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + return response_dict + + def _get( + self, + *, + operation_id: str, + config: Optional[types.GetOperationConfigOrDict] = None, + ) -> types.ProjectOperation: + parameter_model = types._GetProjectOperationParameters( + operation_id=operation_id, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if not self._api_client.vertexai: + raise ValueError('This method is only supported in the Vertex AI client.') + else: + request_dict = _GetProjectOperationParameters_to_vertex(parameter_model) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'operations/{operation_id}'.format_map(request_url_dict) + else: + path = 'operations/{operation_id}' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request('get', path, request_dict, http_options) + + response_dict = {} if not response.body else json.loads(response.body) + + return_value = types.ProjectOperation._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + + self._api_client._verify_response(return_value) + return return_value + + T = TypeVar('T', bound=types.Operation) + + def get( + self, + operation: T, + *, + config: Optional[types.GetOperationConfigOrDict] = None, + ) -> T: + """Gets the status of a long-running operation. + + Args: + operation (Operation): The operation instance to get the status for. + config (GetOperationConfig): Configuration for getting the operation. + + Returns: + Operation: The updated operation instance with the latest status or + result. + + Usage: + + .. code-block:: python + + import time + + operation = client.models.generate_videos( + model="veo-2.0-generate-001", + source=types.GenerateVideosSource( + prompt="A neon hologram of a cat driving at top speed", + ), + ) + while not operation.done: + time.sleep(10) + operation = client.operations.get(operation) + + print(operation.result) + """ + # Currently, only GenerateVideosOperation is supported. + # TODO(b/398040607): Support short form names + operation_name = operation.name + if not operation_name: + raise ValueError('Operation name is empty.') + + # TODO(b/398233524): Cast operation types + if self._api_client.vertexai: + resource_name = operation_name.rpartition('/operations/')[0] + http_options = types.HttpOptions() + if isinstance(config, dict): + dict_options = config.get('http_options', None) + if dict_options is not None: + http_options = types.HttpOptions(**dict(dict_options)) + elif isinstance(config, types.GetOperationConfig) and config is not None: + http_options = ( + config.http_options + if config.http_options is not None + else types.HttpOptions() + ) + fetch_operation_config = types.FetchPredictOperationConfig( + http_options=http_options + ) + response_dict = self._fetch_predict_videos_operation( + operation_name=operation_name, + resource_name=resource_name, + config=fetch_operation_config, + ) + + response_operation = operation.from_api_response( + response_dict, is_vertex_ai=True + ) + + self._api_client._verify_response(response_operation) # type: ignore [arg-type] + return response_operation # type: ignore[no-any-return] + else: + response_dict = self._get_videos_operation( + operation_name=operation_name, + config=config, + ) + response_operation = operation.from_api_response( + response_dict, is_vertex_ai=False + ) + + self._api_client._verify_response(response_operation) # type: ignore [arg-type] + return response_operation # type: ignore[no-any-return] + + +class AsyncOperations(_api_module.BaseModule): + + async def _get_videos_operation( + self, + *, + operation_name: str, + config: Optional[types.GetOperationConfigOrDict] = None, + ) -> Any: + parameter_model = types._GetOperationParameters( + operation_name=operation_name, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _GetOperationParameters_to_vertex(parameter_model) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{operationName}'.format_map(request_url_dict) + else: + path = '{operationName}' + else: + request_dict = _GetOperationParameters_to_mldev(parameter_model) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{operationName}'.format_map(request_url_dict) + else: + path = '{operationName}' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'get', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + return response_dict + + async def _fetch_predict_videos_operation( + self, + *, + operation_name: str, + resource_name: str, + config: Optional[types.FetchPredictOperationConfigOrDict] = None, + ) -> Any: + parameter_model = types._FetchPredictOperationParameters( + operation_name=operation_name, + resource_name=resource_name, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if not self._api_client.vertexai: + raise ValueError('This method is only supported in the Vertex AI client.') + else: + request_dict = _FetchPredictOperationParameters_to_vertex(parameter_model) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{resourceName}:fetchPredictOperation'.format_map( + request_url_dict + ) + else: + path = '{resourceName}:fetchPredictOperation' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'post', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + return response_dict + + async def _get( + self, + *, + operation_id: str, + config: Optional[types.GetOperationConfigOrDict] = None, + ) -> types.ProjectOperation: + parameter_model = types._GetProjectOperationParameters( + operation_id=operation_id, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if not self._api_client.vertexai: + raise ValueError('This method is only supported in the Vertex AI client.') + else: + request_dict = _GetProjectOperationParameters_to_vertex(parameter_model) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'operations/{operation_id}'.format_map(request_url_dict) + else: + path = 'operations/{operation_id}' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'get', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + return_value = types.ProjectOperation._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + + self._api_client._verify_response(return_value) + return return_value + + T = TypeVar('T', bound=types.Operation) + + async def get( + self, + operation: T, + *, + config: Optional[types.GetOperationConfigOrDict] = None, + ) -> T: + """Gets the status of a long-running operation. + + Args: + operation (Operation): The operation instance to get the status for. + config (GetOperationConfig): Configuration for getting the operation. + + Returns: + Operation: The updated operation instance with the latest status or + result. + + Usage: + + .. code-block:: python + + import asyncio + + operation = await client.aio.models.generate_videos( + model="veo-2.0-generate-001", + source=types.GenerateVideosSource( + prompt="A neon hologram of a cat driving at top speed", + ), + ) + while not operation.done: + await asyncio.sleep(10) + operation = await client.aio.operations.get(operation) + + print(operation.result) + """ + # Currently, only GenerateVideosOperation is supported. + operation_name = operation.name + if not operation_name: + raise ValueError('Operation name is empty.') + + if self._api_client.vertexai: + resource_name = operation_name.rpartition('/operations/')[0] + http_options = types.HttpOptions() + if isinstance(config, dict): + dict_options = config.get('http_options', None) + if dict_options is not None: + http_options = types.HttpOptions(**dict(dict_options)) + elif isinstance(config, types.GetOperationConfig) and config is not None: + http_options = ( + config.http_options + if config.http_options is not None + else types.HttpOptions() + ) + fetch_operation_config = types.FetchPredictOperationConfig( + http_options=http_options + ) + response_dict = await self._fetch_predict_videos_operation( + operation_name=operation_name, + resource_name=resource_name, + config=fetch_operation_config, + ) + response_operation = operation.from_api_response( + response_dict, is_vertex_ai=True + ) + return response_operation # type: ignore[no-any-return] + else: + response_dict = await self._get_videos_operation( + operation_name=operation_name, + config=config, + ) + response_operation = operation.from_api_response( + response_dict, is_vertex_ai=False + ) + return response_operation # type: ignore[no-any-return] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/pagers.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/pagers.py new file mode 100644 index 0000000000000000000000000000000000000000..aa1c978ac2162832241b7852e6d90e4a7b962be5 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/pagers.py @@ -0,0 +1,268 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +"""Pagers for the GenAI List APIs.""" + +# pylint: disable=protected-access + +import copy +from typing import Any, AsyncIterator, Awaitable, Callable, Generic, Iterator, Literal, TypeVar, Union +from . import _common +from . import types + +T = TypeVar('T') + +PagedItem = Literal[ + 'batch_jobs', + 'models', + 'tuning_jobs', + 'files', + 'cached_contents', + 'file_search_stores', + 'documents', +] + + +class _BasePager(Generic[T]): + """Base pager class for iterating through paginated results.""" + + def _init_page( + self, + name: PagedItem, + request: Callable[..., Any], + response: Any, + config: Any, + ) -> None: + self._name = name + self._request = request + + self._page = getattr(response, self._name) or [] + self._idx = 0 + + self._sdk_http_response = getattr(response, 'sdk_http_response', None) + + if not config: + request_config = {} + elif isinstance(config, dict): + request_config = copy.deepcopy(config) + else: + request_config = dict(config) + request_config['page_token'] = getattr(response, 'next_page_token') + self._config = request_config + + self._page_size: int = request_config.get('page_size', len(self._page)) + + def __init__( + self, + name: PagedItem, + request: Callable[..., Any], + response: Any, + config: Any, + ): + self._init_page(name, request, response, config) + + @property + def page(self) -> list[T]: + """Returns a subset of the entire list of items. + + For the number of items returned, see `pageSize()`. + + Usage: + + .. code-block:: python + + batch_jobs_pager = client.batches.list(config={'page_size': 5}) + print(f"first page: {batch_jobs_pager.page}") + # first page: [BatchJob(name='projects/./locations/./batchPredictionJobs/1 + """ + + return self._page + + @property + def name(self) -> PagedItem: + """Returns the type of paged item (for example, ``batch_jobs``). + + Usage: + + .. code-block:: python + + batch_jobs_pager = client.batches.list(config={'page_size': 5}) + print(f"name: {batch_jobs_pager.name}") + # name: batch_jobs + """ + + return self._name + + @property + def page_size(self) -> int: + """Returns the maximum number of items fetched by the pager at one time. + + Usage: + + .. code-block:: python + + batch_jobs_pager = client.batches.list(config={'page_size': 5}) + print(f"page_size: {batch_jobs_pager.page_size}") + # page_size: 5 + """ + + return self._page_size + + @property + def sdk_http_response(self) -> Union[types.HttpResponse, None]: + """Returns the http response of the API response.""" + + return self._sdk_http_response + + @property + def config(self) -> _common.StringDict: + """Returns the configuration when making the API request for the next page. + + A configuration is a set of optional parameters and arguments that can be + used to customize the API request. For example, the ``page_token`` parameter + contains the token to request the next page. + + Usage: + + .. code-block:: python + + batch_jobs_pager = client.batches.list(config={'page_size': 5}) + print(f"config: {batch_jobs_pager.config}") + # config: {'page_size': 5, 'page_token': 'AMEw9yO5jnsGnZJLHSKDFHJJu'} + """ + + return self._config + + def __len__(self) -> int: + """Returns the total number of items in the current page.""" + return len(self.page) + + def __getitem__(self, index: int) -> T: + """Returns the item at the given index.""" + return self.page[index] + + def _init_next_page(self, response: Any) -> None: + """Initializes the next page from the response. + + This is an internal method that should be called by subclasses after + fetching the next page. + + Args: + response: The response object from the API request. + """ + self._init_page(self.name, self._request, response, self.config) + + +class Pager(_BasePager[T]): + """Pager class for iterating through paginated results.""" + + def __next__(self) -> T: + """Returns the next item.""" + if self._idx >= len(self): + try: + self.next_page() + except IndexError: + raise StopIteration + + item = self.page[self._idx] + self._idx += 1 + return item + + def __iter__(self) -> Iterator[T]: + """Returns an iterator over the items.""" + self._idx = 0 + return self + + def next_page(self) -> list[T]: + """Fetches the next page of items. This makes a new API request. + + Usage: + + .. code-block:: python + + batch_jobs_pager = client.batches.list(config={'page_size': 5}) + print(f"current page: {batch_jobs_pager.page}") + batch_jobs_pager.next_page() + print(f"next page: {batch_jobs_pager.page}") + # current page: [BatchJob(name='projects/.../batchPredictionJobs/1 + # next page: [BatchJob(name='projects/.../batchPredictionJobs/6 + """ + + if not self.config.get('page_token'): + raise IndexError('No more pages to fetch.') + + response = self._request(config=self.config) + self._init_next_page(response) + return self.page + + +class AsyncPager(_BasePager[T]): + """AsyncPager class for iterating through paginated results.""" + + def __init__( + self, + name: PagedItem, + request: Callable[..., Awaitable[Any]], + response: Any, + config: Any, + ): + super().__init__(name, request, response, config) + + def __aiter__(self) -> AsyncIterator[T]: + """Returns an async iterator over the items.""" + self._idx = 0 + return self + + async def __anext__(self) -> T: + """Returns the next item asynchronously.""" + if self._idx >= len(self): + try: + await self.next_page() + except IndexError: + raise StopAsyncIteration + + item = self.page[self._idx] + self._idx += 1 + return item + + async def next_page(self) -> list[T]: + """Fetches the next page of items asynchronously. + + This makes a new API request. + + Returns: + The next page of items. + + Raises: + IndexError: No more pages to fetch. + + Usage: + + .. code-block:: python + + batch_jobs_pager = await client.aio.batches.list(config={'page_size': 5}) + print(f"current page: {batch_jobs_pager.page}") + await batch_jobs_pager.next_page() + print(f"next page: {batch_jobs_pager.page}") + # current page: [BatchJob(name='projects/.../batchPredictionJobs/1 + # next page: [BatchJob(name='projects/.../batchPredictionJobs/6 + """ + + if not self.config.get('page_token'): + raise IndexError('No more pages to fetch.') + + response = await self._request(config=self.config) + self._init_next_page(response) + return self.page diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/py.typed b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..72927972de18126aa2acfd407f56e3edf46cd36f --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/py.typed @@ -0,0 +1 @@ +# see: https://peps.python.org/pep-0561/ \ No newline at end of file diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..30c0f83306723602c009155f30148bf690bc774e --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/__init__.py @@ -0,0 +1,21 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for the Google GenAI SDK.""" + + +import pytest +pytest.register_assert_rewrite('genai.replay_api_client') \ No newline at end of file diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/afc/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/afc/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a6c6e326b6d94850426fd83c748187ef35a4c9c8 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/afc/__init__.py @@ -0,0 +1,21 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""AFC helper function unit tests. + +For AFC end to end test, please write test cases in +test_generate_content_tools.py module +""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/afc/test_convert_if_exist_pydantic_model.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/afc/test_convert_if_exist_pydantic_model.py new file mode 100644 index 0000000000000000000000000000000000000000..776227a2a573552c7b14a6fe7716814e78b85e0d --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/afc/test_convert_if_exist_pydantic_model.py @@ -0,0 +1,309 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Test convert_if_exist_pydantic_model.""" + +import inspect +from typing import Optional, Union +import pydantic +import pytest +import sys +from ... import errors +from ..._extra_utils import convert_if_exist_pydantic_model + + +def test_builtin_types(): + assert convert_if_exist_pydantic_model(1, int, 'param_name', 'func_name') == 1 + assert ( + convert_if_exist_pydantic_model(1.0, float, 'param_name', 'func_name') + == 1.0 + ) + assert ( + convert_if_exist_pydantic_model('1.0', str, 'param_name', 'func_name') + == '1.0' + ) + assert ( + convert_if_exist_pydantic_model(True, bool, 'param_name', 'func_name') + is True + ) + assert convert_if_exist_pydantic_model( + [1], list, 'param_name', 'func_name' + ) == [1] + assert convert_if_exist_pydantic_model( + {'key1': 1}, dict, 'param_name', 'func_name' + ) == {'key1': 1} + assert convert_if_exist_pydantic_model( + {'key1': 1, 'key2': 2}, dict[str, int], 'param_name', 'func_name' + ) == {'key1': 1, 'key2': 2} + + +def test_value_int_annotation_float(): + assert ( + convert_if_exist_pydantic_model(1, float, 'param_name', 'func_name') + == 1.0 + ) + + +def test_union_types(): + assert ( + convert_if_exist_pydantic_model( + 1, Union[int, float], 'param_name', 'func_name' + ) + == 1 + ) + assert ( + convert_if_exist_pydantic_model( + 1.0, Union[int, float], 'param_name', 'func_name' + ) + == 1.0 + ) + assert ( + convert_if_exist_pydantic_model( + '1.0', Union[str, float], 'param_name', 'func_name' + ) + == '1.0' + ) + assert ( + convert_if_exist_pydantic_model( + True, Union[bool, str], 'param_name', 'func_name' + ) + is True + ) + + # | in 3.10+ + if sys.version_info >= (3, 10): + assert ( + convert_if_exist_pydantic_model(1, int | float, 'param_name', 'func_name') + == 1 + ) + + +def test_nested_pydantic_model(): + class SimpleModel(pydantic.BaseModel): + key1_simple: int + key2_simple: float + + class ComplexModel(pydantic.BaseModel): + key1_complex: SimpleModel + key2_complex: list[SimpleModel] + key3_complex: dict[str, SimpleModel] + + def foo(_: ComplexModel): + pass + + annotation = inspect.signature(foo).parameters['_'].annotation + original_args = { + 'key1_complex': {'key1_simple': 1, 'key2_simple': 1.0}, + 'key2_complex': [ + {'key1_simple': 2, 'key2_simple': 2.0}, + {'key1_simple': 3, 'key2_simple': 3.0}, + ], + 'key3_complex': { + 'key1_simple': {'key1_simple': 4, 'key2_simple': 4.0}, + 'key2_simple': {'key1_simple': 5, 'key2_simple': 5.0}, + }, + } + + converted_args = convert_if_exist_pydantic_model( + original_args, annotation, 'param_name', 'func_name' + ) + assert isinstance(converted_args, ComplexModel) + assert isinstance(converted_args.key1_complex, SimpleModel) + assert isinstance(converted_args.key2_complex[0], SimpleModel) + assert isinstance(converted_args.key2_complex[1], SimpleModel) + assert isinstance(converted_args.key3_complex['key1_simple'], SimpleModel) + assert isinstance(converted_args.key3_complex['key2_simple'], SimpleModel) + assert converted_args.model_dump() == original_args + + +def test_pydantic_model_in_list_union_type(): + class SimpleModel(pydantic.BaseModel): + key1_simple: int + key2_simple: float + + def foo(_: list[Union[int, SimpleModel]]): + pass + + annotation = inspect.signature(foo).parameters['_'].annotation + original_args = [1, {'key1_simple': 1, 'key2_simple': 1.0}] + + converted_args = convert_if_exist_pydantic_model( + original_args, annotation, 'param_name', 'func_name' + ) + + assert isinstance(converted_args, list) + assert len(converted_args) == 2 + assert isinstance(converted_args[0], int) + assert isinstance(converted_args[1], SimpleModel) + assert converted_args[0] == original_args[0] + assert converted_args[1].model_dump() == original_args[1] + + +def test_generic_list_type(): + def foo(_: Optional[list[Union[int, float]]]): + pass + + annotation = inspect.signature(foo).parameters['_'].annotation + original_args = [1, 1.5] + + converted_args = convert_if_exist_pydantic_model( + original_args, annotation, 'param_name', 'func_name' + ) + + assert isinstance(converted_args, list) + assert len(converted_args) == 2 + assert isinstance(converted_args[0], int) + assert isinstance(converted_args[1], float) + assert converted_args[0] == original_args[0] + + +@pytest.mark.skipif(sys.version_info < (3, 10), reason='need python 3.10+') +def test_pydantic_model_with_union_and_generic_type(): + class Model1(pydantic.BaseModel): + arg1: Union[int, float] + arg2: list[str] + arg3: int | float # python 3.9+ + arg4: Union[list[str], str] + + def foo(_: Optional[list[Union[int, Model1]]]): + pass + + annotation = inspect.signature(foo).parameters['_'].annotation + original_args = [1, {'arg1': 1, 'arg2': ['a'], 'arg3': 1.0, 'arg4': '1.0'}] + + converted_args = convert_if_exist_pydantic_model( + original_args, annotation, 'param_name', 'func_name' + ) + + assert isinstance(converted_args, list) + assert len(converted_args) == 2 + assert isinstance(converted_args[0], int) + assert isinstance(converted_args[1], Model1) + assert converted_args[0] == original_args[0] + + +def test_unknown_pydantic_model_argument_error(): + class SimpleModel(pydantic.BaseModel): + key1_simple: int + key2_simple: float + + def foo(_: SimpleModel): + pass + + annotation = inspect.signature(foo).parameters['_'].annotation + original_args = {'key3_simple': 1, 'key2_simple': 1.0} + + with pytest.raises(errors.UnknownFunctionCallArgumentError): + convert_if_exist_pydantic_model( + original_args, annotation, 'param_name', 'func_name' + ) + + +def test_unknown_pydantic_model_argument_error_with_union_type(): + class SimpleModel1(pydantic.BaseModel): + key1_simple: int + key2_simple: float + + class SimpleModel2(pydantic.BaseModel): + key3_simple: str + key4_simple: float + + def foo(_: Union[SimpleModel1, SimpleModel2]): + pass + + annotation = inspect.signature(foo).parameters['_'].annotation + original_args = {'key5_simple': 1, 'key4_simple': 1.0} + + with pytest.raises(errors.UnknownFunctionCallArgumentError): + convert_if_exist_pydantic_model( + original_args, annotation, 'param_name', 'func_name' + ) + + +def test_unknown_pydantic_model_argument_error_with_union_type_and_builtin_type(): + class SimpleModel1(pydantic.BaseModel): + key1_simple: int + key2_simple: float + + def foo(_: Union[SimpleModel1, int]): + pass + + annotation = inspect.signature(foo).parameters['_'].annotation + original_args = {'key5_simple': 1, 'key4_simple': 1.0} + + with pytest.raises(errors.UnknownFunctionCallArgumentError): + convert_if_exist_pydantic_model( + original_args, annotation, 'param_name', 'func_name' + ) + + +def test_incompatible_value_and_annotation(): + with pytest.raises(errors.UnknownFunctionCallArgumentError): + convert_if_exist_pydantic_model( + {'key1_simple': 1, 'key2_simple': 1.0}, + int, + 'param_name', + 'func_name', + ) + with pytest.raises(errors.UnknownFunctionCallArgumentError): + convert_if_exist_pydantic_model( + {'key1_simple': 1, 'key2_simple': 1.0}, + float, + 'param_name', + 'func_name', + ) + with pytest.raises(errors.UnknownFunctionCallArgumentError): + convert_if_exist_pydantic_model( + 1, + str, + 'param_name', + 'func_name', + ) + with pytest.raises(errors.UnknownFunctionCallArgumentError): + convert_if_exist_pydantic_model( + 1.0, + str, + 'param_name', + 'func_name', + ) + with pytest.raises(errors.UnknownFunctionCallArgumentError): + convert_if_exist_pydantic_model( + True, + str, + 'param_name', + 'func_name', + ) + with pytest.raises(errors.UnknownFunctionCallArgumentError): + convert_if_exist_pydantic_model( + [1], + str, + 'param_name', + 'func_name', + ) + with pytest.raises(errors.UnknownFunctionCallArgumentError): + convert_if_exist_pydantic_model( + {'key1': 1}, + str, + 'param_name', + 'func_name', + ) + with pytest.raises(errors.UnknownFunctionCallArgumentError): + convert_if_exist_pydantic_model( + {'key1': 1, 'key2': 2}, + str, + 'param_name', + 'func_name', + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/afc/test_convert_number_values_for_function_call_args.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/afc/test_convert_number_values_for_function_call_args.py new file mode 100644 index 0000000000000000000000000000000000000000..60950fd80d79b8dac880751469deca6563b2c010 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/afc/test_convert_number_values_for_function_call_args.py @@ -0,0 +1,63 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for convert_number_values_for_function_call_args.""" + +from ..._extra_utils import convert_number_values_for_function_call_args + + +def test_integer_value(): + assert convert_number_values_for_function_call_args(1) == 1 + + +def test_float_value(): + assert convert_number_values_for_function_call_args(1.0) == 1 + + +def test_string_value(): + assert convert_number_values_for_function_call_args('1.0') == '1.0' + + +def test_boolean_value(): + assert convert_number_values_for_function_call_args(True) is True + + +def test_none_value(): + assert convert_number_values_for_function_call_args(None) is None + + +def test_float_value_with_decimal(): + assert convert_number_values_for_function_call_args(1.1) == 1.1 + + +def test_dict_value(): + assert convert_number_values_for_function_call_args( + {'key1': 1.0, 'key2': 1.1} + ) == {'key1': 1, 'key2': 1.1} + + +def test_list_value(): + assert convert_number_values_for_function_call_args([1.0, 1.1, 1.2]) == [ + 1, + 1.1, + 1.2, + ] + + +def test_nested_value(): + assert convert_number_values_for_function_call_args( + {'key1': 1.0, 'key2': {'key3': 1.0, 'key4': [1.2, 2.0]}} + ) == {'key1': 1, 'key2': {'key3': 1, 'key4': [1.2, 2]}} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/afc/test_find_afc_incompatible_tool_indexes.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/afc/test_find_afc_incompatible_tool_indexes.py new file mode 100644 index 0000000000000000000000000000000000000000..c66f9b8aad491b46c7f6d8d58dea6b7bf87d7573 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/afc/test_find_afc_incompatible_tool_indexes.py @@ -0,0 +1,268 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for find_afc_incompatible_tool_indexes.""" + +from typing import Any +import pytest +from ... import types +from ..._extra_utils import find_afc_incompatible_tool_indexes + +try: + from mcp import types as mcp_types + from mcp import ClientSession as McpClientSession + from ..._adapters import McpToGenAiToolAdapter +except ImportError as e: + import sys + + if sys.version_info < (3, 10): + raise ImportError( + 'MCP Tool requires Python 3.10 or above. Please upgrade your Python' + ' version.' + ) from e + else: + raise e + + +def get_weather_tool(city: str) -> str: + """Get the weather in a city.""" + return f'The weather in {city} is sunny and 100 degrees.' + + +class MockMcpClientSession(McpClientSession): + + def __init__(self): + self._read_stream = None + self._write_stream = None + + async def call_tool(self, name: str, arguments: dict[str, Any]) -> Any: + return mcp_types.CallToolResult( + content=[mcp_types.TextContent(type='text', text='1.01')] + ) + +mcp_to_genai_tool_adapter = McpToGenAiToolAdapter( + session=MockMcpClientSession(), + list_tools_result=mcp_types.ListToolsResult(tools=[]), +) + + +def test_no_config_returns_empty_list(): + """Verifies that an empty list is returned if the input config is None. + """ + result = find_afc_incompatible_tool_indexes(config=None) + assert result == [] + +def test_config_with_no_tools_returns_empty_list(): + """Verifies an empty list is returned if the config has no 'tools' attribute. + """ + result = find_afc_incompatible_tool_indexes( + config=types.GenerateContentConfig() + ) + assert result == [] + +def test_empty_tools_list_returns_empty_list(): + """Verifies that an empty list is returned if the 'tools' list is empty.""" + result = find_afc_incompatible_tool_indexes( + config=types.GenerateContentConfig(tools=[]) + ) + + assert result == [] + +def test_all_compatible_tools_returns_empty_list_with_empty_fd(): + """Verifies that an empty list is returned when all tools are compatible. + + A tool is compatible if it's not a `types.Tool` or if its + `function_declarations` attribute is empty or None from config. + """ + result = find_afc_incompatible_tool_indexes( + config=types.GenerateContentConfig( + tools=[ + types.Tool( + google_search_retrieval=types.GoogleSearchRetrieval() + ), + types.Tool(retrieval=types.Retrieval()), + types.Tool(google_search=types.GoogleSearch()), + types.Tool(code_execution=types.ToolCodeExecution()), + types.Tool(google_maps=types.GoogleMaps()), + types.Tool(url_context=types.UrlContext()), + types.Tool(computer_use=types.ComputerUse()), + types.Tool(code_execution=types.ToolCodeExecution()), + types.Tool(function_declarations=[]), + mcp_types.Tool( + name='get_weather', + description='Get the weather in a city.', + inputSchema={ + 'type': 'object', + 'properties': {'location': {'type': 'string'}}, + }, + ), + get_weather_tool, + mcp_to_genai_tool_adapter, + ] + ) + ) + + assert result == [] + +def test_all_compatible_tools_returns_empty_list_with_none_fd(): + """Verifies that an empty list is returned when all tools are compatible. + + A tool is compatible if it's not a `types.Tool` or if its + `function_declarations` attribute is empty or None from config. + """ + result = find_afc_incompatible_tool_indexes( + config=types.GenerateContentConfig( + tools=[ + types.Tool( + google_search_retrieval=types.GoogleSearchRetrieval() + ), + types.Tool(retrieval=types.Retrieval()), + types.Tool(google_search=types.GoogleSearch()), + types.Tool(code_execution=types.ToolCodeExecution()), + types.Tool(google_maps=types.GoogleMaps()), + types.Tool(url_context=types.UrlContext()), + types.Tool(computer_use=types.ComputerUse()), + types.Tool(code_execution=types.ToolCodeExecution()), + types.Tool(function_declarations=None), + mcp_types.Tool( + name='get_weather', + description='Get the weather in a city.', + inputSchema={ + 'type': 'object', + 'properties': {'location': {'type': 'string'}}, + }, + ), + get_weather_tool, + mcp_to_genai_tool_adapter, + ] + ) + ) + + assert result == [] + +def test_all_compatible_tools_returns_empty_list(): + """Verifies that an empty list is returned when all tools are compatible. + + A tool is compatible if it's not a `types.Tool` or if its + `function_declarations` attribute is empty or None from config. + """ + result = find_afc_incompatible_tool_indexes( + config=types.GenerateContentConfig( + tools=[ + types.Tool( + google_search_retrieval=types.GoogleSearchRetrieval() + ), + types.Tool(retrieval=types.Retrieval()), + types.Tool(google_search=types.GoogleSearch()), + types.Tool(code_execution=types.ToolCodeExecution()), + types.Tool(google_maps=types.GoogleMaps()), + types.Tool(url_context=types.UrlContext()), + types.Tool(computer_use=types.ComputerUse()), + types.Tool(code_execution=types.ToolCodeExecution()), + types.Tool(function_declarations=[]), + mcp_types.Tool( + name='get_weather', + description='Get the weather in a city.', + inputSchema={ + 'type': 'object', + 'properties': {'location': {'type': 'string'}}, + }, + ), + get_weather_tool, + mcp_to_genai_tool_adapter, + ] + ) + ) + + assert result == [] + +def test_single_incompatible_tool(): + """Verifies that the correct index is returned for a single incompatible + tool. + """ + result = find_afc_incompatible_tool_indexes( + config=types.GenerateContentConfig( + tools=[ + types.Tool( + google_search_retrieval=types.GoogleSearchRetrieval() + ), + types.Tool(retrieval=types.Retrieval()), + types.Tool( + function_declarations=[ + types.FunctionDeclaration(name='test_function') + ] + ), + get_weather_tool, + mcp_to_genai_tool_adapter, + ] + ) + ) + assert result == [2] + + +def test_multiple_incompatible_tools(): + """Verifies correct indexes are returned for multiple incompatible tools.""" + result = find_afc_incompatible_tool_indexes( + config=types.GenerateContentConfig( + tools=[ + types.Tool( + google_search_retrieval=types.GoogleSearchRetrieval() + ), + types.Tool(retrieval=types.Retrieval()), + types.Tool( + function_declarations=[ + types.FunctionDeclaration(name='test_function') + ] + ), + types.Tool(computer_use=types.ComputerUse()), + types.Tool(code_execution=types.ToolCodeExecution()), + types.Tool( + function_declarations=[ + types.FunctionDeclaration(name='test_function_2') + ] + ), + get_weather_tool, + mcp_to_genai_tool_adapter, + ] + ) + ) + assert result == [2, 5] + +def test_mcp_tool_incompatible(): + """Verifies correct indexes are returned for multiple incompatible tools.""" + result = find_afc_incompatible_tool_indexes( + config=types.GenerateContentConfig( + tools=[ + types.Tool( + google_search_retrieval=types.GoogleSearchRetrieval() + ), + types.Tool(retrieval=types.Retrieval()), + types.Tool( + function_declarations=[ + types.FunctionDeclaration(name='test_function') + ] + ), + types.Tool(code_execution=types.ToolCodeExecution()), + + get_weather_tool, + mcp_to_genai_tool_adapter, + types.Tool( + mcp_servers=[types.McpServer(name='test_mcp_server')] + ), + ] + ) + ) + assert result == [2, 6] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/afc/test_generate_content_stream_afc.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/afc/test_generate_content_stream_afc.py new file mode 100644 index 0000000000000000000000000000000000000000..5cdb9b33f8f0524850a8694c2bf29203bd979c3a --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/afc/test_generate_content_stream_afc.py @@ -0,0 +1,530 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# +from unittest import mock +import pytest +from ... import _api_client +from ... import _extra_utils +from ... import client +from ... import models +from ... import types + + +TEST_NO_AFC_PART = types.Part( + text=( + 'Okay, here is the weather in San Francisco' + ' as of approximately 8:10 pm PST on May' + ' 10, 2023. Please note that the weather' + ' can change rapidly.' + ) +) + +TEST_FUNCTION_CALL_PART = types.Part( + function_call=types.FunctionCall( + name='get_current_weather', + args={'location': 'San Francisco'}, + ) +) + +TEST_FUNCTION_RESPONSE_PART = types.Part( + function_response=types.FunctionResponse( + name='get_current_weather', + response={'result': 'sunny'}, + ) +) + +TEST_AFC_TEXT_PART = types.Part(text='San Francisco weather is sunny.') + +TEST_NO_AFC_CONTENT = types.Content( + parts=[TEST_NO_AFC_PART], + role='model', +) + +TEST_FUNCTION_CALL_CONTENT = types.Content( + parts=[TEST_FUNCTION_CALL_PART], + role='model', +) + +TEST_FUNCTION_RESPONSE_CONTENT = types.Content( + parts=[TEST_FUNCTION_RESPONSE_PART], + role='user', +) + +TEST_AFC_TEXT_CONTENT = types.Content( + parts=[TEST_AFC_TEXT_PART], + role='model', +) + +TEST_AFC_HISTORY = [ + types.Content( + parts=[types.Part(text='what is the weather in San Francisco?')], + role='user', + ), + TEST_FUNCTION_CALL_CONTENT, + TEST_FUNCTION_RESPONSE_CONTENT, +] + + +def get_current_weather(location: str) -> str: + """Returns the current weather. + + Args: + location: The location of a city and state, e.g. "San Francisco, CA". + """ + return 'windy' + + +async def get_current_weather_async(location: str) -> str: + """Returns the current weather. + + Args: + location: The location of a city and state, e.g. "San Francisco, CA". + """ + return 'windy' + + +def get_aqi_from_city(location: str) -> str: + """Returns the aqi index of a city. + + Args: + location: The city and State, e.g. San Francisco, CA. + """ + return None + + +@pytest.fixture +def mock_api_client(vertexai=False): + api_client = mock.MagicMock(spec=client.ApiClient) + api_client.api_key = 'TEST_API_KEY' + api_client._host = lambda: 'test_host' + api_client._http_options = {'headers': {}} # Ensure headers exist + api_client.vertexai = vertexai + return api_client + + +@pytest.fixture +def mock_get_function_response_parts_none(): + with mock.patch.object( + _extra_utils, + 'get_function_response_parts', + ) as mock_get_function_response_parts_none: + mock_get_function_response_parts_none.return_value = None + yield mock_get_function_response_parts_none + + +@pytest.fixture +def mock_get_function_response_parts_none_async(): + with mock.patch.object( + _extra_utils, + 'get_function_response_parts_async', + ) as mock_get_function_response_parts_none_async: + mock_get_function_response_parts_none_async.return_value = None + yield mock_get_function_response_parts_none_async + + +@pytest.fixture +def mock_get_function_response_parts() -> list[types.Part]: + with mock.patch.object( + _extra_utils, 'get_function_response_parts' + ) as mock_get_function_response_parts: + mock_get_function_response_parts.side_effect = [ + [TEST_FUNCTION_RESPONSE_PART], + [], # Breaks when the function response is not returned. + ] + yield mock_get_function_response_parts + + +@pytest.fixture +def mock_get_function_response_parts_async() -> list[types.Part]: + with mock.patch.object( + _extra_utils, 'get_function_response_parts_async' + ) as mock_get_function_response_parts_async: + mock_get_function_response_parts_async.side_effect = [ + [TEST_FUNCTION_RESPONSE_PART], + [], # Breaks when the function response is not returned. + ] + yield mock_get_function_response_parts_async + + +@pytest.fixture +def mock_generate_content_stream_no_afc(): + with mock.patch.object( + models.Models, '_generate_content_stream' + ) as mock_stream_no_afc: + mock_stream_no_afc.return_value = [ + types.GenerateContentResponse( + candidates=[types.Candidate(content=TEST_NO_AFC_CONTENT)] + ) + ] + yield mock_stream_no_afc + + +@pytest.fixture +def mock_generate_content_stream_with_afc(): + with mock.patch.object( + models.Models, '_generate_content_stream' + ) as mock_stream_with_afc: + mock_stream_with_afc.side_effect = [ + [ + types.GenerateContentResponse( + candidates=[types.Candidate(content=TEST_FUNCTION_CALL_CONTENT)] + ) + ], + [ + types.GenerateContentResponse( + candidates=[types.Candidate(content=TEST_AFC_TEXT_CONTENT)] + ) + ], + ] + yield mock_stream_with_afc + + +@pytest.fixture +def mock_generate_content_stream_no_afc_async(): + with mock.patch.object( + models.AsyncModels, '_generate_content_stream' + ) as mock_stream_no_afc: + + async def async_generator(): + yield types.GenerateContentResponse( + candidates=[types.Candidate(content=TEST_NO_AFC_CONTENT)] + ) + + mock_stream_no_afc.return_value = async_generator() + yield mock_stream_no_afc + + +@pytest.fixture +def mock_generate_content_stream_with_afc_async(): + with mock.patch.object( + models.AsyncModels, '_generate_content_stream' + ) as mock_stream_with_afc: + + async def async_generator_1(): + yield types.GenerateContentResponse( + candidates=[types.Candidate(content=TEST_FUNCTION_CALL_CONTENT)] + ) + + async def async_generator_2(): + yield types.GenerateContentResponse( + candidates=[types.Candidate(content=TEST_AFC_TEXT_CONTENT)] + ) + + mock_stream_with_afc.side_effect = [ + async_generator_1(), + async_generator_2(), + ] + yield mock_stream_with_afc + + +def test_generate_content_stream_no_function_map( + mock_generate_content_stream_no_afc, + mock_get_function_response_parts_none, +): + """Test when no function tools are provided. + + Expected to answer past weather. + """ + models_instance = models.Models(api_client_=mock_api_client) + stream = models_instance.generate_content_stream( + model='test_model', contents='what is the weather in San Francisco?' + ) + for chunk in stream: + assert chunk.text == TEST_NO_AFC_PART.text + + assert mock_generate_content_stream_no_afc.call_count == 1 + assert mock_get_function_response_parts_none.call_count == 0 + + +def test_generate_content_stream_afc_disabled( + mock_generate_content_stream_with_afc, + mock_get_function_response_parts_none, +): + """Test when function tools are provided but AFC is disabled. + + Expected to respond with function call. + """ + models_instance = models.Models(api_client_=mock_api_client) + stream = models_instance.generate_content_stream( + model='test_model', + contents='what is the weather in San Francisco?', + config=types.GenerateContentConfig( + tools=[get_current_weather], + automatic_function_calling=types.AutomaticFunctionCallingConfig( + disable=True + ), + ), + ) + for chunk in stream: + # Work as manual function calling. + assert chunk.candidates[0].content.parts[0].function_call + + assert mock_generate_content_stream_with_afc.call_count == 1 + assert mock_get_function_response_parts_none.call_count == 0 + + +def test_generate_content_stream_no_function_response( + mock_generate_content_stream_no_afc, + mock_get_function_response_parts_none, +): + """Test when function tools are provided and function responses are not returned. + + Expected to answer past weather. + """ + models_instance = models.Models(api_client_=mock_api_client) + config = types.GenerateContentConfig(tools=[get_aqi_from_city]) + stream = models_instance.generate_content_stream( + model='test_model', + contents='what is the weather in San Francisco?', + config=config, + ) + for chunk in stream: + assert chunk.text == TEST_NO_AFC_PART.text + + assert mock_generate_content_stream_no_afc.call_count == 1 + assert mock_get_function_response_parts_none.call_count == 1 + + +def test_generate_content_stream_with_function_tools_used( + mock_generate_content_stream_with_afc, + mock_get_function_response_parts, +): + """Test when function tools are provided and function responses are returned. + + Expected to answer weather based on function response. + """ + models_instance = models.Models(api_client_=mock_api_client) + config = types.GenerateContentConfig(tools=[get_current_weather]) + stream = models_instance.generate_content_stream( + model='test_model', + contents='what is the weather in San Francisco?', + config=config, + ) + + chunk = None + for chunk in stream: + assert chunk.text == TEST_AFC_TEXT_PART.text + + assert mock_generate_content_stream_with_afc.call_count == 2 + assert mock_get_function_response_parts.call_count == 2 + + assert chunk is not None + for i in range(len(chunk.automatic_function_calling_history)): + assert chunk.automatic_function_calling_history[i].model_dump( + exclude_none=True + ) == TEST_AFC_HISTORY[i].model_dump(exclude_none=True) + + +def test_generate_content_stream_with_thought_summaries( + mock_generate_content_stream_with_afc, + mock_get_function_response_parts, +): + """Test when function tools are provided and thought summaries are enabled. + + Expected to answer weather based on function response. + """ + models_instance = models.Models(api_client_=mock_api_client) + config = types.GenerateContentConfig( + tools=[get_current_weather], + thinking_config=types.ThinkingConfig(include_thoughts=True), + ) + stream = models_instance.generate_content_stream( + model='test_model', + contents='what is the weather in San Francisco?', + config=config, + ) + + chunk = None + for chunk in stream: + assert chunk.text == TEST_AFC_TEXT_PART.text + + assert mock_generate_content_stream_with_afc.call_count == 2 + assert mock_get_function_response_parts.call_count == 2 + + assert chunk is not None + for i in range(len(chunk.automatic_function_calling_history)): + assert chunk.automatic_function_calling_history[i].model_dump( + exclude_none=True + ) == TEST_AFC_HISTORY[i].model_dump(exclude_none=True) + + +@pytest.mark.asyncio +async def test_generate_content_stream_no_function_map_async( + mock_generate_content_stream_no_afc, + mock_get_function_response_parts_none, +): + """Test when no function tools are provided. + + Expected to answer past weather. + """ + models_instance = models.Models(api_client_=mock_api_client) + stream = models_instance.generate_content_stream( + model='test_model', contents='what is the weather in San Francisco?' + ) + for chunk in stream: + assert chunk.text == TEST_NO_AFC_PART.text + + assert mock_generate_content_stream_no_afc.call_count == 1 + assert mock_get_function_response_parts_none.call_count == 0 + + +@pytest.mark.asyncio +async def test_generate_content_stream_afc_disabled_async( + mock_generate_content_stream_with_afc_async, + mock_get_function_response_parts_none, +): + """Test when function tools are provided but AFC is disabled. + + Expected to respond with function call. + """ + models_instance = models.AsyncModels(api_client_=mock_api_client) + stream = await models_instance.generate_content_stream( + model='test_model', + contents='what is the weather in San Francisco?', + config=types.GenerateContentConfig( + tools=[get_current_weather], + automatic_function_calling=types.AutomaticFunctionCallingConfig( + disable=True + ), + ), + ) + async for chunk in stream: + # Work as manual function calling. + assert chunk.candidates[0].content.parts[0].function_call + + assert mock_generate_content_stream_with_afc_async.call_count == 1 + assert mock_get_function_response_parts_none.call_count == 0 + + +@pytest.mark.asyncio +async def test_generate_content_stream_no_function_response_async( + mock_generate_content_stream_no_afc_async, + mock_get_function_response_parts_none_async, +): + """Test when function tools are provided and function responses are not returned. + + Expected to answer past weather. + """ + models_instance = models.AsyncModels(api_client_=mock_api_client) + config = types.GenerateContentConfig(tools=[get_aqi_from_city]) + stream = await models_instance.generate_content_stream( + model='test_model', + contents='what is the weather in San Francisco?', + config=config, + ) + async for chunk in stream: + assert chunk.text == TEST_NO_AFC_PART.text + + assert mock_generate_content_stream_no_afc_async.call_count == 1 + + assert mock_get_function_response_parts_none_async.call_count == 1 + + +@pytest.mark.asyncio +async def test_generate_content_stream_with_function_tools_used_async( + mock_generate_content_stream_with_afc_async, + mock_get_function_response_parts_async, +): + """Test when function tools are provided and function responses are returned. + + Expected to answer weather based on function response. + """ + models_instance = models.AsyncModels(api_client_=mock_api_client) + config = types.GenerateContentConfig(tools=[get_current_weather]) + stream = await models_instance.generate_content_stream( + model='test_model', + contents='what is the weather in San Francisco?', + config=config, + ) + + chunk = None + async for chunk in stream: + assert chunk.text == TEST_AFC_TEXT_PART.text + + assert mock_generate_content_stream_with_afc_async.call_count == 2 + + assert mock_get_function_response_parts_async.call_count == 2 + + assert chunk is not None + for i in range(len(chunk.automatic_function_calling_history)): + assert chunk.automatic_function_calling_history[i].model_dump( + exclude_none=True + ) == TEST_AFC_HISTORY[i].model_dump(exclude_none=True) + + +@pytest.mark.asyncio +async def test_generate_content_stream_with_function_async_function_used_async( + mock_generate_content_stream_with_afc_async, + mock_get_function_response_parts_async, +): + """Test when function tools are provided and function responses are returned. + + Expected to answer weather based on function response. + """ + models_instance = models.AsyncModels(api_client_=mock_api_client) + config = types.GenerateContentConfig(tools=[get_current_weather_async]) + stream = await models_instance.generate_content_stream( + model='test_model', + contents='what is the weather in San Francisco?', + config=config, + ) + + chunk = None + async for chunk in stream: + assert chunk.text == TEST_AFC_TEXT_PART.text + + assert mock_generate_content_stream_with_afc_async.call_count == 2 + + assert mock_get_function_response_parts_async.call_count == 2 + + assert chunk is not None + for i in range(len(chunk.automatic_function_calling_history)): + assert chunk.automatic_function_calling_history[i].model_dump( + exclude_none=True + ) == TEST_AFC_HISTORY[i].model_dump(exclude_none=True) + + +@pytest.mark.asyncio +async def test_generate_content_stream_with_thought_summaries_async( + mock_generate_content_stream_with_afc_async, + mock_get_function_response_parts_async, +): + """Test when function tools are provided and thought summaries are enabled. + + Expected to answer weather based on function response. + """ + models_instance = models.AsyncModels(api_client_=mock_api_client) + config = types.GenerateContentConfig( + tools=[get_current_weather], + thinking_config=types.ThinkingConfig(include_thoughts=True), + ) + stream = await models_instance.generate_content_stream( + model='test_model', + contents='what is the weather in San Francisco?', + config=config, + ) + + chunk = None + async for chunk in stream: + assert chunk.text == TEST_AFC_TEXT_PART.text + + assert mock_generate_content_stream_with_afc_async.call_count == 2 + + assert mock_get_function_response_parts_async.call_count == 2 + + assert chunk is not None + for i in range(len(chunk.automatic_function_calling_history)): + assert chunk.automatic_function_calling_history[i].model_dump( + exclude_none=True + ) == TEST_AFC_HISTORY[i].model_dump(exclude_none=True) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/afc/test_generate_content_stream_afc_thoughts.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/afc/test_generate_content_stream_afc_thoughts.py new file mode 100644 index 0000000000000000000000000000000000000000..434259352f6d89ae64cf0d45e62572122af618c3 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/afc/test_generate_content_stream_afc_thoughts.py @@ -0,0 +1,77 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# +import pytest +from ... import types +from .. import pytest_helper + + +def get_current_weather(location: str) -> str: + """Returns the current weather. + + Args: + location: The location of a city and state, e.g. "San Francisco, CA". + """ + return 'windy' + + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='models.generate_content', +) +pytest_plugins = ('pytest_asyncio',) + + +def test_generate_content_stream_with_function_and_thought_summaries(client): + """Test when function tools are provided and thought summaries are enabled. + + Expected to answer weather based on function response. + """ + config = types.GenerateContentConfig( + tools=[get_current_weather], + thinking_config=types.ThinkingConfig(include_thoughts=True), + ) + stream = client.models.generate_content_stream( + model='gemini-2.5-flash', + contents='what is the weather in San Francisco, CA?', + config=config, + ) + + chunk = None + for chunk in stream: + assert chunk is not None + + +@pytest.mark.asyncio +async def test_generate_content_stream_with_function_and_thought_summaries_async( + client, +): + """Test when function tools are provided and thought summaries are enabled. + + Expected to answer weather based on function response. + """ + config = types.GenerateContentConfig( + tools=[get_current_weather], + thinking_config=types.ThinkingConfig(include_thoughts=True), + ) + stream = await client.aio.models.generate_content_stream( + model='gemini-2.5-flash', + contents='what is the weather in San Francisco, CA?', + config=config, + ) + + chunk = None + async for chunk in stream: + assert chunk is not None diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/afc/test_get_function_map.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/afc/test_get_function_map.py new file mode 100644 index 0000000000000000000000000000000000000000..8a8bc9334a21760280b087681fb09b8a804b7e7a --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/afc/test_get_function_map.py @@ -0,0 +1,176 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +"""Tests for get_function_map.""" + +import typing +from typing import Any +import pytest +from ..._extra_utils import get_function_map +from ...errors import UnsupportedFunctionError +from ...types import GenerateContentConfig + +_is_mcp_imported = False +if typing.TYPE_CHECKING: + from mcp import types as mcp_types + from mcp import ClientSession as McpClientSession + from ..._adapters import McpToGenAiToolAdapter + + _is_mcp_imported = True +else: + McpClientSession: typing.Type = Any + McpToGenAiToolAdapter: typing.Type = Any + try: + from mcp import types as mcp_types + from mcp import ClientSession as McpClientSession + from ..._adapters import McpToGenAiToolAdapter + + _is_mcp_imported = True + except ImportError: + McpClientSession = None + McpToGenAiToolAdapter = None + + +def test_coroutine_function(): + async def func_under_test(): + pass + + config = GenerateContentConfig(tools=[func_under_test]) + + with pytest.raises(UnsupportedFunctionError): + get_function_map(config) + + +def test_empty_config(): + config = {} + + assert get_function_map(config) == {} + + +def test_empty_tools(): + config = GenerateContentConfig(top_p=0.5) + + assert get_function_map(config) == {} + + +def test_valid_function(): + def func_under_test(): + pass + + config = GenerateContentConfig(tools=[func_under_test]) + + assert get_function_map(config) == {'func_under_test': func_under_test} + + +def test_mcp_tool_raises_error(): + if not _is_mcp_imported: + return + + session = McpClientSession(read_stream=None, write_stream=None) + config = GenerateContentConfig(tools=[session]) + mcp_to_genai_tool_adapters = {'tool': McpToGenAiToolAdapter(session, [])} + with pytest.raises(UnsupportedFunctionError): + get_function_map( + config, mcp_to_genai_tool_adapters, is_caller_method_async=False + ) + + +@pytest.mark.asyncio +async def test_mcp_tool(): + if not _is_mcp_imported: + return + + class MockMcpClientSession(McpClientSession): + + def __init__(self): + self._read_stream = None + self._write_stream = None + + async def list_tools(self): + return mcp_types.ListToolsResult( + tools=[ + mcp_types.Tool( + name='tool', + description='tool-description', + inputSchema={ + 'type': 'OBJECT', + 'properties': { + 'key1': { + 'type': 'STRING', + }, + 'key2': { + 'type': 'NUMBER', + }, + }, + }, + ) + ] + ) + + session = MockMcpClientSession() + config = GenerateContentConfig(tools=[session]) + mcp_to_genai_tool_adapters = { + 'tool': McpToGenAiToolAdapter(session, [await session.list_tools()]), + } + result = get_function_map( + config, mcp_to_genai_tool_adapters, is_caller_method_async=True + ) + assert isinstance(result['tool'], McpToGenAiToolAdapter) + + +@pytest.mark.asyncio +async def test_duplicate_mcp_tool_raises_error(): + if not _is_mcp_imported: + return + + class MockMcpClientSession(McpClientSession): + + def __init__(self): + self._read_stream = None + self._write_stream = None + + async def list_tools(self): + return mcp_types.ListToolsResult( + tools=[ + mcp_types.Tool( + name='tool', + description='tool-description', + inputSchema={ + 'type': 'OBJECT', + 'properties': { + 'key1': { + 'type': 'STRING', + }, + 'key2': { + 'type': 'NUMBER', + }, + }, + }, + ) + ] + ) + + def tool(): + pass + + session = MockMcpClientSession() + config = GenerateContentConfig(tools=[tool, session]) + mcp_to_genai_tool_adapters = { + 'tool': McpToGenAiToolAdapter(session, [await session.list_tools()]), + } + with pytest.raises(ValueError): + get_function_map( + config, mcp_to_genai_tool_adapters, is_caller_method_async=True + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/afc/test_get_function_response_parts.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/afc/test_get_function_response_parts.py new file mode 100644 index 0000000000000000000000000000000000000000..e80ec4493f2c23043788bf1d1aaebadc383cffb4 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/afc/test_get_function_response_parts.py @@ -0,0 +1,277 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for get_function_response_parts.""" + +import typing +from typing import Any +import pytest +from ..._extra_utils import get_function_response_parts, get_function_response_parts_async +from ...errors import UnsupportedFunctionError +from ...types import Candidate +from ...types import Content +from ...types import FunctionCall +from ...types import FunctionResponse +from ...types import GenerateContentResponse +from ...types import Part + +_is_mcp_imported = False +if typing.TYPE_CHECKING: + from mcp import types as mcp_types + from mcp import ClientSession as McpClientSession + from ..._adapters import McpToGenAiToolAdapter + + _is_mcp_imported = True +else: + McpClientSession: typing.Type = Any + McpToGenAiToolAdapter: typing.Type = Any + try: + from mcp import types as mcp_types + from mcp import ClientSession as McpClientSession + from ..._adapters import McpToGenAiToolAdapter + + _is_mcp_imported = True + except ImportError: + McpClientSession = None + McpToGenAiToolAdapter = None + + +def test_integer_value(): + def func_under_test(a: int) -> int: + return a + 1 + + response = GenerateContentResponse( + candidates=[ + Candidate( + content=Content( + parts=[ + Part( + function_call=FunctionCall( + name='func_under_test', + args={'a': 1}, + ) + ) + ] + ) + ) + ] + ) + function_map = {'func_under_test': func_under_test} + expected_parts = [ + Part( + function_response=FunctionResponse( + name='func_under_test', + response={'result': 2}, + ) + ) + ] + actual_parts = get_function_response_parts(response, function_map) + + for actual_part, expected_part in zip(actual_parts, expected_parts): + assert actual_part.model_dump_json( + exclude_none=True + ) == expected_part.model_dump_json(exclude_none=True) + + +def test_float_value(): + def func_under_test(a: float) -> float: + return a + 1.0 + + response = GenerateContentResponse( + candidates=[ + Candidate( + content=Content( + parts=[ + Part( + function_call=FunctionCall( + name='func_under_test', + args={'a': 1.0}, + ) + ) + ] + ) + ) + ] + ) + function_map = {'func_under_test': func_under_test} + expected_parts = [ + Part( + function_response=FunctionResponse( + name='func_under_test', + response={'result': 2.0}, + ) + ) + ] + actual_parts = get_function_response_parts(response, function_map) + + for actual_part, expected_part in zip(actual_parts, expected_parts): + assert actual_part.model_dump_json( + exclude_none=True + ) == expected_part.model_dump_json(exclude_none=True) + + +def test_string_value(): + def func_under_test(a: str) -> str: + return a + '1' + + response = GenerateContentResponse( + candidates=[ + Candidate( + content=Content( + parts=[ + Part( + function_call=FunctionCall( + name='func_under_test', + args={'a': '1.0'}, + ) + ) + ] + ) + ) + ] + ) + function_map = {'func_under_test': func_under_test} + expected_parts = [ + Part( + function_response=FunctionResponse( + name='func_under_test', + response={'result': '1.01'}, + ) + ) + ] + actual_parts = get_function_response_parts(response, function_map) + + for actual_part, expected_part in zip(actual_parts, expected_parts): + assert actual_part.model_dump_json( + exclude_none=True + ) == expected_part.model_dump_json(exclude_none=True) + + +@pytest.mark.asyncio +async def test_mcp_tool(): + if not _is_mcp_imported: + return + + class MockMcpClientSession(McpClientSession): + + def __init__(self): + self._read_stream = None + self._write_stream = None + + async def call_tool(self, name: str, arguments: dict[str, Any]) -> Any: + return mcp_types.CallToolResult( + content=[mcp_types.TextContent(type='text', text='1.01')] + ) + + mcp_to_genai_tool_adapter = McpToGenAiToolAdapter( + session=MockMcpClientSession(), + list_tools_result=mcp_types.ListToolsResult(tools=[]), + ) + response = GenerateContentResponse( + candidates=[ + Candidate( + content=Content( + parts=[ + Part( + function_call=FunctionCall( + name='tool', + args={'key1': 'value1', 'key2': 1}, + ) + ) + ] + ) + ) + ] + ) + function_map = {'tool': mcp_to_genai_tool_adapter} + expected_parts = [ + Part( + function_response=FunctionResponse( + name='tool', + response={ + 'result': { + 'content': [{'type': 'text', 'text': '1.01'}], + 'isError': False, + } + }, + ) + ) + ] + actual_parts = await get_function_response_parts_async(response, function_map) + + for actual_part, expected_part in zip(actual_parts, expected_parts): + assert actual_part.model_dump_json( + exclude_none=True + ) == expected_part.model_dump_json(exclude_none=True) + + +@pytest.mark.asyncio +async def test_mcp_tool_error(): + if not _is_mcp_imported: + return + + class MockMcpClientSession(McpClientSession): + + def __init__(self): + self._read_stream = None + self._write_stream = None + + async def call_tool(self, name: str, arguments: dict[str, Any]) -> Any: + return mcp_types.CallToolResult( + content=[mcp_types.TextContent(type='text', text='Internal error')], + isError=True, + ) + + mcp_to_genai_tool_adapter = McpToGenAiToolAdapter( + session=MockMcpClientSession(), + list_tools_result=mcp_types.ListToolsResult(tools=[]), + ) + response = GenerateContentResponse( + candidates=[ + Candidate( + content=Content( + parts=[ + Part( + function_call=FunctionCall( + name='tool', + args={'key1': 'value1', 'key2': 1}, + ) + ) + ] + ) + ) + ] + ) + function_map = {'tool': mcp_to_genai_tool_adapter} + expected_parts = [ + Part( + function_response=FunctionResponse( + name='tool', + response={ + 'error': { + 'content': [{'type': 'text', 'text': 'Internal error'}], + 'isError': True, + } + }, + ) + ) + ] + actual_parts = await get_function_response_parts_async(response, function_map) + + for actual_part, expected_part in zip(actual_parts, expected_parts): + assert actual_part.model_dump_json( + exclude_none=True + ) == expected_part.model_dump_json(exclude_none=True) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/afc/test_get_max_remote_calls_for_afc.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/afc/test_get_max_remote_calls_for_afc.py new file mode 100644 index 0000000000000000000000000000000000000000..5a72020edac2c7d12dea9aeaebb4d428f2483907 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/afc/test_get_max_remote_calls_for_afc.py @@ -0,0 +1,130 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for get_max_remote_calls_for_afc.""" + +from ... import types +from ..._extra_utils import get_max_remote_calls_afc +import pytest + + +def test_config_is_none(): + assert get_max_remote_calls_afc(None) == 10 + + +def test_afc_unset_max_unset(): + assert get_max_remote_calls_afc(types.GenerateContentConfig()) == 10 + + +def test_afc_unset_max_set(): + assert ( + get_max_remote_calls_afc( + types.GenerateContentConfig( + automatic_function_calling=types.AutomaticFunctionCallingConfig( + maximum_remote_calls=20, + ), + ) + ) + == 20 + ) + + +def test_afc_disabled_max_unset(): + with pytest.raises(ValueError): + get_max_remote_calls_afc( + types.GenerateContentConfig( + automatic_function_calling=types.AutomaticFunctionCallingConfig( + disable=True, + ), + ) + ) + + +def test_afc_disabled_max_set(): + with pytest.raises(ValueError): + get_max_remote_calls_afc( + types.GenerateContentConfig( + automatic_function_calling=types.AutomaticFunctionCallingConfig( + disable=True, + maximum_remote_calls=20, + ), + ) + ) + + +def test_afc_d_max_unset(): + assert ( + get_max_remote_calls_afc( + types.GenerateContentConfig( + automatic_function_calling=types.AutomaticFunctionCallingConfig( + disable=False, + ), + ) + ) + == 10 + ) + + +def test_afc_d_max_set(): + assert ( + get_max_remote_calls_afc( + types.GenerateContentConfig( + automatic_function_calling=types.AutomaticFunctionCallingConfig( + disable=False, + maximum_remote_calls=5, + ), + ) + ) + == 5 + ) + + +def test_afc_enabled_max_set_to_zero(): + with pytest.raises(ValueError): + get_max_remote_calls_afc( + types.GenerateContentConfig( + automatic_function_calling=types.AutomaticFunctionCallingConfig( + disable=False, + maximum_remote_calls=0, + ), + ) + ) + + +def test_afc_enabled_max_set_to_negative(): + with pytest.raises(ValueError): + get_max_remote_calls_afc( + types.GenerateContentConfig( + automatic_function_calling=types.AutomaticFunctionCallingConfig( + disable=False, + maximum_remote_calls=-1, + ), + ) + ) + + +def test_afc_enabled_max_set_to_float(): + assert ( + get_max_remote_calls_afc( + types.GenerateContentConfig( + automatic_function_calling=types.AutomaticFunctionCallingConfig( + disable=False, + maximum_remote_calls=5.0, + ), + ) + ) + == 5 + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/afc/test_invoke_function_from_dict_args.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/afc/test_invoke_function_from_dict_args.py new file mode 100644 index 0000000000000000000000000000000000000000..440c3326103c54b6bb5597430aca18a1347e537b --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/afc/test_invoke_function_from_dict_args.py @@ -0,0 +1,241 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Test invoke_function_from_dict_args.""" + +from typing import Union +import pydantic +import pytest +import sys +from ... import errors +from ..._extra_utils import invoke_function_from_dict_args + + +def test_builtin_primitive_types(): + def func_under_test(x: int, y: float, z: str, w: bool): + return { + 'x': x + 1, + 'y': y + 1.0, + 'z': z + '1.0', + 'w': not w, + } + + original_args = { + 'x': 1, + 'y': 1.0, + 'z': '1.0', + 'w': True, + } + expected_response = { + 'x': 2, + 'y': 2.0, + 'z': '1.01.0', + 'w': False, + } + + actual_response = invoke_function_from_dict_args( + original_args, func_under_test + ) + + assert actual_response == expected_response + + +@pytest.mark.skipif( + sys.version_info < (3, 10), + reason='| is only supported in Python 3.9 and above.', +) +def test_builtin_compound_types(): + def func_under_test(x: list[int], y: dict[str, float]): + return { + 'new_x': x + [3], + 'new_y': y | {'key3': 3.0}, + } + + original_args = { + 'x': [1, 2], + 'y': {'key1': 1.0, 'key2': 2.0}, + } + expected_response = { + 'new_x': [1, 2, 3], + 'new_y': {'key1': 1.0, 'key2': 2.0, 'key3': 3.0}, + } + + actual_response = invoke_function_from_dict_args( + original_args, func_under_test + ) + + assert actual_response == expected_response + + +def test_nested_pydantic_model(): + class SimpleModel(pydantic.BaseModel): + key1_simple: int + key2_simple: float + + class ComplexModel(pydantic.BaseModel): + key1_complex: SimpleModel + key2_complex: list[SimpleModel] + key3_complex: dict[str, SimpleModel] + + def func_under_test(x: ComplexModel): + y = x.model_copy() + y.key1_complex.key1_simple += 1 + y.key1_complex.key2_simple += 1.0 + for simple_model in y.key2_complex: + simple_model.key1_simple += 1 + simple_model.key2_simple += 1.0 + for simple_model in y.key3_complex.values(): + simple_model.key1_simple += 1 + simple_model.key2_simple += 1.0 + return y + + original_args = { + 'x': { + 'key1_complex': {'key1_simple': 1, 'key2_simple': 1.0}, + 'key2_complex': [ + {'key1_simple': 2, 'key2_simple': 2.0}, + {'key1_simple': 3, 'key2_simple': 3.0}, + ], + 'key3_complex': { + 'key1_simple': {'key1_simple': 4, 'key2_simple': 4.0}, + 'key2_simple': {'key1_simple': 5, 'key2_simple': 5.0}, + }, + } + } + expected_response = { + 'key1_complex': {'key1_simple': 2, 'key2_simple': 2.0}, + 'key2_complex': [ + {'key1_simple': 3, 'key2_simple': 3.0}, + {'key1_simple': 4, 'key2_simple': 4.0}, + ], + 'key3_complex': { + 'key1_simple': {'key1_simple': 5, 'key2_simple': 5.0}, + 'key2_simple': {'key1_simple': 6, 'key2_simple': 6.0}, + }, + } + + actual_response = invoke_function_from_dict_args( + original_args, func_under_test + ) + + assert isinstance(actual_response, ComplexModel) + assert isinstance(actual_response.key1_complex, SimpleModel) + assert isinstance(actual_response.key2_complex[0], SimpleModel) + assert isinstance(actual_response.key2_complex[1], SimpleModel) + assert isinstance(actual_response.key3_complex['key1_simple'], SimpleModel) + assert isinstance(actual_response.key3_complex['key2_simple'], SimpleModel) + assert actual_response.model_dump() == expected_response + + +def test_pydantic_model_in_list_union_type(): + class SimpleModel(pydantic.BaseModel): + key1_simple: int + key2_simple: float + + def func_under_test(x: list[Union[int, SimpleModel]]): + result = [] + for item in x: + if isinstance(item, int): + result.append(item + 1) + elif isinstance(item, SimpleModel): + result.append(item.model_copy()) + result[-1].key1_simple += 1 + result[-1].key2_simple += 1.0 + else: + raise ValueError('Unsupported type: %s' % type(item)) + return result + + expected_response = [2, {'key1_simple': 2, 'key2_simple': 2.0}] + original_args = {'x': [1, {'key1_simple': 1, 'key2_simple': 1.0}]} + actual_response = invoke_function_from_dict_args( + original_args, func_under_test + ) + assert isinstance(actual_response, list) + assert len(actual_response) == 2 + assert isinstance(actual_response[0], int) + assert isinstance(actual_response[1], SimpleModel) + assert actual_response[0] == expected_response[0] + assert actual_response[1].model_dump() == expected_response[1] + + +def test_unknown_pydantic_model_argument(): + class SimpleModel(pydantic.BaseModel): + key1_simple: int + key2_simple: float + + def func_under_test(x: SimpleModel): + return x.model_copy() + + original_args = {'x': {'key3_simple': 1, 'key2_simple': 1.0}} + + with pytest.raises(errors.UnknownFunctionCallArgumentError): + invoke_function_from_dict_args(original_args, func_under_test) + + +def test_unknown_pydantic_model_argument_with_union_type(): + class SimpleModel1(pydantic.BaseModel): + key1_simple: int + key2_simple: float + + class SimpleModel2(pydantic.BaseModel): + key3_simple: str + key4_simple: float + + def func_under_test(x: Union[SimpleModel1, SimpleModel2]): + return x.model_copy() + + original_args = {'x': {'key5_simple': 1, 'key4_simple': 1.0}} + + with pytest.raises(errors.UnknownFunctionCallArgumentError): + invoke_function_from_dict_args(original_args, func_under_test) + + +def test_unknown_pydantic_model_argument_with_union_type_and_builtin_type(): + class SimpleModel1(pydantic.BaseModel): + key1_simple: int + key2_simple: float + + def func_under_test(x: Union[SimpleModel1, int]): + return x.model_copy() + + original_args = {'x': {'key5_simple': 1, 'key4_simple': 1.0}} + + with pytest.raises(errors.UnknownFunctionCallArgumentError): + invoke_function_from_dict_args(original_args, func_under_test) + + +def test_incompatible_value_and_annotation(): + def func_under_test(x: int): + return x + 1 + + with pytest.raises(errors.UnknownFunctionCallArgumentError): + invoke_function_from_dict_args({'x': {'k': 'v'}}, func_under_test) + with pytest.raises(errors.UnknownFunctionCallArgumentError): + invoke_function_from_dict_args({'x': 'a'}, func_under_test) + with pytest.raises(errors.UnknownFunctionCallArgumentError): + invoke_function_from_dict_args({'x': []}, func_under_test) + with pytest.raises(errors.UnknownFunctionCallArgumentError): + invoke_function_from_dict_args({'x': 1.0}, func_under_test) + with pytest.raises(errors.UnknownFunctionCallArgumentError): + invoke_function_from_dict_args({'x': {}}, func_under_test) + + +def test_function_invocation_error(): + def func_under_test(x: int): + return x / 0 + + with pytest.raises(errors.FunctionInvocationError): + invoke_function_from_dict_args({'x': 1}, func_under_test) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/afc/test_raise_error_for_afc_incompatible_config.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/afc/test_raise_error_for_afc_incompatible_config.py new file mode 100644 index 0000000000000000000000000000000000000000..eadadb2b603718fbbc834adef87b41468dbe2471 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/afc/test_raise_error_for_afc_incompatible_config.py @@ -0,0 +1,159 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for raise_error_for_afc_incompatible_config.""" + +import pytest +from ... import types +from ..._extra_utils import raise_error_for_afc_incompatible_config + + +def test_config_is_none(): + assert raise_error_for_afc_incompatible_config(None) is None + + +def test_tool_config_config_unset(): + assert ( + raise_error_for_afc_incompatible_config(types.GenerateContentConfig( + automatic_function_calling=types.AutomaticFunctionCallingConfig( + disable=False, + maximum_remote_calls=1, + ), + )) + is None + ) + + +def test_function_calling_config_unset(): + assert ( + raise_error_for_afc_incompatible_config(types.GenerateContentConfig( + automatic_function_calling=types.AutomaticFunctionCallingConfig( + disable=False, + maximum_remote_calls=1, + ), + tool_config=types.ToolConfig(), + )) + is None + ) + + + +def test_compatible_config_afc_disabled(): + assert ( + raise_error_for_afc_incompatible_config( + types.GenerateContentConfig( + automatic_function_calling=types.AutomaticFunctionCallingConfig( + disable=True, + ), + tool_config=types.ToolConfig( + function_calling_config=types.FunctionCallingConfig( + stream_function_call_arguments=False, + ), + ), + ) + ) + is None + ) + + +def test_compatible_config_stream_function_call_arguments_unset_afc_unset(): + assert ( + raise_error_for_afc_incompatible_config( + types.GenerateContentConfig( + tool_config=types.ToolConfig( + function_calling_config=types.FunctionCallingConfig( + ), + ), + ) + ) + is None + ) + + +def test_compatible_config_stream_function_call_arguments_unset_no_disable_afc(): + assert ( + raise_error_for_afc_incompatible_config( + types.GenerateContentConfig( + automatic_function_calling=types.AutomaticFunctionCallingConfig( + ), + tool_config=types.ToolConfig( + function_calling_config=types.FunctionCallingConfig( + ), + ), + ) + ) + is None + ) + + +def test_compatible_config_stream_function_call_arguments_unset_disable_afc_true(): + assert ( + raise_error_for_afc_incompatible_config( + types.GenerateContentConfig( + automatic_function_calling=types.AutomaticFunctionCallingConfig( + disable=True, + ), + tool_config=types.ToolConfig( + function_calling_config=types.FunctionCallingConfig( + ), + ), + ) + ) + is None + ) + + +def test_incompatible_config_stream_function_call_arguments_set_enable_afc(): + with pytest.raises(ValueError): + raise_error_for_afc_incompatible_config( + types.GenerateContentConfig( + automatic_function_calling=types.AutomaticFunctionCallingConfig( + disable=False, + ), + tool_config=types.ToolConfig( + function_calling_config=types.FunctionCallingConfig( + stream_function_call_arguments=True, + ), + ), + ) + ) + + +def test_incompatible_config_stream_function_call_arguments_set_no_afc_config(): + with pytest.raises(ValueError): + raise_error_for_afc_incompatible_config( + types.GenerateContentConfig( + tool_config=types.ToolConfig( + function_calling_config=types.FunctionCallingConfig( + stream_function_call_arguments=True, + ), + ), + ) + ) + + +def test_incompatible_config_stream_function_call_arguments_set_no_disable_afc(): + with pytest.raises(ValueError): + raise_error_for_afc_incompatible_config( + types.GenerateContentConfig( + automatic_function_calling=types.AutomaticFunctionCallingConfig(), + tool_config=types.ToolConfig( + function_calling_config=types.FunctionCallingConfig( + stream_function_call_arguments=True, + ), + ), + ) + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/afc/test_should_append_afc_history.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/afc/test_should_append_afc_history.py new file mode 100644 index 0000000000000000000000000000000000000000..f146f3e283546deae579e1ce09f40bcc1800f946 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/afc/test_should_append_afc_history.py @@ -0,0 +1,53 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +"""Tests for _extra_utils.should_append_afc_history.""" + +from ... import types +from ..._extra_utils import should_append_afc_history + + +def test_should_append_afc_history_with_default_config(): + config = types.GenerateContentConfig() + + assert should_append_afc_history(config) == True + + +def test_should_append_afc_history_with_empty_afc_config(): + config = types.GenerateContentConfig( + automatic_function_calling=types.AutomaticFunctionCallingConfig() + ) + + assert should_append_afc_history(config) == True + + +def test_should_append_afc_history_with_ignore_call_history_true(): + config = types.GenerateContentConfig( + automatic_function_calling=types.AutomaticFunctionCallingConfig( + ignore_call_history=True + ) + ) + + assert should_append_afc_history(config) == False + + +def test_should_append_afc_history_with_ignore_call_history_false(): + config = types.GenerateContentConfig( + automatic_function_calling=types.AutomaticFunctionCallingConfig( + ignore_call_history=False + ) + ) + + assert should_append_afc_history(config) == True diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/afc/test_should_disable_afc.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/afc/test_should_disable_afc.py new file mode 100644 index 0000000000000000000000000000000000000000..188bf2b57a84a395b9198bf9dd5aa7480b126f88 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/afc/test_should_disable_afc.py @@ -0,0 +1,214 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for should_disable_afc.""" + +import pytest +from ... import types +from ..._extra_utils import should_disable_afc + + +def test_config_is_none(): + assert should_disable_afc(None) is False + + +def test_afc_config_unset(): + assert should_disable_afc(types.GenerateContentConfig()) is False + + +def test_afc_enable_unset_max_0(): + assert ( + should_disable_afc( + types.GenerateContentConfig( + automatic_function_calling=types.AutomaticFunctionCallingConfig( + maximum_remote_calls=0, + ), + ) + ) + is True + ) + + +def test_afc_enable_unset_max_negative(): + assert ( + should_disable_afc( + types.GenerateContentConfig( + automatic_function_calling=types.AutomaticFunctionCallingConfig( + maximum_remote_calls=-1, + ), + ) + ) + is True + ) + + +def test_afc_enable_unset_max_0_0(): + assert ( + should_disable_afc( + {'automatic_function_calling': {'maximum_remote_calls': 0.0}} + ) + is True + ) + + +def test_afc_enable_unset_max_1(): + assert ( + should_disable_afc( + types.GenerateContentConfig( + automatic_function_calling=types.AutomaticFunctionCallingConfig( + maximum_remote_calls=1, + ), + ) + ) + is False + ) + + +def test_afc_enable_unset_max_1_0(): + assert ( + should_disable_afc( + {'automatic_function_calling': {'maximum_remote_calls': 1.0}} + ) + is False + ) + + +def test_afc_enable_false_max_unset(): + assert ( + should_disable_afc( + types.GenerateContentConfig( + automatic_function_calling=types.AutomaticFunctionCallingConfig( + disable=True, + ), + ) + ) + is True + ) + + +def test_afc_enable_false_max_0(): + assert ( + should_disable_afc( + types.GenerateContentConfig( + automatic_function_calling=types.AutomaticFunctionCallingConfig( + disable=True, + maximum_remote_calls=0, + ), + ) + ) + is True + ) + + +def test_afc_enable_false_max_negative(): + assert ( + should_disable_afc( + types.GenerateContentConfig( + automatic_function_calling=types.AutomaticFunctionCallingConfig( + disable=True, + maximum_remote_calls=-1, + ), + ) + ) + is True + ) + + +def test_afc_enable_false_max_0_0(): + assert ( + should_disable_afc( + {'automatic_function_calling': {'maximum_remote_calls': 0.0}} + ) + is True + ) + + +def test_afc_enable_false_max_1(): + assert ( + should_disable_afc( + types.GenerateContentConfig( + automatic_function_calling=types.AutomaticFunctionCallingConfig( + disable=True, + maximum_remote_calls=1, + ), + ) + ) + is True + ) + + +def test_afc_enable_true_max_unset(): + assert ( + should_disable_afc( + types.GenerateContentConfig( + automatic_function_calling=types.AutomaticFunctionCallingConfig( + disable=False, + ), + ) + ) + is False + ) + + +def test_afc_enable_true_max_0(): + assert ( + should_disable_afc( + types.GenerateContentConfig( + automatic_function_calling=types.AutomaticFunctionCallingConfig( + disable=False, + maximum_remote_calls=0, + ), + ) + ) + is True + ) + + +def test_afc_enable_true_max_negative(): + assert ( + should_disable_afc( + types.GenerateContentConfig( + automatic_function_calling=types.AutomaticFunctionCallingConfig( + disable=False, + maximum_remote_calls=-1, + ), + ) + ) + is True + ) + + +def test_afc_enable_true_max_0_0(): + assert ( + should_disable_afc( + {'automatic_function_calling': {'maximum_remote_calls': 0.0}} + ) + is True + ) + + +def test_afc_enable_true_max_1(): + assert ( + should_disable_afc( + types.GenerateContentConfig( + automatic_function_calling=types.AutomaticFunctionCallingConfig( + disable=False, + maximum_remote_calls=1, + ), + ) + ) + is False + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/batches/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/batches/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e81ca58ba9f30e14fc2dd366cdbf299beb4622f6 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/batches/__init__.py @@ -0,0 +1,17 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for the Google GenAI SDK's batches module.""" \ No newline at end of file diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/batches/test_cancel.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/batches/test_cancel.py new file mode 100644 index 0000000000000000000000000000000000000000..80b1c42d888665b8af122a6ab18df09d91375786 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/batches/test_cancel.py @@ -0,0 +1,77 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for batches.cancel().""" + +import pytest + +from ... import types +from .. import pytest_helper + + +# Vertex AI batch job name. +_BATCH_JOB_NAME = '6339625664542408704' +_BATCH_JOB_FULL_RESOURCE_NAME = ( + 'projects/964831358985/locations/us-central1/' + f'batchPredictionJobs/{_BATCH_JOB_NAME}' +) +# MLDev batch operation name. +_MLDEV_BATCH_OPERATION_NAME = 'batches/0yew7plxupyybd7appsrq5vw7w0lp3l79lab' +_INVALID_BATCH_JOB_NAME = 'invalid_name' + + +# All tests will be run for both Vertex and MLDev. +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_cancel_batch_job', + parameters=types._CancelBatchJobParameters( + name=_BATCH_JOB_NAME, + ), + exception_if_mldev='Invalid batch job name', + skip_in_api_mode=('Cannot cancel a batch job multiple times in Vertex'), + ), + pytest_helper.TestTableItem( + name='test_cancel_batch_operation', + parameters=types._CancelBatchJobParameters( + name=_MLDEV_BATCH_OPERATION_NAME, + ), + exception_if_vertex='Invalid batch job name', + ), + pytest_helper.TestTableItem( + name='test_cancel_batch_job_with_invalid_name', + parameters=types._CancelBatchJobParameters( + name=_INVALID_BATCH_JOB_NAME, + ), + exception_if_mldev='Invalid batch job name', + exception_if_vertex='Invalid batch job name', + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='batches.cancel', + test_table=test_table, +) + + +@pytest.mark.asyncio +async def test_async_cancel(client): + if client.vertexai: + name = _BATCH_JOB_NAME + else: + name = _MLDEV_BATCH_OPERATION_NAME + await client.aio.batches.cancel(name=name) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/batches/test_create.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/batches/test_create.py new file mode 100644 index 0000000000000000000000000000000000000000..55c4be83a7f8ad79ec52edc9d27574af3cd3b027 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/batches/test_create.py @@ -0,0 +1,123 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for batches.create() with invalid source and destinations.""" + +import pytest + +from ... import types +from .. import pytest_helper + + +_GEMINI_MODEL = 'gemini-2.5-flash' +_EMBEDDING_MODEL = 'gemini-embedding-001' +_DISPLAY_NAME = 'test_batch' + +_GENERATE_CONTENT_BQ_OUTPUT_PREFIX = ( + 'bq://vertex-sdk-dev.unified_genai_tests_batches.generate_content_output' +) + +_EMBEDDING_BQ_INPUT_FILE = ( + 'bq://vertex-sdk-dev.unified_genai_tests_batches.embedding_requests' +) + + +# All tests will be run for both Vertex and MLDev. +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_union_with_invalid_src', + parameters=types._CreateBatchJobParameters( + model=_GEMINI_MODEL, + src='invalid_src', + config={ + 'display_name': _DISPLAY_NAME, + 'dest': _GENERATE_CONTENT_BQ_OUTPUT_PREFIX, + }, + ), + exception_if_mldev='Unsupported source', + exception_if_vertex='Unsupported source', + has_union=True, + ), + pytest_helper.TestTableItem( + name='test_union_with_invalid_dest', + parameters=types._CreateBatchJobParameters( + model=_EMBEDDING_MODEL, + src=_EMBEDDING_BQ_INPUT_FILE, + config={ + 'display_name': _DISPLAY_NAME, + 'dest': 'invalid_dest', + }, + ), + exception_if_mldev='not supported in Gemini API', + exception_if_vertex='Unsupported destination', + has_union=True, + ), + pytest_helper.TestTableItem( + name='test_create_with_webhook_config', + parameters=types._CreateBatchJobParameters( + model=_GEMINI_MODEL, + src={ + 'inlined_requests': [ + { + 'contents': [ + {'parts': [{'text': 'say hello'}], 'role': 'user'} + ] + }, + ] + }, + config=types.CreateBatchJobConfig( + display_name=_DISPLAY_NAME, + webhook_config=types.WebhookConfig( + uris=['https://example.com/webhook'], + user_metadata={'batch_id': '123'}, + ), + ), + ), + exception_if_vertex='not supported in Vertex AI', + ), + pytest_helper.TestTableItem( + name='test_create_with_webhook_config_dict', + parameters=types._CreateBatchJobParameters( + model=_GEMINI_MODEL, + src={ + 'inlined_requests': [ + { + 'contents': [ + {'parts': [{'text': 'say hello'}], 'role': 'user'} + ] + }, + ] + }, + config={ + 'display_name': _DISPLAY_NAME, + 'webhook_config': { + 'uris': ['https://example.com/webhook'], + }, + }, + ), + exception_if_vertex='not supported in Vertex AI', + ), +] + +pytestmark = [ + pytest.mark.usefixtures('mock_timestamped_unique_name'), + pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='batches.create', + test_table=test_table, + ), +] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/batches/test_create_with_bigquery.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/batches/test_create_with_bigquery.py new file mode 100644 index 0000000000000000000000000000000000000000..37dec980005243d8a9136776e4f2eaf9e5e7d933 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/batches/test_create_with_bigquery.py @@ -0,0 +1,113 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for batches.create() with BigQuery source.""" + +import pytest + +from ... import types +from .. import pytest_helper + + +_GEMINI_MODEL = 'gemini-2.5-flash' +_GEMINI_MODEL_FULL_NAME = 'publishers/google/models/gemini-2.5-flash' +_EMBEDDING_MODEL = 'gemini-embedding-001' +_EMBEDDING_MODEL_FULL_NAME = 'publishers/google/models/gemini-embedding-001' +_DISPLAY_NAME = 'test_batch' +_GENERATE_CONTENT_BQ_INPUT_FILE = ( + 'bq://vertex-sdk-dev.unified_genai_tests_batches.generate_content_requests' +) +_GENERATE_CONTENT_BQ_OUTPUT_PREFIX = ( + 'bq://vertex-sdk-dev.unified_genai_tests_batches.generate_content_output' +) + +_EMBEDDING_BQ_INPUT_FILE = ( + 'bq://vertex-sdk-dev.unified_genai_tests_batches.embedding_requests' +) +_EMBEDDING_BQ_OUTPUT_PREFIX = ( + 'bq://vertex-sdk-dev.unified_genai_tests_batches.embedding_output' +) + + +# All tests will be run for both Vertex and MLDev. +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_union_generate_content_with_bigquery', + parameters=types._CreateBatchJobParameters( + model=_GEMINI_MODEL_FULL_NAME, + src=_GENERATE_CONTENT_BQ_INPUT_FILE, + ), + exception_if_mldev='not supported in Gemini API', + has_union=True, + ), + pytest_helper.TestTableItem( + name='test_union_embedding_with_bigquery', + parameters=types._CreateBatchJobParameters( + model='publishers/google/models/text-embedding-004', + src=_EMBEDDING_BQ_INPUT_FILE, + config={ + 'display_name': _DISPLAY_NAME, + 'dest': _EMBEDDING_BQ_OUTPUT_PREFIX, + }, + ), + exception_if_mldev='not supported in Gemini API', + has_union=True, + ), + pytest_helper.TestTableItem( + name='test_generate_content_with_bigquery', + parameters=types._CreateBatchJobParameters( + model=_GEMINI_MODEL_FULL_NAME, + src={ + 'bigquery_uri': _GENERATE_CONTENT_BQ_INPUT_FILE, + 'format': 'bigquery', + }, + config={ + 'display_name': _DISPLAY_NAME, + 'dest': { + 'bigquery_uri': _GENERATE_CONTENT_BQ_OUTPUT_PREFIX, + 'format': 'bigquery', + }, + }, + ), + exception_if_mldev='one of', + ), +] + +pytestmark = [ + pytest.mark.usefixtures('mock_timestamped_unique_name'), + pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='batches.create', + test_table=test_table, + ), +] + + +@pytest.mark.asyncio +async def test_async_create(client): + with pytest_helper.exception_if_mldev(client, ValueError): + batch_job = await client.aio.batches.create( + model=_GEMINI_MODEL, + src=_GENERATE_CONTENT_BQ_INPUT_FILE, + ) + + assert batch_job.name.startswith('projects/') + assert ( + batch_job.model == _GEMINI_MODEL_FULL_NAME + ) # Converted to Vertex full name. + assert batch_job.src.bigquery_uri == _GENERATE_CONTENT_BQ_INPUT_FILE + assert batch_job.src.format == 'bigquery' diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/batches/test_create_with_file.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/batches/test_create_with_file.py new file mode 100644 index 0000000000000000000000000000000000000000..dd8b929d02ce8798b6a5d99fbc7517f758943e09 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/batches/test_create_with_file.py @@ -0,0 +1,82 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for batches.create() with file source.""" + +import pytest + +from ... import types +from .. import pytest_helper + + +_GEMINI_MODEL = 'gemini-2.5-flash' +_DISPLAY_NAME = 'test_batch' + +_MLDEV_GEMINI_MODEL = 'gemini-2.5-flash' +_FILE_NAME = 'files/s0pa54alni6w' + +# All tests will be run for both Vertex and MLDev. +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_union_generate_content_with_file', + parameters=types._CreateBatchJobParameters( + model=_MLDEV_GEMINI_MODEL, + src={'file_name': _FILE_NAME}, + config={ + 'display_name': _DISPLAY_NAME, + }, + ), + exception_if_vertex='not supported', + has_union=True, + ), + pytest_helper.TestTableItem( + name='test_generate_content_with_file', + parameters=types._CreateBatchJobParameters( + model=_MLDEV_GEMINI_MODEL, + src={'file_name': _FILE_NAME}, + config={ + 'display_name': _DISPLAY_NAME, + }, + ), + exception_if_vertex='not supported', + ), +] + +pytestmark = [ + pytest.mark.usefixtures('mock_timestamped_unique_name'), + pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='batches.create', + test_table=test_table, + ), +] + + +@pytest.mark.asyncio +async def test_async_create(client): + with pytest_helper.exception_if_vertex(client, ValueError): + batch_job = await client.aio.batches.create( + model=_MLDEV_GEMINI_MODEL, + src={'file_name': _FILE_NAME}, + config={ + 'display_name': _DISPLAY_NAME, + }, + ) + assert batch_job.name.startswith('batches/') + assert ( + batch_job.model == 'models/' + _MLDEV_GEMINI_MODEL + ) # Converted to Gemini full name. diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/batches/test_create_with_gcs.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/batches/test_create_with_gcs.py new file mode 100644 index 0000000000000000000000000000000000000000..cb89346687a9a2f871a002ab1d3da5e1bddbed97 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/batches/test_create_with_gcs.py @@ -0,0 +1,125 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for batches.create() with Google Cloud Storage source.""" + +import pytest + +from ... import types +from .. import pytest_helper + + +_GEMINI_MODEL = 'gemini-2.5-flash' +_GEMINI_MODEL_FULL_NAME = 'publishers/google/models/gemini-2.5-flash' +_EMBEDDING_MODEL = 'gemini-embedding-001' +_EMBEDDING_MODEL_FULL_NAME = 'publishers/google/models/gemini-embedding-001' +_DISPLAY_NAME = 'test_batch' + +_GENERATE_CONTENT_GCS_INPUT_FILE = ( + 'gs://unified-genai-tests/batches/input/generate_content_requests.jsonl' +) +_GENERATE_CONTENT_GCS_OUTPUT_PREFIX = 'gs://unified-genai-tests/batches/output' + +_EMBEDDING_GCS_INPUT_FILE = ( + 'gs://unified-genai-tests/batches/input/embedding_requests.jsonl' +) +_EMBEDDING_GCS_OUTPUT_PREFIX = 'gs://unified-genai-tests/batches/output' + + +# All tests will be run for both Vertex and MLDev. +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_union_generate_content_with_gcs', + parameters=types._CreateBatchJobParameters( + model=_GEMINI_MODEL, + src=_GENERATE_CONTENT_GCS_INPUT_FILE, + ), + exception_if_mldev='not supported in Gemini API', + has_union=True, + ), + pytest_helper.TestTableItem( + name='test_union_embedding_with_gcs', + parameters=types._CreateBatchJobParameters( + model='text-embedding-004', + src=_EMBEDDING_GCS_INPUT_FILE, + config={ + 'display_name': _DISPLAY_NAME, + 'dest': _EMBEDDING_GCS_OUTPUT_PREFIX, + }, + ), + exception_if_mldev='not supported in Gemini API', + has_union=True, + ), + pytest_helper.TestTableItem( + name='test_union_with_http_options', + parameters=types._CreateBatchJobParameters( + model=_GEMINI_MODEL, + src=_GENERATE_CONTENT_GCS_INPUT_FILE, + config={ + 'http_options': { + 'api_version': 'v1', + 'headers': {'test': 'headers'}, + }, + }, + ), + exception_if_mldev='not supported in Gemini API', + has_union=True, + ), + pytest_helper.TestTableItem( + name='test_generate_content_with_gcs', + parameters=types._CreateBatchJobParameters( + model=_GEMINI_MODEL, + src={ + 'gcs_uri': [_GENERATE_CONTENT_GCS_INPUT_FILE], + 'format': 'jsonl', + }, + config={ + 'display_name': _DISPLAY_NAME, + 'dest': { + 'gcs_uri': _GENERATE_CONTENT_GCS_OUTPUT_PREFIX, + 'format': 'jsonl', + }, + }, + ), + exception_if_mldev='one of', + ), +] + +pytestmark = [ + pytest.mark.usefixtures('mock_timestamped_unique_name'), + pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='batches.create', + test_table=test_table, + ), +] + + +@pytest.mark.asyncio +async def test_async_create(client): + with pytest_helper.exception_if_mldev(client, ValueError): + batch_job = await client.aio.batches.create( + model=_GEMINI_MODEL, + src=_GENERATE_CONTENT_GCS_INPUT_FILE, + ) + + assert batch_job.name.startswith('projects/') + assert ( + batch_job.model == _GEMINI_MODEL_FULL_NAME + ) # Converted to Vertex full name. + assert batch_job.src.gcs_uri == [_GENERATE_CONTENT_GCS_INPUT_FILE] + assert batch_job.src.format == 'jsonl' diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/batches/test_create_with_inlined_requests.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/batches/test_create_with_inlined_requests.py new file mode 100644 index 0000000000000000000000000000000000000000..f528162cd88e6aed6911e8bc65828a4a65fbba97 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/batches/test_create_with_inlined_requests.py @@ -0,0 +1,271 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for batches.create() with inlined requests.""" +import base64 +import copy +import datetime +import os + +import pytest + +from ... import _transformers as t +from ... import types +from .. import pytest_helper + +_GEMINI_MODEL = 'gemini-2.5-flash' +_DISPLAY_NAME = 'test_batch' + +_MLDEV_GEMINI_MODEL = 'gemini-2.5-flash' + +_SAFETY_SETTINGS = [ + { + 'category': 'HARM_CATEGORY_HATE_SPEECH', + 'threshold': 'BLOCK_ONLY_HIGH', + }, + { + 'category': 'HARM_CATEGORY_DANGEROUS_CONTENT', + 'threshold': 'BLOCK_LOW_AND_ABOVE', + }, +] + +_INLINED_REQUESTS = [ + { + 'contents': [{ + 'parts': [{ + 'text': 'what is the number after 1? return just the number.', + }], + 'role': 'user', + }], + 'metadata': { + 'key': 'request-1', + }, + 'config': { + 'safety_settings': _SAFETY_SETTINGS, + }, + }, + { + 'contents': [{ + 'parts': [{ + 'text': 'what is the number after 2? return just the number.', + }], + 'role': 'user', + }], + 'metadata': { + 'key': 'request-2', + }, + 'config': { + 'safety_settings': _SAFETY_SETTINGS, + }, + }, +] +_INLINED_TEXT_REQUEST_UNION = { + 'contents': [{ + 'parts': [{ + 'text': 'high', + }], + 'role': 'user', + }], + 'config': { + 'response_modalities': ['TEXT'], + 'system_instruction': 'I say high, you say low', + 'thinking_config': { + 'include_thoughts': True, + 'thinking_budget': 4000, + }, + }, +} +_INLINED_TEXT_REQUEST = copy.deepcopy(_INLINED_TEXT_REQUEST_UNION) +_INLINED_TEXT_REQUEST['config']['system_instruction'] = t.t_content( + 'I say high, you say low' +) +_INLINED_TEXT_REQUEST['config']['tools'] = [{'google_search': {}}] +_INLINED_TEXT_REQUEST['config']['tool_config'] = { + 'retrieval_config': {'lat_lng': {'latitude': 37.422, 'longitude': -122.084}} +} + +_INLINED_IMAGE_REQUEST = { + 'contents': [{ + 'parts': [ + {'text': 'What is in this image?'}, + { + 'file_data': { + 'file_uri': ( + 'https://generativelanguage.googleapis.com/v1beta/files/kje1wewvo85z' + ), + 'mime_type': 'image/jpeg', + }, + }, + ], + 'role': 'user', + }], + 'config': { + 'temperature': 0.7, + 'top_p': 0.9, + 'top_k': 10, + }, +} +_INLINED_VIDEO_REQUEST = { + 'contents': [{ + 'parts': [ + { + 'text': 'Summerize this video.', + }, + { + 'file_data': { + 'file_uri': ( + 'https://generativelanguage.googleapis.com/v1beta/files/tyvaih24jwje' + ), + 'mime_type': 'video/mp4', + }, + 'video_metadata': { + 'start_offset': '0s', + 'end_offset': '5s', + 'fps': 3, + }, + }, + ], + 'role': 'user', + }], +} +_IMAGE_PNG_FILE_PATH = os.path.abspath( + os.path.join(os.path.dirname(__file__), '../data/google.png') +) +with open(_IMAGE_PNG_FILE_PATH, 'rb') as image_file: + image_bytes = image_file.read() + image_string = base64.b64encode(image_bytes).decode('utf-8') +_INLINED_IMAGE_BLOB_REQUEST = types.InlinedRequest( + contents=[ + types.Content( + parts=[ + types.Part(text='What is this image about?'), + types.Part( + inline_data=types.Blob( + data=image_string, + mime_type='image/png', + ), + ), + ], + role='user', + ) + ] +) + +# All tests will be run for both Vertex and MLDev. +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_union_with_inlined_request', + parameters=types._CreateBatchJobParameters( + model=_MLDEV_GEMINI_MODEL, + src=_INLINED_REQUESTS, + config={ + 'display_name': _DISPLAY_NAME, + }, + ), + exception_if_vertex='not supported in Vertex', + has_union=True, + ), + pytest_helper.TestTableItem( + name='test_with_inlined_request', + parameters=types._CreateBatchJobParameters( + model=_MLDEV_GEMINI_MODEL, + src={'inlined_requests': _INLINED_REQUESTS}, + config={ + 'display_name': _DISPLAY_NAME, + }, + ), + exception_if_vertex='not supported', + ), + pytest_helper.TestTableItem( + name='test_with_inlined_request_config', + parameters=types._CreateBatchJobParameters( + model=_MLDEV_GEMINI_MODEL, + src={'inlined_requests': _INLINED_REQUESTS}, + config={ + 'display_name': _DISPLAY_NAME, + }, + ), + exception_if_vertex='not supported', + ), + pytest_helper.TestTableItem( + name='test_union_with_inlined_request_system_instruction', + parameters=types._CreateBatchJobParameters( + model=_MLDEV_GEMINI_MODEL, + src={'inlined_requests': [_INLINED_TEXT_REQUEST_UNION]}, + config={ + 'display_name': _DISPLAY_NAME, + }, + ), + has_union=True, + exception_if_vertex='not supported', + ), + pytest_helper.TestTableItem( + name='test_with_image_file', + parameters=types._CreateBatchJobParameters( + model=_MLDEV_GEMINI_MODEL, + src={'inlined_requests': [_INLINED_IMAGE_REQUEST]}, + config={ + 'display_name': _DISPLAY_NAME, + }, + ), + exception_if_vertex='not supported', + ), + pytest_helper.TestTableItem( + name='test_with_image_blob', + parameters=types._CreateBatchJobParameters( + model=_MLDEV_GEMINI_MODEL, + src={'inlined_requests': [_INLINED_IMAGE_BLOB_REQUEST]}, + config={ + 'display_name': _DISPLAY_NAME, + }, + ), + exception_if_vertex='not supported', + ), + pytest_helper.TestTableItem( + name='test_with_video_file', + parameters=types._CreateBatchJobParameters( + model=_MLDEV_GEMINI_MODEL, + src={'inlined_requests': [_INLINED_VIDEO_REQUEST]}, + config={ + 'display_name': _DISPLAY_NAME, + }, + ), + exception_if_vertex='not supported', + ), +] + +pytestmark = [ + pytest.mark.usefixtures('mock_timestamped_unique_name'), + pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='batches.create', + test_table=test_table, + ), +] + + +@pytest.mark.asyncio +async def test_async_create(client): + with pytest_helper.exception_if_vertex(client, ValueError): + batch_job = await client.aio.batches.create( + model=_GEMINI_MODEL, + src=_INLINED_REQUESTS, + ) + assert batch_job.name.startswith('batches/') + assert ( + batch_job.model == 'models/' + _GEMINI_MODEL + ) # Converted to Gemini full name. diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/batches/test_delete.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/batches/test_delete.py new file mode 100644 index 0000000000000000000000000000000000000000..f084189a7844384312a6659e0f245c6da76c7a94 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/batches/test_delete.py @@ -0,0 +1,86 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for batches.delete().""" + +import pytest + +from ... import types +from .. import pytest_helper + + +_BATCH_JOB_NAME = '7085929781874655232' +_BATCH_JOB_FULL_RESOURCE_NAME = ( + 'projects/964831358985/locations/us-central1/' + f'batchPredictionJobs/{_BATCH_JOB_NAME}' +) +_INVALID_BATCH_JOB_NAME = 'invalid_name' +_MLDEV_BATCH_OPERATION_NAME = 'batches/70h2jo0ic2t1zejyl0p4jgi8mk1gj0wvjusv' + + +# All tests will be run for both Vertex and MLDev. +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_delete_batch_job', + parameters=types._DeleteBatchJobParameters( + name=_BATCH_JOB_NAME, + ), + exception_if_mldev='Invalid batch job name', + skip_in_api_mode=('Cannot cancel a batch job multiple times in Vertex'), + ), + pytest_helper.TestTableItem( + name='test_delete_batch_job_full_resource_name', + override_replay_id='test_delete_batch_job', + parameters=types._DeleteBatchJobParameters( + name=_BATCH_JOB_FULL_RESOURCE_NAME, + ), + exception_if_mldev='Invalid batch job name', + skip_in_api_mode=('Cannot cancel a batch job multiple times in Vertex'), + ), + pytest_helper.TestTableItem( + name='test_delete_batch_job_with_invalid_name', + parameters=types._DeleteBatchJobParameters( + name=_INVALID_BATCH_JOB_NAME, + ), + exception_if_mldev='Invalid batch job name', + exception_if_vertex='Invalid batch job name', + ), + pytest_helper.TestTableItem( + name='test_delete_batch_operation', + parameters=types._DeleteBatchJobParameters( + name=_MLDEV_BATCH_OPERATION_NAME, + ), + exception_if_vertex='Invalid batch job name', + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='batches.delete', + test_table=test_table, +) + + +@pytest.mark.asyncio +async def test_async_delete(client): + if client.vertexai: + name = _BATCH_JOB_NAME + else: + name = _MLDEV_BATCH_OPERATION_NAME + + delete_job = await client.aio.batches.delete(name=name) + assert delete_job diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/batches/test_embedding.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/batches/test_embedding.py new file mode 100644 index 0000000000000000000000000000000000000000..e8a8e2df772e872a630ea9dd6eea5abea9e61417 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/batches/test_embedding.py @@ -0,0 +1,157 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for batches._create_embeddings()""" + +import pytest + +from ... import types +from .. import pytest_helper + +_MLDEV_EMBEDDING_BATCH_INLINE_OPERATION_NAME = ( + 'batches/wdx71o8cgbzoa6gg3be1mg7g8ulrhapcjgo3' +) +_MLDEV_EMBEDDING_BATCH_FILE_OPERATION_NAME = ( + 'batches/507oatd242het8ox60pwsmn7tcmtkrj8itff' +) + +_DISPLAY_NAME = 'test_batch' +_MLDEV_EMBEDDING_MODEL = 'gemini-embedding-001' +_EMBED_CONTENT_FILE_NAME = 'files/mq9e3mg3u2y5' +_INLINED_EMBED_CONTENT_REQUESTS = { + 'config': {'output_dimensionality': 64}, + 'contents': [ + { + 'parts': [{ + 'text': '1', + }], + }, + { + 'parts': [{ + 'text': '2', + }], + }, + { + 'parts': [{ + 'text': '3', + }], + }, + ], +} + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_from_inlined', + parameters=types._CreateEmbeddingsBatchJobParameters( + model=_MLDEV_EMBEDDING_MODEL, + src={'inlined_requests': _INLINED_EMBED_CONTENT_REQUESTS}, + config={ + 'display_name': _DISPLAY_NAME, + }, + ), + exception_if_vertex='Vertex AI does not support', + ), +] + +pytestmark = [ + pytest.mark.usefixtures('mock_timestamped_unique_name'), + pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='batches.create_embeddings', + test_table=test_table, + http_options={ + 'api_version': 'v1alpha', + 'base_url': ( + 'https://autopush-generativelanguage.sandbox.googleapis.com' + ), + }, + ), +] + + +@pytest.mark.asyncio +async def test_async_from_inline(client): + with pytest_helper.exception_if_vertex(client, ValueError): + batch_job = await client.aio.batches.create_embeddings( + model=_MLDEV_EMBEDDING_MODEL, + src={'inlined_requests': _INLINED_EMBED_CONTENT_REQUESTS}, + ) + assert batch_job.name.startswith('batches/') + + +def test_from_file(client): + """Tests creating a batch job with an embedding file name.""" + with pytest_helper.exception_if_vertex(client, ValueError): + batch_job = client.batches.create_embeddings( + model=_MLDEV_EMBEDDING_MODEL, + src={'file_name': _EMBED_CONTENT_FILE_NAME}, + config={ + 'display_name': _DISPLAY_NAME, + }, + ) + assert batch_job.name.startswith('batches/') + assert batch_job.model == 'models/' + _MLDEV_EMBEDDING_MODEL + + +@pytest.mark.asyncio +async def test_async_from_file(client): + with pytest_helper.exception_if_vertex(client, ValueError): + batch_job = await client.aio.batches.create_embeddings( + model=_MLDEV_EMBEDDING_MODEL, + src={'file_name': _EMBED_CONTENT_FILE_NAME}, + config={ + 'display_name': _DISPLAY_NAME, + }, + ) + assert batch_job.name.startswith('batches/') + assert ( + batch_job.model == 'models/' + _MLDEV_EMBEDDING_MODEL + ) # Converted to Gemini full name. + + +def test_get_inline(client): + """Tests getting a batch job that used inline requests.""" + with pytest_helper.exception_if_vertex(client, ValueError): + name = _MLDEV_EMBEDDING_BATCH_INLINE_OPERATION_NAME + batch_job = client.batches.get(name=name) + assert batch_job.dest.inlined_embed_content_responses is not None + + +@pytest.mark.asyncio +async def test_async_get_inline(client): + with pytest_helper.exception_if_vertex(client, ValueError): + name = _MLDEV_EMBEDDING_BATCH_INLINE_OPERATION_NAME + batch_job = await client.aio.batches.get(name=name) + + assert batch_job.dest.inlined_embed_content_responses is not None + + +def test_get_file(client): + """Tests getting a batch job that used a file source.""" + with pytest_helper.exception_if_vertex(client, ValueError): + name = _MLDEV_EMBEDDING_BATCH_FILE_OPERATION_NAME + batch_job = client.batches.get(name=name) + assert batch_job.dest.file_name is not None + + +@pytest.mark.asyncio +async def test_async_get_file(client): + with pytest_helper.exception_if_vertex(client, ValueError): + name = _MLDEV_EMBEDDING_BATCH_FILE_OPERATION_NAME + batch_job = await client.aio.batches.get(name=name) + + assert batch_job.dest.file_name is not None diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/batches/test_get.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/batches/test_get.py new file mode 100644 index 0000000000000000000000000000000000000000..5f010ab1800a856db4232d1477b896fbb70b46bd --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/batches/test_get.py @@ -0,0 +1,78 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for batches.get().""" + +import pytest + +from ... import types +from .. import pytest_helper + + +# Vertex AI batch job name. +_BATCH_JOB_NAME = '5798522612028014592' +_BATCH_JOB_FULL_RESOURCE_NAME = ( + 'projects/964831358985/locations/us-central1/' + f'batchPredictionJobs/{_BATCH_JOB_NAME}' +) +# MLDev batch operation name. +_MLDEV_BATCH_OPERATION_NAME = 'batches/z2p8ksus4lyxt25rntl3fpd67p2niw4hfij5' +_INVALID_BATCH_JOB_NAME = 'invalid_name' + + +# All tests will be run for both Vertex and MLDev. +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_get_batch_job', + parameters=types._GetBatchJobParameters( + name=_BATCH_JOB_NAME, + ), + exception_if_mldev='Invalid batch job name', + ), + pytest_helper.TestTableItem( + name='test_get_batch_operation', + parameters=types._GetBatchJobParameters( + name=_MLDEV_BATCH_OPERATION_NAME, + ), + exception_if_vertex='Invalid batch job name', + ), + pytest_helper.TestTableItem( + name='test_get_batch_job_with_invalid_name', + parameters=types._GetBatchJobParameters( + name=_INVALID_BATCH_JOB_NAME, + ), + exception_if_mldev='Invalid batch job name', + exception_if_vertex='Invalid batch job name', + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='batches.get', + test_table=test_table, +) + + +@pytest.mark.asyncio +async def test_async_get(client): + if client.vertexai: + name = _BATCH_JOB_NAME + else: + name = _MLDEV_BATCH_OPERATION_NAME + batch_job = await client.aio.batches.get(name=name) + + assert batch_job diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/batches/test_list.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/batches/test_list.py new file mode 100644 index 0000000000000000000000000000000000000000..2cfd66db8789dc6e51e31a3286a67ac416385891 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/batches/test_list.py @@ -0,0 +1,79 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for batches.list().""" + +import pytest + +from ... import errors +from ... import types +from .. import pytest_helper + + +# All tests will be run for both Vertex and MLDev. +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_list_batch_jobs', + parameters=types._ListBatchJobsParameters( + config=types.ListBatchJobsConfig( + page_size=5, + ), + ), + ), + pytest_helper.TestTableItem( + name='test_list_batch_jobs_with_config', + parameters=types._ListBatchJobsParameters( + config=types.ListBatchJobsConfig( + filter='display_name:"genai_*"', + page_size=5, + ), + ), + exception_if_mldev='filter parameter is not supported in Gemini API', + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='batches.list', + test_table=test_table, +) + + +def test_pager(client): + batch_jobs = client.batches.list(config={'page_size': 10}) + assert 'content-type' in batch_jobs.sdk_http_response.headers + assert batch_jobs.name == 'batch_jobs' + assert batch_jobs.page_size == 10 + assert len(batch_jobs) <= 10 + + # Iterate through the first page. Otherwise, too many batches are returned. + for _ in batch_jobs.page: + pass + + +@pytest.mark.asyncio +async def test_async_pager(client): + batch_jobs = await client.aio.batches.list(config={'page_size': 10}) + + assert 'Content-Type' in batch_jobs.sdk_http_response.headers + assert batch_jobs.name == 'batch_jobs' + assert batch_jobs.page_size == 10 + assert len(batch_jobs) <= 10 + + # Iterate through the first page. Otherwise, too many batches are returned. + for _ in batch_jobs.page: + pass diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/caches/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/caches/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fd82d9e9ac12fd740239b74a4cbeb4b596a8305a --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/caches/__init__.py @@ -0,0 +1,17 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for the Google GenAI SDK's caches module.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/caches/constants.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/caches/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..e7a9d8ea922e07d162a56c2364e151e33235f4b9 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/caches/constants.py @@ -0,0 +1,29 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Constants for caches tests.""" + +CACHED_CONTENT_NAME_MLDEV = 'cachedContents/o239k1gxzz0juy9wqstndhncr85krehehf551hqh' +CACHED_CONTENT_NAME_VERTEX = 'cachedContents/2164089915711684608' + +VERTEX_HTTP_OPTIONS = { + 'api_version': 'v1beta1', + 'base_url': 'https://us-central1-aiplatform.googleapis.com/', +} +MLDEV_HTTP_OPTIONS = { + 'api_version': 'v1beta', + 'base_url': 'https://generativelanguage.googleapis.com/', +} \ No newline at end of file diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/caches/test_create.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/caches/test_create.py new file mode 100644 index 0000000000000000000000000000000000000000..27362b96a4c220bf8060d5170d6aef6566a7c641 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/caches/test_create.py @@ -0,0 +1,210 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +from copy import deepcopy +import datetime +import pytest +import sys +from ... import types +from .. import pytest_helper +from ... import _transformers as t + + +_CREATE_CACHED_CONTENT_PARAMETERS_GCS_URI = types._CreateCachedContentParameters( + model='gemini-2.5-flash', + config={ + 'contents': [ + types.Content( + role='user', + parts=[ + types.Part( + fileData=types.FileData( + fileUri='gs://cloud-samples-data/generative-ai/pdf/2312.11805v3.pdf', + mimeType='application/pdf', + ) + ), + types.Part( + fileData=types.FileData( + fileUri='gs://cloud-samples-data/generative-ai/pdf/2403.05530.pdf', + mimeType='application/pdf', + ) + ), + ], + ) + ], + 'system_instruction': t.t_content('What is the sum of the two pdfs?'), + 'display_name': 'test cache', + 'ttl': '86400s', + }, +) + +_CREATE_CACHED_CONTENT_PARAMETERS_GOOGLEAI_FILE = types._CreateCachedContentParameters( + model='gemini-2.5-flash', + config={ + 'contents': [ + types.Content( + role='user', + parts=[ + types.Part( + fileData=types.FileData( + mimeType='application/pdf', + fileUri='https://generativelanguage.googleapis.com/v1beta/files/v200dhvn15h7', + ) + ) + ], + ) + ], + 'system_instruction': t.t_content('What is the sum of the two pdfs?'), + 'display_name': 'test cache', + 'ttl': '86400s', + }, +) + +_CREATE_CACHED_CONTENT_PARAMETERS_GCS_URI_PARTIAL_MODEL_1 = deepcopy( + _CREATE_CACHED_CONTENT_PARAMETERS_GCS_URI +) +_CREATE_CACHED_CONTENT_PARAMETERS_GCS_URI_PARTIAL_MODEL_1.model = ( + 'models/gemini-2.5-flash' +) +_CREATE_CACHED_CONTENT_PARAMETERS_GCS_URI_PARTIAL_MODEL_2 = deepcopy( + _CREATE_CACHED_CONTENT_PARAMETERS_GCS_URI +) +_CREATE_CACHED_CONTENT_PARAMETERS_GCS_URI_PARTIAL_MODEL_2.model = ( + 'publishers/google/models/gemini-2.5-flash' +) + +_CREATE_CACHED_CONTENT_PARAMETERS_GOOGLEAI_FILE_PARTIAL_MODEL_1 = deepcopy( + _CREATE_CACHED_CONTENT_PARAMETERS_GOOGLEAI_FILE +) +_CREATE_CACHED_CONTENT_PARAMETERS_GOOGLEAI_FILE_PARTIAL_MODEL_1.model = ( + 'models/gemini-2.5-flash' +) + +_CREATE_CACHED_CONTENT_PARAMETERS_GCS_URI_CMEK = deepcopy( + _CREATE_CACHED_CONTENT_PARAMETERS_GCS_URI +) +_CREATE_CACHED_CONTENT_PARAMETERS_GCS_URI_CMEK.config.kms_key_name = ( + 'projects/test-project/locations/us-central1/keyRings/test-keyring/cryptoKeys/test-key' +) + +if sys.version_info >= (3, 11): + _EXPIRE_TIME = datetime.datetime.fromisoformat('2025-12-20T00:00:00Z') +else: + _EXPIRE_TIME = datetime.datetime.fromisoformat('2025-12-20T00:00:00+00:00') + +_CREATE_CACHED_CONTENT_PARAMETERS_GCS_URI_EXPIRE_TIME = deepcopy( + _CREATE_CACHED_CONTENT_PARAMETERS_GCS_URI +) +_CREATE_CACHED_CONTENT_PARAMETERS_GCS_URI_EXPIRE_TIME.config.ttl = None +_CREATE_CACHED_CONTENT_PARAMETERS_GCS_URI_EXPIRE_TIME.config.expire_time = ( + _EXPIRE_TIME +) +_CREATE_CACHED_CONTENT_PARAMETERS_GCS_URI_EXPIRE_TIME.config.display_name = ( + 'test cache' +) + +_CREATE_CACHED_CONTENT_PARAMETERS_GOOGLEAI_FILE_EXPIRE_TIME = deepcopy( + _CREATE_CACHED_CONTENT_PARAMETERS_GOOGLEAI_FILE +) +_CREATE_CACHED_CONTENT_PARAMETERS_GOOGLEAI_FILE_EXPIRE_TIME.config.ttl = None +_CREATE_CACHED_CONTENT_PARAMETERS_GOOGLEAI_FILE_EXPIRE_TIME.config.expire_time = ( + _EXPIRE_TIME +) +_CREATE_CACHED_CONTENT_PARAMETERS_GOOGLEAI_FILE_EXPIRE_TIME.config.display_name = ( + 'test cache' +) + + +# Replay mode is not supported for caches tests due to the error message +# inconsistency in api and replay mode. +# To run api mode tests, use the following steps: +# 1. First create the resource. +# sh run_tests.sh pytest -s tests/caches/test_create.py --mode=api +# 1.1 If mldev test_create fails, update the uploaded file using this colab +# https://colab.sandbox.google.com/drive/1Fv6KGSs0cg6tlpcUHdsclHussXMEGOXk#scrollTo=RSKmFPx00MVL. +# 2. Find the resource name in debugging print and change the resource name constants.py. +# 3. Run and record get and update tests. +# sh run_tests.sh pytest -s tests/caches/test_get.py --mode=api && sh run_tests.sh pytest -s tests/caches/test_update.py --mode=api && sh run_tests.sh pytest -s tests/caches/test_delete.py --mode=api +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_caches_create_with_gcs_uri', + exception_if_mldev='INVALID_ARGUMENT', + parameters=_CREATE_CACHED_CONTENT_PARAMETERS_GCS_URI, + ), + pytest_helper.TestTableItem( + name='test_caches_create_with_gcs_uri_cmek', + exception_if_mldev='not supported', + exception_if_vertex='INVALID_ARGUMENT', # The key is invalid. + parameters=_CREATE_CACHED_CONTENT_PARAMETERS_GCS_URI_CMEK, + ), + pytest_helper.TestTableItem( + name='test_caches_create_with_gcs_uri_expire_time', + exception_if_mldev='INVALID_ARGUMENT', + parameters=_CREATE_CACHED_CONTENT_PARAMETERS_GCS_URI_EXPIRE_TIME, + ), + pytest_helper.TestTableItem( + name='test_caches_create_model_partial_path_1', + exception_if_mldev='INVALID_ARGUMENT', + parameters=_CREATE_CACHED_CONTENT_PARAMETERS_GCS_URI_PARTIAL_MODEL_1, + ), + pytest_helper.TestTableItem( + name='test_caches_create_model_partial_path_2', + exception_if_mldev='404', + parameters=_CREATE_CACHED_CONTENT_PARAMETERS_GCS_URI_PARTIAL_MODEL_2, + ), + pytest_helper.TestTableItem( + name='test_caches_create_with_googleai_file', + exception_if_vertex='Internal', + parameters=_CREATE_CACHED_CONTENT_PARAMETERS_GOOGLEAI_FILE, + skip_in_api_mode='Create is not reproducible in the API mode.', + ), + pytest_helper.TestTableItem( + name='test_caches_create_with_googleai_file_expire_time', + exception_if_vertex='Internal', + parameters=_CREATE_CACHED_CONTENT_PARAMETERS_GOOGLEAI_FILE_EXPIRE_TIME, + skip_in_api_mode='Create is not reproducible in the API mode.', + ), + pytest_helper.TestTableItem( + name='test_caches_create_with_googleai_file_model_partial_path_1', + exception_if_vertex='Internal', + parameters=_CREATE_CACHED_CONTENT_PARAMETERS_GOOGLEAI_FILE_PARTIAL_MODEL_1, + skip_in_api_mode='Create is not reproducible in the API mode.', + ), +] +pytestmark = [ + pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='caches.create', + test_table=test_table, + ), +] +pytest_plugins = ('pytest_asyncio',) + + +@pytest.mark.asyncio +async def test_async_googleai_file_create(client): + if client._api_client.vertexai: + with pytest.raises(Exception): + await client.aio.caches.create( + model=_CREATE_CACHED_CONTENT_PARAMETERS_GOOGLEAI_FILE.model, + config=_CREATE_CACHED_CONTENT_PARAMETERS_GOOGLEAI_FILE.config, + ) + else: + await client.aio.caches.create( + model=_CREATE_CACHED_CONTENT_PARAMETERS_GOOGLEAI_FILE.model, + config=_CREATE_CACHED_CONTENT_PARAMETERS_GOOGLEAI_FILE.config, + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/caches/test_create_custom_url.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/caches/test_create_custom_url.py new file mode 100644 index 0000000000000000000000000000000000000000..27895c09c5ee6fd38373367d949414f5709ae758 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/caches/test_create_custom_url.py @@ -0,0 +1,105 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +import copy +import pytest +from ... import types +from .. import pytest_helper +from . import constants +from ... import _transformers as t + +_CREATE_CACHED_CONTENT_PARAMETERS_GCS_URI = types._CreateCachedContentParameters( + model='gemini-2.5-flash', + config={ + 'contents': [ + types.Content( + role='user', + parts=[ + types.Part( + fileData=types.FileData( + fileUri='gs://cloud-samples-data/generative-ai/pdf/2312.11805v3.pdf', + mimeType='application/pdf', + ) + ), + types.Part( + fileData=types.FileData( + fileUri='gs://cloud-samples-data/generative-ai/pdf/2403.05530.pdf', + mimeType='application/pdf', + ) + ), + ], + ) + ], + 'system_instruction': t.t_content('What is the sum of the two pdfs?'), + 'display_name': 'test cache', + 'ttl': '86400s', + 'http_options': constants.VERTEX_HTTP_OPTIONS, + }, +) + +_CREATE_CACHED_CONTENT_PARAMETERS_GOOGLEAI_FILE = types._CreateCachedContentParameters( + model='gemini-2.5-flash', + config={ + 'contents': [ + types.Content( + role='user', + parts=[ + types.Part( + fileData=types.FileData( + mimeType='application/pdf', + fileUri='https://generativelanguage.googleapis.com/v1beta/files/v200dhvn15h7', + ) + ) + ], + ) + ], + 'system_instruction': t.t_content('What is the sum of the two pdfs?'), + 'display_name': 'test cache', + 'ttl': '86400s', + 'http_options': constants.MLDEV_HTTP_OPTIONS, + }, +) + +# Replay mode is not supported for caches tests due to the error message +# inconsistency in api and replay mode. +# To run api mode tests, use the following steps: +# 1. First create the resource. +# sh run_tests.sh pytest -s tests/caches/test_create.py --mode=api +# 1.1 If mldev test_create fails, update the uploaded file using this colab +# https://colab.sandbox.google.com/drive/1Fv6KGSs0cg6tlpcUHdsclHussXMEGOXk#scrollTo=RSKmFPx00MVL. +# 2. Find the resource name in debugging print and change the resource name constants.py. +# 3. Run and record get and update tests. +# sh run_tests.sh pytest -s tests/caches/test_get.py --mode=api && sh run_tests.sh pytest -s tests/caches/test_update.py --mode=api && sh run_tests.sh pytest -s tests/caches/test_delete.py --mode=api +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_caches_create_with_gcs_uri', + exception_if_mldev='404', + parameters=_CREATE_CACHED_CONTENT_PARAMETERS_GCS_URI, + ), + pytest_helper.TestTableItem( + name='test_caches_create_with_googleai_file', + exception_if_vertex='404', + parameters=_CREATE_CACHED_CONTENT_PARAMETERS_GOOGLEAI_FILE, + skip_in_api_mode='Create is not reproducible in the API mode.', + ), +] +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='caches.create', + test_table=test_table, +) +pytest_plugins = ('pytest_asyncio',) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/caches/test_delete.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/caches/test_delete.py new file mode 100644 index 0000000000000000000000000000000000000000..fdd2642d28579ced91559d11ae2fad25899f7bdc --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/caches/test_delete.py @@ -0,0 +1,54 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +import pytest +from ... import types +from .. import pytest_helper +from . import constants + + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + skip_in_api_mode='Delete is not reproducible in the API mode.', + name='test_caches_delete_with_vertex_cache_name', + exception_if_mldev='PERMISSION_DENIED', + parameters=types._DeleteCachedContentParameters( + name=constants.CACHED_CONTENT_NAME_VERTEX, + ), + ), + pytest_helper.TestTableItem( + skip_in_api_mode='Delete is not reproducible in the API mode.', + name='test_caches_delete_with_mldev_cache_name', + exception_if_vertex='NOT_FOUND', + parameters=types._DeleteCachedContentParameters( + name=constants.CACHED_CONTENT_NAME_MLDEV, + ), + ), +] +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='caches.delete', + test_table=test_table, +) + + +@pytest.mark.asyncio +async def test_async_delete(client): + if client._api_client.vertexai: + await client.aio.caches.delete(name=constants.CACHED_CONTENT_NAME_VERTEX) + else: + await client.aio.caches.delete(name=constants.CACHED_CONTENT_NAME_MLDEV) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/caches/test_delete_custom_url.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/caches/test_delete_custom_url.py new file mode 100644 index 0000000000000000000000000000000000000000..73fb79c931080f8adf067ca4df8f78d8c5879910 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/caches/test_delete_custom_url.py @@ -0,0 +1,52 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +import pytest +from ... import types +from .. import pytest_helper +from . import constants + + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + skip_in_api_mode='Delete is not reproducible in the API mode.', + name='test_caches_delete_with_vertex_cache_name', + exception_if_mldev='404', + parameters=types._DeleteCachedContentParameters( + name=constants.CACHED_CONTENT_NAME_VERTEX, + config={ + 'http_options': constants.VERTEX_HTTP_OPTIONS, + }, + ), + ), + pytest_helper.TestTableItem( + skip_in_api_mode='Delete is not reproducible in the API mode.', + name='test_caches_delete_with_mldev_cache_name', + exception_if_vertex='404', + parameters=types._DeleteCachedContentParameters( + name=constants.CACHED_CONTENT_NAME_MLDEV, + config={ + 'http_options': constants.MLDEV_HTTP_OPTIONS, + }, + ), + ), +] +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='caches.delete', + test_table=test_table, +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/caches/test_get.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/caches/test_get.py new file mode 100644 index 0000000000000000000000000000000000000000..cef1caf04a9639e950ce17f2bcf04e7e9dd05c18 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/caches/test_get.py @@ -0,0 +1,94 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +import pytest +from ... import types +from .. import pytest_helper +from . import constants + + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + skip_in_api_mode='Get is not reproducible in the API mode.', + name='test_caches_get_with_vertex_cache_name', + exception_if_mldev='PERMISSION_DENIED', + parameters=types._GetCachedContentParameters( + name=constants.CACHED_CONTENT_NAME_VERTEX, + ), + ), + pytest_helper.TestTableItem( + skip_in_api_mode='Get is not reproducible in the API mode.', + name='test_caches_get_with_mldev_cache_name', + exception_if_vertex='NOT_FOUND', + parameters=types._GetCachedContentParameters( + name=constants.CACHED_CONTENT_NAME_MLDEV, + ), + ), + pytest_helper.TestTableItem( + skip_in_api_mode='Get is not reproducible in the API mode.', + name='test_caches_get_with_mldev_cache_name_partial_1', + exception_if_vertex='NOT_FOUND', + parameters=types._GetCachedContentParameters( + name='cachedContents/o239k1gxzz0juy9wqstndhncr85krehehf551hqh' + ), + ), +] +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='caches.get', + test_table=test_table, +) + + +@pytest.mark.asyncio +async def test_async_get(client): + if client._api_client.vertexai: + response = await client.aio.caches.get( + name=constants.CACHED_CONTENT_NAME_VERTEX + ) + assert response + else: + await client.aio.caches.get(name=constants.CACHED_CONTENT_NAME_MLDEV) + + +def test_different_cache_name_formats(client): + if client._api_client.vertexai: + response1 = client.caches.get( + name='projects/964831358985/locations/us-central1/cachedContents/2164089915711684608' + ) + assert response1 + response2 = client.caches.get( + name='locations/us-central1/cachedContents/2164089915711684608' + ) + assert response2 + response3 = client.caches.get( + name='cachedContents/2164089915711684608' + ) + assert response3 + response4 = client.caches.get( + name='2164089915711684608' + ) + assert response4 + else: + response1 = client.caches.get( + name='cachedContents/o239k1gxzz0juy9wqstndhncr85krehehf551hqh' + ) + assert response1 + response2 = client.caches.get( + name='o239k1gxzz0juy9wqstndhncr85krehehf551hqh' + ) + assert response2 diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/caches/test_get_custom_url.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/caches/test_get_custom_url.py new file mode 100644 index 0000000000000000000000000000000000000000..fa1aa4586cd981abd915d1586c0462adf166a54b --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/caches/test_get_custom_url.py @@ -0,0 +1,52 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +import pytest +from ... import types +from .. import pytest_helper +from . import constants + + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + skip_in_api_mode='Get is not reproducible in the API mode.', + name='test_caches_get_with_vertex_cache_name', + exception_if_mldev='404', + parameters=types._GetCachedContentParameters( + name=constants.CACHED_CONTENT_NAME_VERTEX, + config={ + 'http_options': constants.VERTEX_HTTP_OPTIONS, + }, + ), + ), + pytest_helper.TestTableItem( + skip_in_api_mode='Get is not reproducible in the API mode.', + name='test_caches_get_with_mldev_cache_name', + exception_if_vertex='404', + parameters=types._GetCachedContentParameters( + name=constants.CACHED_CONTENT_NAME_MLDEV, + config={ + 'http_options': constants.MLDEV_HTTP_OPTIONS, + }, + ), + ), +] +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='caches.get', + test_table=test_table, +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/caches/test_list.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/caches/test_list.py new file mode 100644 index 0000000000000000000000000000000000000000..81f390a5a3571ef9daa8186a06c645506f218698 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/caches/test_list.py @@ -0,0 +1,68 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Test caches list method.""" + +import pytest +from ... import types +from .. import pytest_helper + + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + skip_in_api_mode='List is not reproducible in the API mode.', + name='test_caches_list', + parameters=types._ListCachedContentsParameters(config={'page_size': 3}), + ), +] +pytestmark = [ + pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='caches.list', + test_table=test_table, + ) +] + + +def test_pager(client): + cached_contents = client.caches.list(config={'page_size': 2}) + assert 'content-type' in cached_contents.sdk_http_response.headers + assert cached_contents.name == 'cached_contents' + assert cached_contents.page_size == 2 + assert len(cached_contents) <= 2 + + # Iterate through all the pages. Then next_page() should raise an exception. + for _ in cached_contents: + pass + with pytest.raises(IndexError, match='No more pages to fetch.'): + cached_contents.next_page() + + +@pytest.mark.asyncio +async def test_async_pager(client): + cached_contents = await client.aio.caches.list(config={'page_size': 2}) + + assert 'Content-Type' in cached_contents.sdk_http_response.headers + assert cached_contents.name == 'cached_contents' + assert cached_contents.page_size == 2 + assert len(cached_contents) <= 2 + + # Iterate through all the pages. Then next_page() should raise an exception. + async for _ in cached_contents: + pass + with pytest.raises(IndexError, match='No more pages to fetch.'): + await cached_contents.next_page() diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/caches/test_update.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/caches/test_update.py new file mode 100644 index 0000000000000000000000000000000000000000..b40d885d7cb3d533760b1b59a2401ed11b136999 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/caches/test_update.py @@ -0,0 +1,70 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +import pytest +from ... import types +from .. import pytest_helper +from . import constants + +_VERTEX_UPDATE_PARAMETERS = types._UpdateCachedContentParameters( + name=constants.CACHED_CONTENT_NAME_VERTEX, + config={ + 'ttl': '7600s', + }, +) +_MLDEV_UPDATE_PARAMETERS = types._UpdateCachedContentParameters( + name=constants.CACHED_CONTENT_NAME_MLDEV, + config={ + 'ttl': '7600s', + }, +) + + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + skip_in_api_mode='Update has permission issues in the API mode.', + name='test_caches_update_with_vertex_cache_name', + exception_if_mldev='PERMISSION_DENIED', + parameters=_VERTEX_UPDATE_PARAMETERS, + ), + pytest_helper.TestTableItem( + skip_in_api_mode='Update has permission issues in the API mode.', + name='test_caches_update_with_mldev_cache_name', + exception_if_vertex='NOT_FOUND', + parameters=_MLDEV_UPDATE_PARAMETERS, + ), +] +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='caches.update', + test_table=test_table, +) + + +@pytest.mark.asyncio +async def test_async_update(client): + if client._api_client.vertexai: + response = await client.aio.caches.update( + name=_VERTEX_UPDATE_PARAMETERS.name, + config=_VERTEX_UPDATE_PARAMETERS.config, + ) + assert response + else: + await client.aio.caches.update( + name=_MLDEV_UPDATE_PARAMETERS.name, + config=_MLDEV_UPDATE_PARAMETERS.config, + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/caches/test_update_custom_url.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/caches/test_update_custom_url.py new file mode 100644 index 0000000000000000000000000000000000000000..d00ac76d32de69f7808bb02eb8a67b938553397e --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/caches/test_update_custom_url.py @@ -0,0 +1,58 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +import pytest +from ... import types +from .. import pytest_helper +from . import constants + +_VERTEX_UPDATE_PARAMETERS = types._UpdateCachedContentParameters( + name=constants.CACHED_CONTENT_NAME_VERTEX, + config={ + 'ttl': '7600s', + 'http_options': constants.VERTEX_HTTP_OPTIONS, + }, +) +_MLDEV_UPDATE_PARAMETERS = types._UpdateCachedContentParameters( + name=constants.CACHED_CONTENT_NAME_MLDEV, + config={ + 'ttl': '7600s', + 'http_options': constants.MLDEV_HTTP_OPTIONS, + }, +) + + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + skip_in_api_mode='Update has permission issues in the API mode.', + name='test_caches_update_with_vertex_cache_name', + exception_if_mldev='404', + parameters=_VERTEX_UPDATE_PARAMETERS, + ), + pytest_helper.TestTableItem( + skip_in_api_mode='Update has permission issues in the API mode.', + name='test_caches_update_with_mldev_cache_name', + exception_if_vertex='404', + parameters=_MLDEV_UPDATE_PARAMETERS, + ), +] +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='caches.update', + test_table=test_table, +) + diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/chats/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/chats/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..029f04fa44699c6f3f05fb10524fceb373fb235f --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/chats/__init__.py @@ -0,0 +1 @@ +"""Tests for the Google GenAI SDK's chats module.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/chats/test_get_history.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/chats/test_get_history.py new file mode 100644 index 0000000000000000000000000000000000000000..e29862a775dfb70441f4209cc2c891a7bec8be84 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/chats/test_get_history.py @@ -0,0 +1,598 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +from unittest import mock + +import pytest + +from ... import chats +from ... import client +from ... import models +from ... import types + +AFC_HISTORY = [ + types.Content( + role='user', + parts=[types.Part.from_text(text='afc input')], + ), + types.Content( + role='model', + parts=[ + types.Part( + function_call=types.FunctionCall( + name='foo', args={'bar': 'baz'} + ) + ) + ], + ), +] + + +pytest_plugins = 'pytest_asyncio' + + +@pytest.fixture +def mock_api_client(vertexai=False): + api_client = mock.MagicMock(spec=client.ApiClient) + api_client.api_key = 'TEST_API_KEY' + api_client._host = lambda: 'test_host' + api_client._http_options = {'headers': {}} # Ensure headers exist + api_client.vertexai = vertexai + return api_client + + +@pytest.fixture +def mock_generate_content_with_empty_text_part(): + with mock.patch.object( + models.Models, 'generate_content' + ) as mock_generate_content: + mock_generate_content.return_value = types.GenerateContentResponse( + candidates=[ + types.Candidate( + content=types.Content( + role='model', + parts=[types.Part(text='')], + ) + ) + ] + ) + yield mock_generate_content + + +@pytest.fixture +def mock_generate_content_empty_content(): + with mock.patch.object( + models.Models, 'generate_content' + ) as mock_generate_content: + mock_generate_content.return_value = types.GenerateContentResponse( + candidates=[] + ) + yield mock_generate_content + + +@pytest.fixture +def mock_generate_content_stream_with_empty_text_part(): + with mock.patch.object( + models.Models, 'generate_content_stream' + ) as mock_generate_content: + mock_generate_content.return_value = [ + types.GenerateContentResponse( + candidates=[ + types.Candidate( + content=types.Content( + role='model', + parts=[types.Part(text='')], + ), + finish_reason=types.FinishReason.STOP, + ) + ] + ) + ] + yield mock_generate_content + + +@pytest.fixture +def mock_generate_content_stream_empty_content(): + with mock.patch.object( + models.Models, 'generate_content_stream' + ) as mock_generate_content: + mock_generate_content.return_value = [ + types.GenerateContentResponse(candidates=[]) + ] + yield mock_generate_content + + +@pytest.fixture +def mock_generate_content_afc_history(): + with mock.patch.object( + models.Models, 'generate_content' + ) as mock_generate_content: + mock_generate_content.return_value = types.GenerateContentResponse( + candidates=[ + types.Candidate( + content=types.Content( + role='model', + parts=[types.Part.from_text(text='afc output')], + ) + ) + ], + automatic_function_calling_history=AFC_HISTORY, + ) + yield mock_generate_content + + +@pytest.fixture +def mock_generate_content_stream_afc_history(): + with mock.patch.object( + models.Models, 'generate_content_stream' + ) as mock_generate_content: + mock_generate_content.return_value = [ + types.GenerateContentResponse( + candidates=[ + types.Candidate( + content=types.Content( + role='model', + parts=[types.Part.from_text(text='afc output')], + ), + finish_reason=types.FinishReason.STOP, + ) + ], + automatic_function_calling_history=AFC_HISTORY, + ) + ] + yield mock_generate_content + + +def test_history_start_with_valid_model_content(): + history = [ + types.Content( + role='model', + parts=[types.Part.from_text(text='Hello there! how can I help you?')], + ), + types.Content(role='user', parts=[types.Part.from_text(text='Hello')]), + ] + + models_module = models.Models(mock_api_client) + chats_module = chats.Chats(modules=models_module) + chat = chats_module.create(model='gemini-2.5-flash', history=history) + + assert chat.get_history() == history + assert chat.get_history(curated=True) == history + + +def test_history_start_with_invalid_model_content(): + history = [ + types.Content( + role='model', + parts=[], + ), + types.Content(role='user', parts=[types.Part.from_text(text='Hello')]), + ] + + models_module = models.Models(mock_api_client) + chats_module = chats.Chats(modules=models_module) + chat = chats_module.create(model='gemini-2.5-flash', history=history) + + assert chat.get_history() == history + assert chat.get_history(curated=True) == [types.Content(role='user', parts=[types.Part.from_text(text='Hello')])] + + +def test_history_with_consecutive_valid_user_inputs(): + history = [ + types.Content( + role='user', + parts=[types.Part.from_text(text='user input 1')], + ), + types.Content( + role='user', + parts=[types.Part.from_text(text='user input 2')], + ), + ] + + models_module = models.Models(mock_api_client) + chats_module = chats.Chats(modules=models_module) + chat = chats_module.create(model='gemini-2.5-flash', history=history) + + assert chat.get_history() == history + assert chat.get_history(curated=True) == history + + +def test_history_with_valid_and_invalid_user_inputs(): + history = [ + types.Content( + role='user', + parts=[types.Part.from_text(text='user input 1')], + ), + types.Content( + role='user', + parts=[], # invalid content + ), + types.Content( + role='user', + parts=[types.Part.from_text(text='user input 2')], + ), + ] + + models_module = models.Models(mock_api_client) + chats_module = chats.Chats(modules=models_module) + chat = chats_module.create(model='gemini-2.5-flash', history=history) + + assert chat.get_history() == history + assert chat.get_history(curated=True) == history + + +def test_history_with_consecutive_valid_model_outputs(): + history = [ + types.Content( + role='model', + parts=[types.Part.from_text(text='model output 1')], + ), + types.Content( + role='model', + parts=[types.Part.from_text(text='model output 2')], + ), + ] + + models_module = models.Models(mock_api_client) + chats_module = chats.Chats(modules=models_module) + chat = chats_module.create(model='gemini-2.5-flash', history=history) + + assert chat.get_history() == history + assert chat.get_history(curated=True) == history + + +def test_history_with_valid_and_invalid_model_output(): + history = [ + types.Content( + role='model', + parts=[types.Part.from_text(text='model output 1')], + ), + types.Content( + role='model', + parts=[], # invalid content + ), + types.Content( + role='model', + parts=[types.Part.from_text(text='model output 2')], + ), + ] + + models_module = models.Models(mock_api_client) + chats_module = chats.Chats(modules=models_module) + chat = chats_module.create(model='gemini-2.5-flash', history=history) + + assert chat.get_history() == history + assert chat.get_history(curated=True) == [] + + +def test_history_end_with_user_input(): + history = [ + types.Content( + role='user', + parts=[types.Part.from_text(text='user input 1')], + ), + types.Content( + role='model', + parts=[types.Part.from_text(text='model output')], + ), + types.Content( + role='user', + parts=[types.Part.from_text(text='user input 2')], + ), + ] + + models_module = models.Models(mock_api_client) + chats_module = chats.Chats(modules=models_module) + chat = chats_module.create(model='gemini-2.5-flash', history=history) + + assert chat.get_history() == history + assert chat.get_history(curated=True) == history + + +def test_unrecognized_role_in_history(): + history = [ + types.Content(role='user', parts=[types.Part.from_text(text='Hello')]), + types.Content( + role='invalid_role', + parts=[types.Part.from_text(text='Hello there! how can I help you?')], + ), + ] + + models_module = models.Models(mock_api_client) + chats_module = chats.Chats(modules=models_module) + with pytest.raises(ValueError) as e: + chat = chats_module.create(model='gemini-2.5-flash', history=history) + + assert 'Role must be user or model' in str(e) + + +def test_sync_chat_create(): + history = [ + types.Content( + role='user', parts=[types.Part.from_text(text='user input turn 1')] + ), + types.Content( + role='model', + parts=[types.Part.from_text(text='model output turn 1')], + ), + types.Content( + role='model', + parts=[types.Part.from_text(text='model output turn 1')], + ), + types.Content( + role='model', + parts=[types.Part.from_text(text='user input turn 2')], + ), + ] + + models_module = models.Models(mock_api_client) + chats_module = chats.Chats(modules=models_module) + chat = chats_module.create(model='gemini-2.5-flash', history=history) + + assert chat.get_history() == history + assert chat.get_history(curated=True) == history + + +def test_async_chat_create(): + history = [ + types.Content( + role='user', parts=[types.Part.from_text(text='user input turn 1')] + ), + types.Content( + role='model', + parts=[types.Part.from_text(text='model output turn 1')], + ), + types.Content( + role='model', + parts=[types.Part.from_text(text='model output turn 1')], + ), + types.Content( + role='model', + parts=[types.Part.from_text(text='user input turn 2')], + ), + types.Content( + role='model', + parts=[types.Part.from_text(text='model output turn 2')], + ), + ] + + models_module = models.AsyncModels(mock_api_client) + chats_module = chats.AsyncChats(modules=models_module) + chat = chats_module.create(model='gemini-2.5-flash', history=history) + + assert chat.get_history() == history + assert chat.get_history(curated=True) == history + + +def test_sync_chat_create_with_history_dict(): + history = [ + {'role': 'user', 'parts': [{'text': 'user input turn 1'}]}, + {'role': 'model', 'parts': [{'text': 'model output turn 1'}]}, + {'role': 'user', 'parts': [{'text': 'user input turn 2'}]}, + {'role': 'model', 'parts': [{'text': 'model output turn 2'}]}, + ] + models_module = models.Models(mock_api_client) + chats_module = chats.Chats(modules=models_module) + chat = chats_module.create(model='gemini-2.5-flash', history=history) + + expected_history = [ + types.Content( + role='user', parts=[types.Part.from_text(text='user input turn 1')] + ), + types.Content( + role='model', + parts=[types.Part.from_text(text='model output turn 1')], + ), + types.Content( + role='user', parts=[types.Part.from_text(text='user input turn 2')] + ), + types.Content( + role='model', + parts=[types.Part.from_text(text='model output turn 2')], + ), + ] + assert chat.get_history() == expected_history + assert chat.get_history(curated=True) == expected_history + + +def test_async_chat_create_with_history_dict(): + history = [ + {'role': 'user', 'parts': [{'text': 'user input turn 1'}]}, + {'role': 'model', 'parts': [{'text': 'model output turn 1'}]}, + {'role': 'user', 'parts': [{'text': 'user input turn 2'}]}, + {'role': 'model', 'parts': [{'text': 'model output turn 2'}]}, + ] + models_module = models.AsyncModels(mock_api_client) + chats_module = chats.AsyncChats(modules=models_module) + chat = chats_module.create(model='gemini-2.5-flash', history=history) + + expected_history = [ + types.Content( + role='user', parts=[types.Part.from_text(text='user input turn 1')] + ), + types.Content( + role='model', + parts=[types.Part.from_text(text='model output turn 1')], + ), + types.Content( + role='user', parts=[types.Part.from_text(text='user input turn 2')] + ), + types.Content( + role='model', + parts=[types.Part.from_text(text='model output turn 2')], + ), + ] + assert chat.get_history() == expected_history + assert chat.get_history(curated=True) == expected_history + + +def test_history_with_invalid_turns(): + valid_input = types.Content( + role='user', parts=[types.Part.from_text(text='Hello')] + ) + valid_output = [ + types.Content( + role='model', + parts=[types.Part.from_text(text='Hello there! how can I help you?')], + ), + types.Content( + role='model', + parts=[types.Part.from_text(text='Hello there! how can I help you?')], + ), + ] + invalid_input = types.Content( + role='user', + parts=[ + types.Part.from_text(text='a input will be rejected by the model') + ], + ) + invalid_output = types.Content( + role='model', + parts=[], + ) + comprehensive_history = [] + comprehensive_history.append(valid_input) + comprehensive_history.extend(valid_output) + comprehensive_history.append(invalid_input) + comprehensive_history.append(invalid_output) + curated_history = [] + curated_history.append(valid_input) + curated_history.extend(valid_output) + + models_module = models.Models(mock_api_client) + chats_module = chats.Chats(modules=models_module) + chat = chats_module.create( + model='gemini-2.5-flash', history=comprehensive_history + ) + + assert chat.get_history() == comprehensive_history + assert chat.get_history(curated=True) == curated_history + + +def test_chat_with_empty_text_part(mock_generate_content_with_empty_text_part): + models_module = models.Models(mock_api_client) + chats_module = chats.Chats(modules=models_module) + chat = chats_module.create(model='gemini-2.5-flash') + + chat.send_message('Hello') + + expected_comprehensive_history = [ + types.UserContent(parts=[types.Part.from_text(text='Hello')]), + types.Content( + parts=[types.Part(text='')], + role='model', + ), + ] + assert chat.get_history() == expected_comprehensive_history + assert chat.get_history(curated=True) == expected_comprehensive_history + + +def test_chat_with_empty_content(mock_generate_content_empty_content): + models_module = models.Models(mock_api_client) + chats_module = chats.Chats(modules=models_module) + chat = chats_module.create(model='gemini-2.5-flash') + + chat.send_message('Hello') + + expected_comprehensive_history = [ + types.UserContent(parts=[types.Part.from_text(text='Hello')]), + types.Content( + parts=[], + role='model', + ), + ] + assert chat.get_history() == expected_comprehensive_history + assert not chat.get_history(curated=True) + + +def test_chat_stream_with_empty_text_part( + mock_generate_content_stream_with_empty_text_part, +): + models_module = models.Models(mock_api_client) + chats_module = chats.Chats(modules=models_module) + chat = chats_module.create(model='gemini-2.5-flash') + + chunks = chat.send_message_stream('Hello') + for chunk in chunks: + pass + + expected_comprehensive_history = [ + types.UserContent(parts=[types.Part.from_text(text='Hello')]), + types.Content( + parts=[types.Part(text='')], + role='model', + ), + ] + assert chat.get_history() == expected_comprehensive_history + assert chat.get_history(curated=True) == expected_comprehensive_history + + +def test_chat_stream_with_empty_content( + mock_generate_content_stream_empty_content, +): + models_module = models.Models(mock_api_client) + chats_module = chats.Chats(modules=models_module) + chat = chats_module.create(model='gemini-2.5-flash') + + chunks = chat.send_message_stream('Hello') + for chunk in chunks: + pass + + expected_comprehensive_history = [ + types.UserContent(parts=[types.Part.from_text(text='Hello')]), + types.Content( + parts=[], + role='model', + ), + ] + assert chat.get_history() == expected_comprehensive_history + assert not chat.get_history(curated=True) + + +def test_chat_with_afc_history(mock_generate_content_afc_history): + models_module = models.Models(mock_api_client) + chats_module = chats.Chats(modules=models_module) + chat = chats_module.create(model='gemini-2.5-flash') + + chat.send_message('Hello') + + expected_history = AFC_HISTORY + [ + types.Content( + role='model', + parts=[types.Part.from_text(text='afc output')], + ), + ] + assert chat.get_history() == expected_history + assert chat.get_history(curated=True) == expected_history + + +def test_chat_stream_with_afc_history(mock_generate_content_stream_afc_history): + models_module = models.Models(mock_api_client) + chats_module = chats.Chats(modules=models_module) + chat = chats_module.create(model='gemini-2.5-flash') + + chunks = chat.send_message_stream('Hello') + for chunk in chunks: + pass + + expected_history = AFC_HISTORY + [ + types.Content( + role='model', + parts=[types.Part.from_text(text='afc output')], + ), + ] + assert chat.get_history() == expected_history + assert chat.get_history(curated=True) == expected_history diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/chats/test_send_message.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/chats/test_send_message.py new file mode 100644 index 0000000000000000000000000000000000000000..cee6bfe3cd848a24595c3994631cbc9fffd1c2c8 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/chats/test_send_message.py @@ -0,0 +1,941 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +import json +import os +import sys + +from pydantic import BaseModel +from pydantic import ValidationError +import pytest + +from .. import pytest_helper +from ... import errors +from ... import types + +try: + from mcp import types as mcp_types + from mcp import ClientSession as McpClientSession +except ImportError as e: + import sys + + if sys.version_info < (3, 10): + raise ImportError( + 'MCP Tool requires Python 3.10 or above. Please upgrade your Python' + ' version.' + ) from e + else: + raise e + + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), +) +pytest_plugins = ('pytest_asyncio',) + + +MODEL_NAME = 'gemini-2.5-flash' + +def divide_intergers_with_customized_math_rule( + numerator: int, denominator: int +) -> int: + """Divides two integers with customized math rule.""" + return numerator // denominator + 1 + + +def square_integer(given_integer: int) -> int: + return given_integer*given_integer + + +def power_disco_ball(power: bool) -> bool: + """Powers the spinning disco ball.""" + print(f"Disco ball is {'spinning!' if power else 'stopped.'}") + return True + +def start_music(energetic: bool, loud: bool, bpm: int) -> str: + """Play some music matching the specified parameters. + + Args: + energetic: Whether the music is energetic or not. + loud: Whether the music is loud or not. + bpm: The beats per minute of the music. + + Returns: The name of the song being played. + """ + print(f"Starting music! {energetic=} {loud=}, {bpm=}") + return "Never gonna give you up." + +def dim_lights(brightness: float) -> bool: + """Dim the lights. + + Args: + brightness: The brightness of the lights, 0.0 is off, 1.0 is full. + """ + print(f"Lights are now set to {brightness:.0%}") + return True + +def test_text(client): + chat = client.chats.create(model=MODEL_NAME) + chat.send_message( + 'tell me a story in 100 words', + ) + + +def test_part(client): + chat = client.chats.create(model=MODEL_NAME) + chat.send_message( + types.Part.from_text(text='tell me a story in 100 words'), + ) + + +def test_parts(client): + chat = client.chats.create(model=MODEL_NAME) + chat.send_message( + [ + types.Part.from_text(text='tell me a US city'), + types.Part.from_text(text='the city is in west coast'), + ], + ) + + +def test_image(client, image_jpeg): + chat = client.chats.create(model=MODEL_NAME) + chat.send_message( + [ + 'what is the image about?', + image_jpeg, + ], + ) + + +def test_thinking_budget(client): + """Tests that the thinking budget is respected and generates thoughts.""" + chat = client.chats.create( + model=MODEL_NAME, + config={ + 'thinking_config': { + 'include_thoughts': True, + 'thinking_budget': 10000, + }, + }, + ) + response1 = chat.send_message( + 'what is the sum of natural numbers from 1 to 100?', + ) + has_thought1 = False + if response1.candidates: + for candidate in response1.candidates: + for part in candidate.content.parts: + if part.thought: + has_thought1 = True + break + assert has_thought1 + + response2 = chat.send_message( + 'can you help me to understand the logic better?' + ) + has_thought2 = False + if response2.candidates: + for candidate in response2.candidates: + for part in candidate.content.parts: + if part.thought: + has_thought2 = True + break + assert has_thought2 + + +def test_thinking_budget_stream(client): + """Tests that the thinking budget is respected and generates thoughts.""" + chat = client.chats.create( + model=MODEL_NAME, + config={ + 'thinking_config': { + 'include_thoughts': True, + 'thinking_budget': 10000, + }, + }, + ) + has_thought1 = False + for chunk in chat.send_message_stream( + 'what is the sum of natural numbers from 1 to 100?', + ): + if chunk.candidates: + for candidate in chunk.candidates: + for part in candidate.content.parts: + if part.thought: + has_thought1 = True + break + assert has_thought1 + + has_thought2 = False + for chunk in chat.send_message_stream( + 'can you help me to understand the logic better?' + ): + if chunk.candidates: + for candidate in chunk.candidates: + for part in candidate.content.parts: + if part.thought: + has_thought2 = True + break + assert has_thought2 + + +def test_google_cloud_storage_uri(client): + chat = client.chats.create(model=MODEL_NAME) + with pytest_helper.exception_if_mldev(client, errors.ClientError): + chat.send_message( + [ + 'what is the image about?', + types.Part.from_uri( + file_uri='gs://unified-genai-dev/imagen-inputs/google_small.png', + mime_type='image/png', + ), + ], + ) + + +def test_uploaded_file_uri(client): + chat = client.chats.create(model=MODEL_NAME) + with pytest_helper.exception_if_vertex(client, errors.ClientError): + chat.send_message( + [ + 'what is the image about?', + types.Part.from_uri( + file_uri='https://generativelanguage.googleapis.com/v1beta/files/az606f58k7zj', + mime_type='image/png', + ), + ], + ) + + +def test_config_override(client): + chat_config = {'candidate_count': 1} + chat = client.chats.create(model=MODEL_NAME, config=chat_config) + request_config = {'candidate_count': 2} + request_config_response = chat.send_message( + 'tell me a story in 100 words', + config=request_config) + default_config_response = chat.send_message( + 'tell me a story in 100 words') + + assert len(request_config_response.candidates) == 2 + assert len(default_config_response.candidates) == 1 + + +def test_history(client): + history = [ + types.Content( + role='user', parts=[types.Part.from_text(text='define a=5, b=10')] + ), + types.Content( + role='model', + parts=[types.Part.from_text(text='Hello there! how can I help you?')], + ), + ] + chat = client.chats.create(model=MODEL_NAME, history=history) + chat.send_message('what is a + b?') + + assert len(chat.get_history()) > 2 + + +def test_send_2_messages(client): + chat = client.chats.create(model=MODEL_NAME) + chat.send_message('write a python function to check if a year is a leap year') + chat.send_message('write a unit test for the function') + + +def test_with_afc_history(client): + chat = client.chats.create( + model='gemini-2.0-flash-exp', + config={'tools': [divide_intergers_with_customized_math_rule]}, + ) + _ = chat.send_message('what is the result of 100/2?') + chat_history = chat.get_history() + + assert len(chat_history) == 4 + assert chat_history[0].role == 'user' + assert chat_history[0].parts[0].text == 'what is the result of 100/2?' + + assert chat_history[1].role == 'model' + assert ( + chat_history[1].parts[0].function_call.name + == 'divide_intergers_with_customized_math_rule' + ) + assert chat_history[1].parts[0].function_call.args == { + 'numerator': 100, + 'denominator': 2, + } + + assert chat_history[2].role == 'user' + assert ( + chat_history[2].parts[0].function_response.name + == 'divide_intergers_with_customized_math_rule' + ) + assert chat_history[2].parts[0].function_response.response == {'result': 51} + + assert chat_history[3].role == 'model' + assert '51' in chat_history[3].parts[0].text + + +def test_existing_chat_history_extends_afc_history(client): + chat = client.chats.create( + model='gemini-2.0-flash-exp', + config={'tools': [divide_intergers_with_customized_math_rule]}, + ) + _ = chat.send_message('hello') + _ = chat.send_message('could you help me with a math problem?') + _ = chat.send_message('what is the result of 100/2?') + chat_history = chat.get_history() + content_strings = [] + for content in chat_history: + content_strings.append(content.model_dump_json()) + + # checks that the history is not duplicated + assert len(content_strings) == len(set(content_strings)) + + +@pytest.mark.skipif( + sys.version_info >= (3, 13), + reason=( + 'object type is dumped as as opposed to' + ' "OBJECT" in Python 3.13' + ), +) +def test_with_afc_multiple_remote_calls(client): + + house_fns = [power_disco_ball, start_music, dim_lights] + config = { + 'tools': house_fns, + # Force the model to act (call 'any' function), instead of chatting. + 'tool_config': { + 'function_calling_config': { + 'mode': 'ANY', + } + }, + 'automatic_function_calling': { + 'maximum_remote_calls': 3, + } + } + chat = client.chats.create(model=MODEL_NAME, config=config) + chat.send_message('Turn this place into a party!') + curated_history = chat.get_history() + + assert len(curated_history) == 8 + assert curated_history[0].role == 'user' + assert curated_history[0].parts[0].text == 'Turn this place into a party!' + assert curated_history[1].role == 'model' + assert len(curated_history[1].parts) == 3 + for part in curated_history[1].parts: + assert part.function_call + assert curated_history[2].role == 'user' + assert len(curated_history[2].parts) == 3 + for part in curated_history[2].parts: + assert part.function_response + assert curated_history[3].role == 'model' + assert len(curated_history[3].parts) == 3 + for part in curated_history[3].parts: + assert part.function_call + assert curated_history[4].role == 'user' + assert len(curated_history[4].parts) == 3 + for part in curated_history[4].parts: + assert part.function_response + assert curated_history[5].role == 'model' + assert len(curated_history[5].parts) == 3 + for part in curated_history[5].parts: + assert part.function_call + assert curated_history[6].role == 'user' + assert len(curated_history[6].parts) == 3 + for part in curated_history[6].parts: + assert part.function_response + assert curated_history[7].role == 'model' + assert len(curated_history[7].parts) == 3 + for part in curated_history[7].parts: + assert part.function_call + + +@pytest.mark.skipif( + sys.version_info >= (3, 13), + reason=( + 'object type is dumped as as opposed to' + ' "OBJECT" in Python 3.13' + ), +) +def test_with_afc_multiple_remote_calls_async(client): + + house_fns = [power_disco_ball, start_music, dim_lights] + config = { + 'tools': house_fns, + # Force the model to act (call 'any' function), instead of chatting. + 'tool_config': { + 'function_calling_config': { + 'mode': 'ANY', + } + }, + 'automatic_function_calling': { + 'maximum_remote_calls': 3, + } + } + chat = client.chats.create(model=MODEL_NAME, config=config) + chat.send_message('Turn this place into a party!') + curated_history = chat.get_history() + + assert len(curated_history) == 8 + assert curated_history[0].role == 'user' + assert curated_history[0].parts[0].text == 'Turn this place into a party!' + assert curated_history[1].role == 'model' + assert len(curated_history[1].parts) == 3 + for part in curated_history[1].parts: + assert part.function_call + assert curated_history[2].role == 'user' + assert len(curated_history[2].parts) == 3 + for part in curated_history[2].parts: + assert part.function_response + assert curated_history[3].role == 'model' + assert len(curated_history[3].parts) == 3 + for part in curated_history[3].parts: + assert part.function_call + assert curated_history[4].role == 'user' + assert len(curated_history[4].parts) == 3 + for part in curated_history[4].parts: + assert part.function_response + assert curated_history[5].role == 'model' + assert len(curated_history[5].parts) == 3 + for part in curated_history[5].parts: + assert part.function_call + assert curated_history[6].role == 'user' + assert len(curated_history[6].parts) == 3 + for part in curated_history[6].parts: + assert part.function_response + assert curated_history[7].role == 'model' + assert len(curated_history[7].parts) == 3 + for part in curated_history[7].parts: + assert part.function_call + +def test_with_afc_disabled(client): + chat = client.chats.create( + model='gemini-2.0-flash-exp', + config={ + 'tools': [square_integer], + 'automatic_function_calling': {'disable': True}, + }, + ) + chat.send_message( + 'Do the square of 3.', + ) + chat_history = chat.get_history() + + assert len(chat_history) == 2 + assert chat_history[0].role == 'user' + assert chat_history[0].parts[0].text == 'Do the square of 3.' + + assert chat_history[1].role == 'model' + assert chat_history[1].parts[0].function_call.name == 'square_integer' + assert chat_history[1].parts[0].function_call.args == { + 'given_integer': 3, + } + + +@pytest.mark.asyncio +async def test_with_afc_history_async(client): + chat = client.aio.chats.create( + model='gemini-2.0-flash-exp', + config={'tools': [divide_intergers_with_customized_math_rule]}, + ) + _ = await chat.send_message('what is the result of 100/2?') + chat_history = chat.get_history() + + assert len(chat_history) == 4 + assert chat_history[0].role == 'user' + assert chat_history[0].parts[0].text == 'what is the result of 100/2?' + + assert chat_history[1].role == 'model' + assert ( + chat_history[1].parts[0].function_call.name + == 'divide_intergers_with_customized_math_rule' + ) + assert chat_history[1].parts[0].function_call.args == { + 'numerator': 100, + 'denominator': 2, + } + + assert chat_history[2].role == 'user' + assert ( + chat_history[2].parts[0].function_response.name + == 'divide_intergers_with_customized_math_rule' + ) + assert chat_history[2].parts[0].function_response.response == {'result': 51} + + assert chat_history[3].role == 'model' + assert '51' in chat_history[3].parts[0].text + + +@pytest.mark.asyncio +async def test_with_afc_disabled_async(client): + chat = client.aio.chats.create( + model='gemini-2.0-flash-exp', + config={ + 'tools': [square_integer], + 'automatic_function_calling': {'disable': True}, + }, + ) + await chat.send_message( + 'Do the square of 3.', + ) + chat_history = chat.get_history() + + assert len(chat_history) == 2 + assert chat_history[0].role == 'user' + assert chat_history[0].parts[0].text == 'Do the square of 3.' + + assert chat_history[1].role == 'model' + assert chat_history[1].parts[0].function_call.name == 'square_integer' + assert chat_history[1].parts[0].function_call.args == { + 'given_integer': 3, + } + + +def test_stream_text(client): + chat = client.chats.create(model=MODEL_NAME) + chunks = 0 + for chunk in chat.send_message_stream( + 'tell me a story in 100 words', + ): + chunks += 1 + + assert chunks > 1 + + +def test_stream_part(client): + chat = client.chats.create(model=MODEL_NAME) + chunks = 0 + for chunk in chat.send_message_stream( + types.Part.from_text(text='tell me a story in 100 words'), + ): + chunks += 1 + + assert chunks > 1 + + +def test_stream_parts(client): + chat = client.chats.create(model=MODEL_NAME) + chunks = 0 + for chunk in chat.send_message_stream( + [ + types.Part.from_text(text='tell me a story in 100 words'), + types.Part.from_text(text='the story is about a car'), + ], + ): + chunks += 1 + + assert chunks > 2 + + +def test_stream_config_override(client): + chat_config = {'response_mime_type': 'text/plain'} + chat = client.chats.create(model=MODEL_NAME, config=chat_config) + request_config = {'response_mime_type': 'application/json'} + request_config_text = '' + for chunk in chat.send_message_stream( + 'tell me a story in 100 words', config=request_config + ): + request_config_text += chunk.text + default_config_text = '' + for chunk in chat.send_message_stream('tell me a story in 100 words'): + default_config_text += chunk.text + + assert json.loads(request_config_text) + with pytest.raises(json.JSONDecodeError): + json.loads(default_config_text) + + +def test_stream_function_calling(client): + chat = client.chats.create( + model='gemini-2.0-flash-exp', + config={'tools': [divide_intergers_with_customized_math_rule]}, + ) + # Now we support AFC. + for chunk in chat.send_message_stream( + 'what is the result of 100/2?', + ): + pass + for chunk in chat.send_message_stream( + 'what is the result of 50/2?', + ): + pass + chat_history = chat.get_history() + + assert chat_history[0].role == 'user' + assert chat_history[0].parts[0].text == 'what is the result of 100/2?' + + assert chat_history[1].role == 'model' + assert ( + chat_history[1].parts[0].function_call.name + == 'divide_intergers_with_customized_math_rule' + ) + assert chat_history[1].parts[0].function_call.args == { + 'numerator': 100, + 'denominator': 2, + } + + +def test_stream_send_2_messages(client): + chat = client.chats.create(model=MODEL_NAME) + for chunk in chat.send_message_stream( + 'write a python function to check if a year is a leap year' + ): + pass + + for chunk in chat.send_message_stream('write a unit test for the function'): + pass + + +@pytest.mark.asyncio +async def test_async_text(client): + chat = client.aio.chats.create(model=MODEL_NAME) + await chat.send_message('tell me a story in 100 words') + + +@pytest.mark.asyncio +async def test_async_part(client): + chat = client.aio.chats.create(model=MODEL_NAME) + await chat.send_message(types.Part.from_text(text='tell me a story in 100 words')) + + +@pytest.mark.asyncio +async def test_async_parts(client): + chat = client.aio.chats.create(model=MODEL_NAME) + await chat.send_message( + [ + types.Part.from_text(text='tell me a US city'), + types.Part.from_text(text='the city is in west coast'), + ], + ) + + +@pytest.mark.asyncio +async def test_async_config_override(client): + chat_config = {'candidate_count': 1} + chat = client.aio.chats.create(model=MODEL_NAME, config=chat_config) + request_config = {'candidate_count': 2} + request_config_response = await chat.send_message( + 'tell me a story in 100 words', + config=request_config) + default_config_response = await chat.send_message( + 'tell me a story in 100 words') + + assert len(request_config_response.candidates) == 2 + assert len(default_config_response.candidates) == 1 + + +@pytest.mark.asyncio +async def test_async_history(client): + history = [ + types.Content( + role='user', parts=[types.Part.from_text(text='define a=5, b=10')] + ), + types.Content( + role='model', + parts=[types.Part.from_text(text='Hello there! how can I help you?')], + ), + ] + chat = client.aio.chats.create(model=MODEL_NAME, history=history) + await chat.send_message('what is a + b?') + + assert len(chat.get_history()) > 2 + + +@pytest.mark.asyncio +async def test_async_stream_text(client): + chat = client.aio.chats.create(model=MODEL_NAME) + chunks = 0 + async for chunk in await chat.send_message_stream('tell me a story in 100 words'): + chunks += 1 + + assert chunks > 1 + + +@pytest.mark.asyncio +async def test_async_stream_part(client): + chat = client.aio.chats.create(model=MODEL_NAME) + chunks = 0 + async for chunk in await chat.send_message_stream( + types.Part.from_text(text='tell me a story in 100 words') + ): + chunks += 1 + + assert chunks > 1 + + +@pytest.mark.asyncio +async def test_async_stream_parts(client): + chat = client.aio.chats.create(model=MODEL_NAME) + chunks = 0 + async for chunk in await chat.send_message_stream( + [ + types.Part.from_text(text='tell me a story in 100 words'), + types.Part.from_text(text='the story is about a car'), + ], + ): + chunks += 1 + + assert chunks > 1 + + +@pytest.mark.asyncio +async def test_async_stream_config_override(client): + chat_config = {'response_mime_type': 'text/plain'} + chat = client.aio.chats.create(model=MODEL_NAME, config=chat_config) + request_config = {'response_mime_type': 'application/json'} + request_config_text = '' + async for chunk in await chat.send_message_stream( + 'tell me a story in 100 words', config=request_config + ): + request_config_text += chunk.text + default_config_text = '' + + async for chunk in await chat.send_message_stream('tell me family friendly story in 100 words'): + default_config_text += chunk.text + + assert json.loads(request_config_text) + with pytest_helper.exception_if_mldev(client, json.JSONDecodeError): + json.loads(default_config_text) + + +@pytest.mark.asyncio +async def test_async_stream_function_calling(client): + chat = client.aio.chats.create( + model='gemini-2.0-flash-exp', + config={'tools': [divide_intergers_with_customized_math_rule]}, + ) + # Now we support AFC. + async for chunk in await chat.send_message_stream('what is the result of 100/2?'): + pass + async for chunk in await chat.send_message_stream('what is the result of 50/2?'): + pass + chat_history = chat.get_history() + + assert chat_history[0].role == 'user' + assert chat_history[0].parts[0].text == 'what is the result of 100/2?' + + assert chat_history[1].role == 'model' + assert ( + chat_history[1].parts[0].function_call.name + == 'divide_intergers_with_customized_math_rule' + ) + assert chat_history[1].parts[0].function_call.args == { + 'numerator': 100, + 'denominator': 2, + } + + +@pytest.mark.asyncio +async def test_async_stream_send_2_messages(client): + chat = client.aio.chats.create(model=MODEL_NAME) + async for chunk in await chat.send_message_stream( + 'write a python function to check if a year is a leap year' + ): + pass + async for chunk in await chat.send_message_stream( + 'write a unit test for the function' + ): + pass + + +def test_mcp_tools(client): + chat = client.chats.create( + model='gemini-2.0-flash-exp', + config={'tools': [ + mcp_types.Tool( + name='get_weather', + description='Get the weather in a city.', + inputSchema={ + 'type': 'object', + 'properties': {'location': {'type': 'string'}}, + }, + ) + ],}, + ) + response = chat.send_message('What is the weather in Boston?') + response = chat.send_message('What is the weather in San Francisco?') + + +def test_mcp_tools_stream(client): + chat = client.chats.create( + model='gemini-2.0-flash-exp', + config={'tools': [ + mcp_types.Tool( + name='get_weather', + description='Get the weather in a city.', + inputSchema={ + 'type': 'object', + 'properties': {'location': {'type': 'string'}}, + }, + ) + ], + }, + ) + for chunk in chat.send_message_stream( + 'What is the weather in Boston?' + ): + pass + for chunk in chat.send_message_stream( + 'What is the weather in San Francisco?' + ): + pass + + +@pytest.mark.asyncio +async def test_async_mcp_tools(client): + chat = client.aio.chats.create( + model='gemini-2.0-flash-exp', + config={'tools': [ + mcp_types.Tool( + name='get_weather', + description='Get the weather in a city.', + inputSchema={ + 'type': 'object', + 'properties': {'location': {'type': 'string'}}, + }, + ) + ],}, + ) + await chat.send_message('What is the weather in Boston?'); + await chat.send_message('What is the weather in San Francisco?'); + + +@pytest.mark.asyncio +async def test_async_mcp_tools_stream(client): + chat = client.aio.chats.create( + model='gemini-2.0-flash-exp', + config={'tools': [ + mcp_types.Tool( + name='get_weather', + description='Get the weather in a city.', + inputSchema={ + 'type': 'object', + 'properties': {'location': {'type': 'string'}}, + }, + ) + ], + }, + ) + + async for chunk in await chat.send_message_stream( + 'What is the weather in Boston?' + ): + pass + async for chunk in await chat.send_message_stream( + 'What is the weather in San Francisco?' + ): + pass + + +def test_server_side_mcp_tools(client): + with pytest_helper.exception_if_vertex(client, ValueError): + chat = client.chats.create( + model='gemini-2.5-flash', + config={ + 'tools': [ + { + 'mcp_servers': [ + { + 'name': 'weather_server', + 'streamable_http_transport': { + 'url': ( + 'https://gemini-api-demos.uc.r.appspot.com/mcp' + ), + 'headers': { + 'AUTHORIZATION': 'Bearer github_pat_XXXX', + }, + 'timeout': '10s', + }, + }, + ], + }, + ], + }, + ) + response = chat.send_message('What is the weather in Boston on 02/02/2026?') + response = chat.send_message( + 'What is the weather in San Francisco on 02/02/2026?' + ) + + +def test_server_side_mcp_tools_stream(client): + with pytest_helper.exception_if_vertex(client, ValueError): + chat = client.chats.create( + model='gemini-2.5-flash', + config={ + 'tools': [ + { + 'mcp_servers': [ + { + 'name': 'weather_server', + 'streamable_http_transport': { + 'url': ( + 'https://gemini-api-demos.uc.r.appspot.com/mcp' + ), + 'headers': { + 'AUTHORIZATION': 'Bearer github_pat_XXXX', + }, + 'timeout': '10s', + }, + }, + ], + }, + ], + }, + ) + for chunk in chat.send_message_stream( + 'What is the weather in Boston on 02/02/2026?' + ): + pass + for chunk in chat.send_message_stream( + 'What is the weather in San Francisco on 02/02/2026?' + ): + pass + + +@pytest.mark.asyncio +async def test_async_server_side_mcp_tools(client): + with pytest_helper.exception_if_vertex(client, ValueError): + chat = client.aio.chats.create( + model='gemini-2.5-flash', + config={ + 'tools': [ + { + 'mcp_servers': [ + { + 'name': 'weather_server', + 'streamable_http_transport': { + 'url': ( + 'https://gemini-api-demos.uc.r.appspot.com/mcp' + ), + 'headers': { + 'AUTHORIZATION': 'Bearer github_pat_XXXX', + }, + 'timeout': '10s', + }, + }, + ], + }, + ], + }, + ) + await chat.send_message('What is the weather in Boston on 02/02/2026?') + await chat.send_message( + 'What is the weather in San Francisco on 02/02/2026?' + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/chats/test_validate_response.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/chats/test_validate_response.py new file mode 100644 index 0000000000000000000000000000000000000000..40c63094b9484f4e93dba74980e3be222a8da2d0 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/chats/test_validate_response.py @@ -0,0 +1,90 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +from ... import types +from ...chats import _validate_response + + +def test_validate_response_default_response(): + response = types.GenerateContentResponse() + + assert not _validate_response(response) + + +def test_validate_response_empty_content(): + response = types.GenerateContentResponse(candidates=[]) + + assert not _validate_response(response) + + +def test_validate_response_empty_parts(): + response = types.GenerateContentResponse( + candidates=[types.Candidate(content=types.Content(parts=[]))] + ) + + assert not _validate_response(response) + + +def test_validate_response_empty_part(): + response = types.GenerateContentResponse( + candidates=[types.Candidate(content=types.Content(parts=[types.Part()]))] + ) + + assert not _validate_response(response) + + +def test_validate_response_part_with_empty_text(): + response = types.GenerateContentResponse( + candidates=[ + types.Candidate(content=types.Content(parts=[types.Part(text='')])) + ] + ) + + assert _validate_response(response) + + +def test_validate_response_part_with_text(): + response = types.GenerateContentResponse( + candidates=[ + types.Candidate( + content=types.Content( + parts=[types.Part(text='response from model')] + ) + ) + ] + ) + + assert _validate_response(response) + + +def test_validate_response_part_with_function_call(): + response = types.GenerateContentResponse( + candidates=[ + types.Candidate( + content=types.Content( + parts=[ + types.Part( + function_call=types.FunctionCall( + name='foo', args={'bar': 'baz'} + ) + ) + ] + ) + ) + ] + ) + + assert _validate_response(response) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/client/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/client/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6943892e4086585e5b71fc29211849a309cd9771 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/client/__init__.py @@ -0,0 +1,17 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for the Google GenAI SDK.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/client/test_async_stream.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/client/test_async_stream.py new file mode 100644 index 0000000000000000000000000000000000000000..1fc5cebd1d02ddbb7df9d3d92254157a4340f4ab --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/client/test_async_stream.py @@ -0,0 +1,427 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +"""Tests for async stream.""" + +import asyncio +from typing import List +from unittest import mock +from unittest.mock import AsyncMock +from unittest.mock import MagicMock +from unittest.mock import patch +import pytest + + +try: + import aiohttp + + AIOHTTP_NOT_INSTALLED = False +except ImportError: + AIOHTTP_NOT_INSTALLED = True + aiohttp = mock.MagicMock() + +import httpx + +from ... import _api_client as api_client +from ... import Client +from ... import errors +from ... import types + + +EVENT_STREAM_DATA_WITH_ERROR = [ + b'{"candidates":[{"content":{"parts":[{"text":"test"}],"role":"model"}}]}', + b'\n', + b'{"error":{"code":500,"message":"Error","status":"INTERNAL"}}', +] + + +class MockHTTPXResponse(httpx.Response): + """Mock httpx.Response class for testing.""" + + def __init__(self, lines: List[str]): + self.aiter_lines = MagicMock() + self.aiter_lines.return_value.__aiter__ = MagicMock( + return_value=self._async_line_iterator(lines) + ) + self.aclose = AsyncMock() + + async def _async_line_iterator(self, lines: List[str]): + for line in lines: + yield line + + +class MockAIOHTTPResponse(aiohttp.ClientResponse): + + def __init__(self, lines: List[str]): + self.content = MagicMock() + self.content.readline = AsyncMock() + # Simulate reading lines, each ending with newline bytes for readline behavior + self._read_data = b"\n".join(line.encode("utf-8") for line in lines) + b"\n" + self._read_pos = 0 + self.content.readline.side_effect = self._async_read_line + self.release = MagicMock() + + async def _async_read_line(self) -> bytes: + if self._read_pos >= len(self._read_data): + return b"" # End of stream + + newline_pos = self._read_data.find(b"\n", self._read_pos) + if newline_pos == -1: # Should not happen with the appended '\n' + line = self._read_data[self._read_pos :] + self._read_pos = len(self._read_data) + return line + else: + line = self._read_data[self._read_pos : newline_pos + 1] + self._read_pos = newline_pos + 1 + return line + + +@pytest.fixture +def responses() -> api_client.HttpResponse: + return api_client.HttpResponse(headers={}) + + +requires_aiohttp = pytest.mark.skipif( + AIOHTTP_NOT_INSTALLED, reason="aiohttp is not installed, skipping test." +) + + +@pytest.fixture(autouse=True) +def reset_has_aiohttp(): + yield + api_client.has_aiohttp = False + + +def test_invalid_response_stream_type(responses: api_client.HttpResponse): + """Tests that an invalid response stream type raises an error.""" + api_client.has_aiohttp = False + with pytest.raises( + TypeError, + match=( + "Expected self.response_stream to be an httpx.Response or" + " aiohttp.ClientResponse object" + ), + ): + + async def run(): + async for _ in responses._aiter_response_stream(): + pass + + asyncio.run(run()) + + +@pytest.mark.asyncio +async def test_httpx_simple_lines(responses: api_client.HttpResponse): + lines = ["hello", "world", "testing"] + mock_response = MockHTTPXResponse(lines) + responses.response_stream = mock_response + + results = [line async for line in responses._aiter_response_stream()] + + assert results == lines + mock_response.aiter_lines.assert_called_once() + mock_response.aclose.assert_called_once() + + +@pytest.mark.asyncio +async def test_httpx_data_prefix(responses: api_client.HttpResponse): + lines = ["data: { 'message': 'hello' }", "data: { 'status': 'ok' }"] + mock_response = MockHTTPXResponse(lines) + responses.response_stream = mock_response + + results = [line async for line in responses._aiter_response_stream()] + + assert results == ["{ 'message': 'hello' }", "{ 'status': 'ok' }"] + mock_response.aiter_lines.assert_called_once() + mock_response.aclose.assert_called_once() + + +@pytest.mark.asyncio +async def test_httpx_multiple_json_chunk(responses: api_client.HttpResponse): + lines = [ + '{ "id": 1 }', + "", + 'data: { "id": 2 }', + 'data: { "id": 3 }', + ] + mock_response = MockHTTPXResponse(lines) + responses.response_stream = mock_response + + results = [line async for line in responses._aiter_response_stream()] + + assert results == ['{ "id": 1 }', '{ "id": 2 }', '{ "id": 3 }'] + mock_response.aiter_lines.assert_called_once() + mock_response.aclose.assert_called_once() + + +@pytest.mark.asyncio +async def test_httpx_incomplete_json_at_end(responses: api_client.HttpResponse): + lines = ['{ "partial": "data"'] # Missing closing brace + mock_response = MockHTTPXResponse(lines) + responses.response_stream = mock_response + + results = [line async for line in responses._aiter_response_stream()] + + # The remaining chunk is yielded + assert results == ['{ "partial": "data"'] + mock_response.aiter_lines.assert_called_once() + mock_response.aclose.assert_called_once() + + +@pytest.mark.asyncio +async def test_httpx_empty_stream(responses: api_client.HttpResponse): + lines: List[str] = [] + mock_response = MockHTTPXResponse(lines) + responses.response_stream = mock_response + + results = [line async for line in responses._aiter_response_stream()] + + assert results == [] + mock_response.aiter_lines.assert_called_once() + mock_response.aclose.assert_called_once() + + +# Async aiohttp +@requires_aiohttp +@pytest.mark.asyncio +async def test_aiohttp_simple_lines(responses: api_client.HttpResponse): + api_client.has_aiohttp = True # Force aiohttp + lines = ["hello", "world", "testing"] + # Use the mock class that pretends to be aiohttp.ClientResponse + mock_response = MockAIOHTTPResponse(lines) + responses.response_stream = mock_response + + results = [line async for line in responses._aiter_response_stream()] + + assert results == lines + mock_response.content.readline.assert_any_call() + mock_response.release.assert_called_once() + + +@requires_aiohttp +@pytest.mark.asyncio +async def test_aiohttp_data_prefix(responses: api_client.HttpResponse): + api_client.has_aiohttp = True # Force aiohttp + lines = ["data: { 'message': 'hello' }", "data: { 'status': 'ok' }"] + # Use the mock class that pretends to be aiohttp.ClientResponse + mock_response = MockAIOHTTPResponse(lines) + responses.response_stream = mock_response + + results = [line async for line in responses._aiter_response_stream()] + + assert results == ["{ 'message': 'hello' }", "{ 'status': 'ok' }"] + mock_response.content.readline.assert_any_call() + mock_response.release.assert_called_once() + + +@requires_aiohttp +@pytest.mark.asyncio +async def test_aiohttp_multiple_json_chunks(responses: api_client.HttpResponse): + api_client.has_aiohttp = True # Force aiohttp + lines = [ + '{ "id": 1 }', + "", # empty line to check robustness + 'data: { "id": 2 }', + 'data: { "id": 3 }', + ] + # Use the mock class that pretends to be aiohttp.ClientResponse + mock_response = MockAIOHTTPResponse(lines) + responses.response_stream = mock_response + + results = [line async for line in responses._aiter_response_stream()] + + assert results == ['{ "id": 1 }', '{ "id": 2 }', '{ "id": 3 }'] + mock_response.content.readline.assert_any_call() + mock_response.release.assert_called_once() + + +@requires_aiohttp +@pytest.mark.asyncio +async def test_aiohttp_incomplete_json_at_end( + responses: api_client.HttpResponse, +): + api_client.has_aiohttp = True # Force aiohttp + lines = ['{ "partial": "data"'] # Missing closing brace + # Use the mock class that pretends to be aiohttp.ClientResponse + mock_response = MockAIOHTTPResponse(lines) + responses.response_stream = mock_response + + results = [line async for line in responses._aiter_response_stream()] + + assert results == ['{ "partial": "data"'] + mock_response.content.readline.assert_any_call() + mock_response.release.assert_called_once() + + +def mock_response(chunks): + mock_stream = MagicMock(spec=httpx.SyncByteStream) + mock_stream.__iter__.return_value = chunks + return httpx.Response( + status_code=200, + stream=mock_stream, + ) + + +@patch('httpx.Client.send') +def test_error_event_in_streamed_responses_bad_json(mock_send_method): + with_bad_json = [ + b'{"candidates":[{"content":{"parts":[{"text":"test"}],"role":"model"}}]}', + b'\n', + b'{"error": bad_json}', + ] + mock_send_method.return_value = mock_response(with_bad_json) + + client = api_client.BaseApiClient(api_key='test_api_key') + stream = client.request_streamed('POST', 'models/gemini-2.5-flash', {}) + + chunk = next(stream) + assert chunk == types.HttpResponse( + headers={}, + body=( + '{"candidates": [{"content": {"parts": [{"text": "test"}], "role":' + ' "model"}}]}' + ), + ) + + with pytest.raises(errors.UnknownApiResponseError): + next(stream) + + +@patch('httpx.Client.send') +def test_error_event_in_streamed_responses(mock_send_method): + mock_send_method.return_value = mock_response(EVENT_STREAM_DATA_WITH_ERROR) + + client = api_client.BaseApiClient(api_key='test_api_key') + stream = client.request_streamed('POST', 'models/gemini-2.5-flash', {}) + + chunk = next(stream) + assert chunk == types.HttpResponse( + body=( + '{"candidates": [{"content": {"parts": [{"text": "test"}], "role":' + ' "model"}}]}' + ), + headers={}, + ) + + with pytest.raises(errors.ServerError): + next(stream) + + +@patch('httpx.Client.send') +def test_error_event_in_generate_content_stream(mock_send_method): + mock_send_method.return_value = mock_response(EVENT_STREAM_DATA_WITH_ERROR) + + client = Client(api_key='test_api_key') + generated_response = client.models.generate_content_stream( + model='gemini-2.5-flash', + contents='Tell me a story in 300 words.', + ) + + chunk = next(generated_response) + assert chunk == types.GenerateContentResponse( + candidates=[ + types.Candidate( + content=types.Content( + parts=[ + types.Part( + text='test' + ), + ], + role='model' + ) + ), + ], + sdk_http_response=types.HttpResponse(headers={}) + ) + + with pytest.raises(errors.ServerError): + next(generated_response) + + +async def _async_httpx_response(_): + mock_stream = MagicMock(spec=httpx.AsyncByteStream) + mock_stream.__aiter__.return_value = EVENT_STREAM_DATA_WITH_ERROR + mock_stream.aclose = AsyncMock() + return httpx.Response( + status_code=200, + stream=mock_stream, + ) + + +@patch('httpx.AsyncBaseTransport') +@pytest.mark.asyncio +async def test_error_event_in_streamed_responses_async(mock_transport): + client = api_client.BaseApiClient( + api_key='test_api_key', + http_options=types.HttpOptions( + async_client_args={'transport': mock_transport} + ), + ) + mock_transport.handle_async_request = _async_httpx_response + mock_transport.aclose = AsyncMock() + + resp = await client.async_request_streamed( + 'POST', 'models/gemini-2.5-flash', {'key': 'value'} + ) + + chunk = await anext(resp) + assert chunk == types.HttpResponse( + headers={}, + body=( + '{"candidates": [{"content": {"parts": [{"text": "test"}], "role":' + ' "model"}}]}' + ), + ) + + with pytest.raises(errors.ServerError): + await anext(resp) + + +@patch('httpx.AsyncBaseTransport') +@pytest.mark.asyncio +async def test_error_event_in_generate_content_stream_async(mock_transport): + client = Client( + api_key='test_api_key', + http_options=types.HttpOptions( + async_client_args={'transport': mock_transport} + ), + ) + mock_transport.handle_async_request = _async_httpx_response + mock_transport.aclose = AsyncMock() + + generated_response = await client.aio.models.generate_content_stream( + model='gemini-2.5-flash', + contents='Tell me a story in 300 words.', + ) + + chunk = await anext(generated_response) + assert chunk == types.GenerateContentResponse( + candidates=[ + types.Candidate( + content=types.Content( + parts=[ + types.Part( + text='test' + ), + ], + role='model' + ) + ), + ], + sdk_http_response=types.HttpResponse(headers={}) + ) + + with pytest.raises(errors.ServerError): + await anext(generated_response) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/client/test_client_close.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/client/test_client_close.py new file mode 100644 index 0000000000000000000000000000000000000000..00e2bc6bc5ac2483bf6c81c3ed4b8d040bb5224d --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/client/test_client_close.py @@ -0,0 +1,204 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +"""Tests for closing the clients and context managers.""" +import asyncio +from unittest import mock + +from google.oauth2 import credentials +import pytest +try: + import aiohttp + AIOHTTP_NOT_INSTALLED = False +except ImportError: + AIOHTTP_NOT_INSTALLED = True + aiohttp = mock.MagicMock() + + +from ... import _api_client as api_client +from ... import Client + + +requires_aiohttp = pytest.mark.skipif( + AIOHTTP_NOT_INSTALLED, reason='aiohttp is not installed, skipping test.' +) + + +def test_close_httpx_client(): + """Tests that the httpx client is closed when the client is closed.""" + api_client.has_aiohttp = False + client = Client( + vertexai=True, + project='test_project', + location='global', + http_options=api_client.HttpOptions(client_args={'max_redirects': 10}), + ) + client.close() + assert client._api_client._httpx_client.is_closed + + +def test_httpx_client_context_manager(): + """Tests that the httpx client is closed when the client is closed.""" + api_client.has_aiohttp = False + with Client( + vertexai=True, + project='test_project', + location='global', + http_options=api_client.HttpOptions(client_args={'max_redirects': 10}), + ) as client: + pass + assert not client._api_client._httpx_client.is_closed + + assert client._api_client._httpx_client.is_closed + + +@pytest.mark.asyncio +async def test_aclose_httpx_client(): + """Tests that the httpx async client is closed when the client is closed.""" + api_client.has_aiohttp = False + async_client = Client( + vertexai=True, + project='test_project', + location='global', + ).aio + await async_client.aclose() + assert async_client._api_client._async_httpx_client.is_closed + + +@pytest.mark.asyncio +async def test_async_httpx_client_context_manager(): + """Tests that the httpx async client is closed when the client is closed.""" + api_client.has_aiohttp = False + async with Client( + vertexai=True, + project='test_project', + location='global', + ).aio as async_client: + pass + assert not async_client._api_client._async_httpx_client.is_closed + + assert async_client._api_client._async_httpx_client.is_closed + + +@pytest.fixture +def mock_request(): + mock_aiohttp_response = mock.Mock(spec=aiohttp.ClientSession.request) + mock_aiohttp_response.return_value = mock_aiohttp_response + yield mock_aiohttp_response + + +def _patch_auth_default(): + return mock.patch( + 'google.auth.default', + return_value=(credentials.Credentials('magic_token'), 'test_project'), + autospec=True, + ) + + +async def _aiohttp_async_response(status: int): + """Has to return a coroutine hence async.""" + response = mock.Mock(spec=aiohttp.ClientResponse) + response.status = status + response.headers = {'status-code': str(status)} + response.json.return_value = {} + response.text.return_value = 'test' + return response + + +@requires_aiohttp +@mock.patch.object(aiohttp.ClientSession, 'request', autospec=True) +def test_aclose_aiohttp_session(mock_request): + """Tests that the aiohttp session is closed when the client is closed.""" + api_client.has_aiohttp = True + async def run(): + mock_request.side_effect = ( + aiohttp.ClientConnectorError( + connection_key=aiohttp.client_reqrep.ConnectionKey( + 'localhost', 80, False, True, None, None, None + ), + os_error=OSError, + ), + _aiohttp_async_response(200), + ) + with _patch_auth_default(): + async_client = Client( + vertexai=True, + project='test_project', + location='global', + http_options=api_client.HttpOptions( + async_client_args={'trust_env': False} + ), + ).aio + # aiohttp session is created in the first request instead of client + # initialization. + _ = await async_client._api_client._async_request_once( + api_client.HttpRequest( + method='GET', + url='https://example.com', + headers={}, + data=None, + timeout=None, + ) + ) + assert async_client._api_client._aiohttp_session is not None + assert not async_client._api_client._aiohttp_session.closed + # Close the client and check that the session is closed. + await async_client.aclose() + assert async_client._api_client._aiohttp_session.closed + + asyncio.run(run()) + + +@requires_aiohttp +@mock.patch.object(aiohttp.ClientSession, 'request', autospec=True) +def test_aiohttp_session_context_manager(mock_request): + """Tests that the aiohttp session is closed when the client is closed.""" + api_client.has_aiohttp = True + async def run(): + mock_request.side_effect = ( + aiohttp.ClientConnectorError( + connection_key=aiohttp.client_reqrep.ConnectionKey( + 'localhost', 80, False, True, None, None, None + ), + os_error=OSError, + ), + _aiohttp_async_response(200), + ) + with _patch_auth_default(): + async with Client( + vertexai=True, + project='test_project', + location='global', + http_options=api_client.HttpOptions( + async_client_args={'trust_env': False} + ), + ).aio as async_client: + # aiohttp session is created in the first request instead of client + # initialization. + _ = await async_client._api_client._async_request_once( + api_client.HttpRequest( + method='GET', + url='https://example.com', + headers={}, + data=None, + timeout=None, + ) + ) + assert async_client._api_client._aiohttp_session is not None + assert not async_client._api_client._aiohttp_session.closed + + assert async_client._api_client._aiohttp_session.closed + + asyncio.run(run()) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/client/test_client_initialization.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/client/test_client_initialization.py new file mode 100644 index 0000000000000000000000000000000000000000..64c9da2732ed157edc0566ee623027920eb24a25 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/client/test_client_initialization.py @@ -0,0 +1,1791 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for client initialization.""" + +import asyncio +import concurrent.futures +import logging +import os +import requests +import ssl +from unittest import mock + +import certifi +import google.auth +from google.auth import credentials +import httpx +import pytest + +from ... import _api_client as api_client +from ... import _base_url as base_url +from ... import _replay_api_client as replay_api_client +from ... import Client +from ... import types +try: + import aiohttp + AIOHTTP_NOT_INSTALLED = False +except ImportError: + AIOHTTP_NOT_INSTALLED = True + aiohttp = mock.MagicMock() + + +requires_aiohttp = pytest.mark.skipif( + AIOHTTP_NOT_INSTALLED, reason="aiohttp is not installed, skipping test." +) + + +@pytest.fixture(autouse=True) +def reset_has_aiohttp(): + yield + api_client.has_aiohttp = False + + +def test_ml_dev_from_gemini_env_only(monkeypatch): + api_key = "gemini_api_key" + monkeypatch.setenv("GEMINI_API_KEY", api_key) + monkeypatch.delenv("GOOGLE_API_KEY", raising=False) + + client = Client() + + assert not client.models._api_client.vertexai + assert client.models._api_client.api_key == api_key + assert isinstance(client.models._api_client, api_client.BaseApiClient) + + +def test_ml_dev_from_gemini_env_with_google_env_empty(monkeypatch): + api_key = "gemini_api_key" + monkeypatch.setenv("GEMINI_API_KEY", api_key) + monkeypatch.setenv("GOOGLE_API_KEY", "") + + client = Client() + + assert not client.models._api_client.vertexai + assert client.models._api_client.api_key == api_key + assert isinstance(client.models._api_client, api_client.BaseApiClient) + + +def test_ml_dev_from_google_env_only(monkeypatch): + api_key = "google_api_key" + monkeypatch.setenv("GOOGLE_API_KEY", api_key) + monkeypatch.delenv("GEMINI_API_KEY", raising=False) + + client = Client() + + assert not client.models._api_client.vertexai + assert client.models._api_client.api_key == api_key + assert isinstance(client.models._api_client, api_client.BaseApiClient) + + +def test_ml_dev_both_env_key_set(monkeypatch, caplog): + caplog.set_level(logging.DEBUG, logger="google_genai._api_client") + google_api_key = "google_api_key" + gemini_api_key = "gemini_api_key" + monkeypatch.setenv("GOOGLE_API_KEY", google_api_key) + monkeypatch.setenv("GEMINI_API_KEY", gemini_api_key) + + client = Client() + + assert not client.models._api_client.vertexai + assert client.models._api_client.api_key == google_api_key + assert isinstance(client.models._api_client, api_client.BaseApiClient) + assert ( + "Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY." + in caplog.text + ) + + +def test_api_key_with_new_line(monkeypatch, caplog): + caplog.set_level(logging.DEBUG, logger="google_genai._api_client") + api_key = "gemini_api_key\r\n" + monkeypatch.setenv("GOOGLE_API_KEY", api_key) + + client = Client() + + assert client.models._api_client.api_key == "gemini_api_key" + + +def test_ml_dev_from_constructor(): + api_key = "google_api_key" + + client = Client(api_key=api_key) + + assert not client.models._api_client.vertexai + assert client.models._api_client.api_key == api_key + + +def test_constructor_with_http_options(): + mldev_http_options = { + "api_version": "v1main", + "base_url": "https://placeholder-fake-url.com/", + "headers": {"X-Custom-Header": "custom_value_mldev"}, + "timeout": 10000, + } + vertexai_http_options = { + "api_version": "v1", + "base_url": ( + "https://{self.location}-aiplatform.googleapis.com/{{api_version}}/" + ), + "headers": {"X-Custom-Header": "custom_value_vertexai"}, + "timeout": 11000, + } + + mldev_client = Client( + api_key="google_api_key", http_options=mldev_http_options + ) + assert not mldev_client.models._api_client.vertexai + assert ( + mldev_client.models._api_client.get_read_only_http_options()["base_url"] + == "https://placeholder-fake-url.com/" + ) + assert ( + mldev_client.models._api_client.get_read_only_http_options()[ + "api_version" + ] + == "v1main" + ) + + assert ( + mldev_client.models._api_client.get_read_only_http_options()["headers"][ + "X-Custom-Header" + ] + == "custom_value_mldev" + ) + + assert ( + mldev_client.models._api_client.get_read_only_http_options()["timeout"] + == 10000 + ) + + vertexai_client = Client( + vertexai=True, + project="fake_project_id", + location="fake-location", + http_options=vertexai_http_options, + ) + assert vertexai_client.models._api_client.vertexai + assert ( + vertexai_client.models._api_client.get_read_only_http_options()[ + "base_url" + ] + == "https://{self.location}-aiplatform.googleapis.com/{{api_version}}/" + ) + assert ( + vertexai_client.models._api_client.get_read_only_http_options()[ + "api_version" + ] + == "v1" + ) + assert ( + vertexai_client.models._api_client.get_read_only_http_options()[ + "headers" + ]["X-Custom-Header"] + == "custom_value_vertexai" + ) + + assert ( + vertexai_client.models._api_client.get_read_only_http_options()["timeout"] + == 11000 + ) + + +def test_constructor_with_invalid_http_options_key(): + mldev_http_options = { + "invalid_version_key": "v1", + "base_url": "https://placeholder-fake-url.com/", + "headers": {"X-Custom-Header": "custom_value"}, + } + vertexai_http_options = { + "api_version": "v1", + "base_url": ( + "https://{self.location}-aiplatform.googleapis.com/{{api_version}}/" + ), + "invalid_header_key": {"X-Custom-Header": "custom_value"}, + } + + # Expect value error when HTTPOptions is provided as a dict and contains + # an invalid key. + try: + _ = Client(api_key="google_api_key", http_options=mldev_http_options) + except Exception as e: + assert isinstance(e, ValueError) + assert "invalid_version_key" in str(e) + + # Expect value error when HTTPOptions is provided as a dict and contains + # an invalid key. + try: + _ = Client( + vertexai=True, + project="fake_project_id", + location="fake-location", + http_options=vertexai_http_options, + ) + except Exception as e: + assert isinstance(e, ValueError) + assert "invalid_header_key" in str(e) + + +def test_constructor_with_http_options_as_pydantic_type(): + mldev_http_options = types.HttpOptions( + api_version="v1", + base_url="https://placeholder-fake-url.com/", + headers={"X-Custom-Header": "custom_value"}, + ) + vertexai_http_options = types.HttpOptions( + api_version="v1", + base_url=( + "https://{self.location}-aiplatform.googleapis.com/{{api_version}}/" + ), + headers={"X-Custom-Header": "custom_value"}, + ) + + # Test http_options for mldev client. + mldev_client = Client( + api_key="google_api_key", http_options=mldev_http_options + ) + assert not mldev_client.models._api_client.vertexai + assert ( + mldev_client.models._api_client.get_read_only_http_options()["base_url"] + == mldev_http_options.base_url + ) + assert ( + mldev_client.models._api_client.get_read_only_http_options()[ + "api_version" + ] + == mldev_http_options.api_version + ) + + assert ( + mldev_client.models._api_client.get_read_only_http_options()["headers"][ + "X-Custom-Header" + ] + == mldev_http_options.headers["X-Custom-Header"] + ) + + # Test http_options for vertexai client. + vertexai_client = Client( + vertexai=True, + project="fake_project_id", + location="fake-location", + http_options=vertexai_http_options, + ) + assert vertexai_client.models._api_client.vertexai + assert ( + vertexai_client.models._api_client.get_read_only_http_options()[ + "base_url" + ] + == vertexai_http_options.base_url + ) + assert ( + vertexai_client.models._api_client.get_read_only_http_options()[ + "api_version" + ] + == vertexai_http_options.api_version + ) + assert ( + vertexai_client.models._api_client.get_read_only_http_options()[ + "headers" + ]["X-Custom-Header"] + == vertexai_http_options.headers["X-Custom-Header"] + ) + + +def test_vertexai_from_env_1(monkeypatch): + project_id = "fake_project_id" + location = "fake-location" + monkeypatch.setenv("GOOGLE_GENAI_USE_VERTEXAI", "1") + monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", project_id) + monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", location) + + client = Client() + + assert client.models._api_client.vertexai + assert client.models._api_client.project == project_id + assert client.models._api_client.location == location + + +def test_vertexai_from_env_true(monkeypatch): + project_id = "fake_project_id" + location = "fake-location" + monkeypatch.setenv("GOOGLE_GENAI_USE_VERTEXAI", "true") + monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", project_id) + monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", location) + + client = Client() + + assert client.models._api_client.vertexai + assert client.models._api_client.project == project_id + assert client.models._api_client.location == location + + +def test_vertexai_from_constructor(): + project_id = "fake_project_id" + location = "fake-location" + + client = Client( + vertexai=True, + project=project_id, + location=location, + ) + + assert client.models._api_client.vertexai + assert client.models._api_client.project == project_id + assert client.models._api_client.location == location + assert isinstance(client.models._api_client, api_client.BaseApiClient) + + +def test_invalid_vertexai_constructor_empty(monkeypatch): + with pytest.raises(ValueError): + monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "") + monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", "") + monkeypatch.setenv("GOOGLE_API_KEY", "") + monkeypatch.setenv("GEMINI_API_KEY", "") + + def mock_auth_default(scopes=None): + return None, None + + monkeypatch.setattr(google.auth, "default", mock_auth_default) + Client(vertexai=True) + + +def test_vertexai_constructor_empty_base_url_override(monkeypatch): + monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "") + monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", "") + monkeypatch.setenv("GOOGLE_API_KEY", "") + monkeypatch.setenv("GEMINI_API_KEY", "") + + def mock_auth_default(scopes=None): + return None, None + + monkeypatch.setattr(google.auth, "default", mock_auth_default) + # Including a base_url override skips the check for having proj/location or + # api_key set. + client = Client(vertexai=True, http_options={"base_url": "https://override.com/"}) + assert client.models._api_client.location is None + + +def test_invalid_mldev_constructor_empty(monkeypatch): + with pytest.raises(ValueError): + monkeypatch.setenv("GOOGLE_API_KEY", "") + monkeypatch.setenv("GEMINI_API_KEY", "") + Client() + + +def test_invalid_vertexai_constructor1(): + project_id = "fake_project_id" + location = "fake-location" + api_key = "fake-api_key" + try: + Client( + vertexai=True, + project=project_id, + location=location, + api_key=api_key, + ) + except Exception as e: + assert isinstance(e, ValueError) + + +def test_invalid_vertexai_constructor2(): + creds = credentials.AnonymousCredentials() + api_key = "fake-api_key" + with pytest.raises(ValueError): + Client( + vertexai=True, + credentials=creds, + api_key=api_key, + ) + + +def test_vertexai_default_location_to_global(monkeypatch): + + with monkeypatch.context() as m: + m.delenv("GOOGLE_CLOUD_LOCATION", raising=False) + project_id = "fake_project_id" + client = Client(vertexai=True, project=project_id) + assert client.models._api_client.location == "global" + + +def test_vertexai_default_location_to_global_with_credentials(monkeypatch): + # Test case 1: When credentials are provided with project but no location + creds = credentials.AnonymousCredentials() + project_id = "fake_project_id" + + with monkeypatch.context() as m: + m.delenv("GOOGLE_CLOUD_LOCATION", raising=False) + m.setenv("GOOGLE_API_KEY", "") + client = Client(vertexai=True, credentials=creds, project=project_id) + assert client.models._api_client.location == "global" + assert client.models._api_client.project == project_id + + +def test_vertexai_default_location_to_global_with_explicit_project_and_env_apikey( + monkeypatch, +): + # Test case 2: When explicit project is provided and env api_key exists + project_id = "explicit_project_id" + api_key = "env_api_key" + + with monkeypatch.context() as m: + m.delenv("GOOGLE_CLOUD_LOCATION", raising=False) + m.delenv("GOOGLE_CLOUD_PROJECT", raising=False) + m.setenv("GOOGLE_API_KEY", api_key) + client = Client(vertexai=True, project=project_id) + # Explicit project takes precedence over implicit api_key + assert client.models._api_client.location == "global" + assert client.models._api_client.project == project_id + assert not client.models._api_client.api_key + + +def test_vertexai_default_location_to_global_with_vertexai_base_url( + monkeypatch, +): + # Test case 4: When project and vertex base url are set + project_id = "env_project_id" + + with monkeypatch.context() as m: + m.delenv("GOOGLE_CLOUD_LOCATION", raising=False) + m.setenv("GOOGLE_CLOUD_PROJECT", project_id) + client = Client( + vertexai=True, + http_options={'base_url': 'https://fake-url.googleapis.com'}, + ) + # Implicit project takes precedence over implicit api_key + assert client.models._api_client.location == "global" + assert client.models._api_client.project == project_id + + +def test_vertexai_default_location_to_global_with_arbitrary_base_url( + monkeypatch, +): + # Test case 5: When project and arbitrary base url (proxy) are set + project_id = "env_project_id" + + with monkeypatch.context() as m: + m.delenv("GOOGLE_CLOUD_LOCATION", raising=False) + m.setenv("GOOGLE_CLOUD_PROJECT", project_id) + client = Client( + vertexai=True, + http_options={'base_url': 'https://fake-url.com'}, + ) + # Implicit project takes precedence over implicit api_key + assert not client.models._api_client.location + assert not client.models._api_client.project + + +def test_vertexai_default_location_to_global_with_env_project_and_env_apikey( + monkeypatch, +): + # Test case 3: When env project and env api_key both exist + project_id = "env_project_id" + api_key = "env_api_key" + + with monkeypatch.context() as m: + m.delenv("GOOGLE_CLOUD_LOCATION", raising=False) + m.setenv("GOOGLE_CLOUD_PROJECT", project_id) + m.setenv("GOOGLE_API_KEY", api_key) + client = Client(vertexai=True) + # Implicit project takes precedence over implicit api_key + assert client.models._api_client.location == "global" + assert client.models._api_client.project == project_id + assert not client.models._api_client.api_key + + +def test_vertexai_no_default_location_when_location_explicitly_set(monkeypatch): + # Verify that location is NOT defaulted to global when explicitly set + project_id = "fake_project_id" + location = "us-central1" + + with monkeypatch.context() as m: + m.delenv("GOOGLE_CLOUD_LOCATION", raising=False) + client = Client(vertexai=True, project=project_id, location=location) + assert client.models._api_client.location == location + assert client.models._api_client.project == project_id + + +def test_vertexai_location_us_routing(monkeypatch): + # Verify that location='us' correctly routes to the us.rep endpoint + project_id = "fake_project_id" + location = "us" + + with monkeypatch.context() as m: + m.delenv("GOOGLE_CLOUD_LOCATION", raising=False) + client = Client(vertexai=True, project=project_id, location=location) + assert client.models._api_client.location == location + assert client.models._api_client.project == project_id + assert ( + client.models._api_client.get_read_only_http_options()["base_url"] + == "https://aiplatform.us.rep.googleapis.com/" + ) + + +def test_vertexai_location_eu_routing(monkeypatch): + # Verify that location='eu' correctly routes to the eu.rep endpoint + project_id = "fake_project_id" + location = "eu" + + with monkeypatch.context() as m: + m.delenv("GOOGLE_CLOUD_LOCATION", raising=False) + client = Client(vertexai=True, project=project_id, location=location) + assert client.models._api_client.location == location + assert client.models._api_client.project == project_id + assert ( + client.models._api_client.get_read_only_http_options()["base_url"] + == "https://aiplatform.eu.rep.googleapis.com/" + ) + + +def test_vertexai_location_us_routing_base_url_override(monkeypatch): + # Verify that base_url override takes precedence over location='us' routing + project_id = "fake_project_id" + location = "us" + + with monkeypatch.context() as m: + m.delenv("GOOGLE_CLOUD_LOCATION", raising=False) + client = Client( + vertexai=True, + project=project_id, + location=location, + http_options={"base_url": "https://my-custom-url.com/"}, + ) + assert client.models._api_client.location == location + assert client.models._api_client.project == project_id + assert ( + client.models._api_client.get_read_only_http_options()["base_url"] + == "https://my-custom-url.com/" + ) + + +def test_vertexai_no_default_location_when_env_location_set(monkeypatch): + # Verify that location is NOT defaulted to global when set via environment + project_id = "fake_project_id" + location = "us-west1" + + with monkeypatch.context() as m: + m.setenv("GOOGLE_CLOUD_LOCATION", location) + m.setenv("GOOGLE_CLOUD_PROJECT", project_id) + client = Client(vertexai=True) + assert client.models._api_client.location == location + assert client.models._api_client.project == project_id + + +def test_vertexai_no_default_location_with_apikey_only(monkeypatch): + # Verify that location is NOT set when using API key mode (no project) + api_key = "vertexai_api_key" + + with monkeypatch.context() as m: + m.delenv("GOOGLE_CLOUD_LOCATION", raising=False) + m.delenv("GOOGLE_CLOUD_PROJECT", raising=False) + m.setenv("GOOGLE_API_KEY", "") + client = Client(vertexai=True, api_key=api_key) + assert not client.models._api_client.location + assert not client.models._api_client.project + assert client.models._api_client.api_key == api_key + + +def test_vertexai_explicit_credentials(monkeypatch): + creds = credentials.AnonymousCredentials() + monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "fake_project_id") + monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", "fake-location") + monkeypatch.setenv("GOOGLE_API_KEY", "env_api_key") + + client = Client( + vertexai=True, + credentials=creds + ) + + assert client.models._api_client.vertexai + assert client.models._api_client.project + assert client.models._api_client.location + assert not client.models._api_client.api_key + assert client.models._api_client._credentials is creds + assert isinstance(client.models._api_client, api_client.BaseApiClient) + + +def test_vertexai_explicit_arg_precedence1(monkeypatch): + project_id = "constructor_project_id" + location = "constructor-location" + + monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "env_project_id") + monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", "env_location") + monkeypatch.setenv("GOOGLE_API_KEY", "") + + client = Client( + vertexai=True, + project=project_id, + location=location, + ) + + assert client.models._api_client.vertexai + assert client.models._api_client.project == project_id + assert client.models._api_client.location == location + assert not client.models._api_client.api_key + assert isinstance(client.models._api_client, api_client.BaseApiClient) + + +def test_vertexai_explicit_arg_precedence2(monkeypatch): + api_key = "constructor_apikey" + + monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "") + monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", "") + monkeypatch.setenv("GOOGLE_API_KEY", "env_api_key") + + client = Client( + vertexai=True, + api_key=api_key, + ) + + assert client.models._api_client.vertexai + assert not client.models._api_client.project + assert not client.models._api_client.location + assert client.models._api_client.api_key == api_key + assert isinstance(client.models._api_client, api_client.BaseApiClient) + + +def test_invalid_mldev_constructor(): + project_id = "fake_project_id" + location = "fake-location" + api_key = "fake-api_key" + try: + Client( + project=project_id, + location=location, + api_key=api_key, + ) + except Exception as e: + assert isinstance(e, ValueError) + + +def test_mldev_explicit_arg_precedence(monkeypatch, caplog): + caplog.set_level(logging.DEBUG, logger="google_genai._api_client") + api_key = "constructor_api_key" + + monkeypatch.setenv("GOOGLE_API_KEY", "google_env_api_key") + monkeypatch.setenv("GEMINI_API_KEY", "gemini_env_api_key") + + client = Client(api_key=api_key) + + assert not client.models._api_client.vertexai + assert client.models._api_client.api_key == api_key + assert isinstance(client.models._api_client, api_client.BaseApiClient) + assert ( + "Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY." + in caplog.text + ) + + +def test_replay_client_ml_dev_from_env(monkeypatch, use_vertex: bool): + api_key = "google_api_key" + monkeypatch.setenv("GOOGLE_API_KEY", api_key) + monkeypatch.setenv("GOOGLE_GENAI_CLIENT_MODE", "replay") + api_type = "vertex" if use_vertex else "mldev" + monkeypatch.setenv("GOOGLE_GENAI_REPLAY_ID", "test_replay_id." + api_type) + monkeypatch.setenv("GOOGLE_GENAI_REPLAYS_DIRECTORY", "test_replay_data") + + client = Client() + + assert not client.models._api_client.vertexai + assert client.models._api_client.api_key == api_key + assert isinstance( + client.models._api_client, replay_api_client.ReplayApiClient + ) + + +def test_replay_client_vertexai_from_env(monkeypatch, use_vertex: bool): + project_id = "fake_project_id" + location = "fake-location" + monkeypatch.setenv("GOOGLE_GENAI_USE_VERTEXAI", "1") + monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", project_id) + monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", location) + monkeypatch.setenv("GOOGLE_GENAI_CLIENT_MODE", "replay") + api_type = "vertex" if use_vertex else "mldev" + monkeypatch.setenv("GOOGLE_GENAI_REPLAY_ID", "test_replay_id." + api_type) + monkeypatch.setenv("GOOGLE_GENAI_REPLAYS_DIRECTORY", "test_replay_data") + + client = Client() + + assert client.models._api_client.vertexai + assert client.models._api_client.project == project_id + assert client.models._api_client.location == location + assert isinstance( + client.models._api_client, replay_api_client.ReplayApiClient + ) + + +def test_change_client_mode_from_env(monkeypatch, use_vertex: bool): + api_key = "google_api_key" + monkeypatch.setenv("GOOGLE_API_KEY", api_key) + monkeypatch.setenv("GOOGLE_GENAI_CLIENT_MODE", "replay") + + client1 = Client() + assert isinstance( + client1.models._api_client, replay_api_client.ReplayApiClient + ) + monkeypatch.setenv("GOOGLE_GENAI_CLIENT_MODE", "") + + client2 = Client() + assert isinstance(client2.models._api_client, api_client.BaseApiClient) + + +def test_vertexai_apikey_from_constructor(monkeypatch): + # Vertex AI Express mode uses API key on Vertex AI. + api_key = "vertexai_api_key" + + # Due to proj/location taking precedence, need to clear proj/location env + # variables. + monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", "") + monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "") + + client = Client(api_key=api_key, vertexai=True) + + assert client.models._api_client.vertexai + assert not client.models._api_client.project + assert not client.models._api_client.location + assert client.models._api_client.api_key == api_key + assert "aiplatform" in client._api_client._http_options.base_url + assert isinstance(client.models._api_client, api_client.BaseApiClient) + + +def test_vertexai_apikey_from_env_google_api_key_only(monkeypatch): + # Vertex AI Express mode uses API key on Vertex AI. + api_key = "vertexai_api_key" + monkeypatch.setenv("GOOGLE_API_KEY", api_key) + monkeypatch.delenv("GEMINI_API_KEY", raising=False) + + # Due to proj/location taking precedence, need to clear proj/location env + # variables. + monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", "") + monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "") + + client = Client(vertexai=True) + + assert client.models._api_client.vertexai + assert client.models._api_client.api_key == api_key + assert not client.models._api_client.project + assert not client.models._api_client.location + assert "aiplatform" in client._api_client._http_options.base_url + assert isinstance(client.models._api_client, api_client.BaseApiClient) + + +def test_vertexai_apikey_from_env_gemini_api_key_only(monkeypatch): + # Vertex AI Express mode uses API key on Vertex AI. + api_key = "vertexai_api_key" + monkeypatch.setenv("GEMINI_API_KEY", api_key) + monkeypatch.delenv("GOOGLE_API_KEY", raising=False) + + # Due to proj/location taking precedence, need to clear proj/location env + # variables. + monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", "") + monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "") + + client = Client(vertexai=True) + + assert client.models._api_client.vertexai + assert client.models._api_client.api_key == api_key + assert not client.models._api_client.project + assert not client.models._api_client.location + assert "aiplatform" in client._api_client._http_options.base_url + assert isinstance(client.models._api_client, api_client.BaseApiClient) + + +def test_vertexai_apikey_from_env_gemini_api_key_with_google_api_key_empty( + monkeypatch, +): + # Vertex AI Express mode uses API key on Vertex AI. + api_key = "vertexai_api_key" + monkeypatch.setenv("GEMINI_API_KEY", api_key) + monkeypatch.setenv("GOOGLE_API_KEY", "") + + # Due to proj/location taking precedence, need to clear proj/location env + # variables. + monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", "") + monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "") + + client = Client(vertexai=True) + + assert client.models._api_client.vertexai + assert client.models._api_client.api_key == api_key + assert not client.models._api_client.project + assert not client.models._api_client.location + assert "aiplatform" in client._api_client._http_options.base_url + assert isinstance(client.models._api_client, api_client.BaseApiClient) + + +def test_vertexai_apikey_from_env_both_api_keys(monkeypatch, caplog): + caplog.set_level(logging.DEBUG, logger="google_genai._api_client") + # Vertex AI Express mode uses API key on Vertex AI. + google_api_key = "google_api_key" + gemini_api_key = "vertexai_api_key" + monkeypatch.setenv("GEMINI_API_KEY", gemini_api_key) + monkeypatch.setenv("GOOGLE_API_KEY", google_api_key) + + # Due to proj/location taking precedence, need to clear proj/location env + # variables. + monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", "") + monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "") + + client = Client(vertexai=True) + + assert client.models._api_client.vertexai + assert client.models._api_client.api_key == google_api_key + assert not client.models._api_client.project + assert not client.models._api_client.location + assert "aiplatform" in client._api_client._http_options.base_url + assert isinstance(client.models._api_client, api_client.BaseApiClient) + assert ( + "Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY." + in caplog.text + ) + + +def test_vertexai_apikey_invalid_constructor1(): + # Vertex AI Express mode uses API key on Vertex AI. + api_key = "vertexai_api_key" + project_id = "fake_project_id" + location = "fake-location" + + with pytest.raises(ValueError): + Client( + api_key=api_key, + project=project_id, + location=location, + vertexai=True, + ) + + +def test_vertexai_apikey_combo1(monkeypatch): + # Vertex AI Express mode uses API key on Vertex AI. + api_key = "vertexai_api_key" + project_id = "fake_project_id" + location = "fake-location" + monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", project_id) + monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", location) + monkeypatch.setenv("GOOGLE_API_KEY", "") + + # Explicit api_key takes precedence over implicit project/location. + client = Client(vertexai=True, api_key=api_key) + + assert client.models._api_client.vertexai + assert client.models._api_client.api_key == api_key + assert not client.models._api_client.project + assert not client.models._api_client.location + assert "aiplatform" in client._api_client._http_options.base_url + assert isinstance(client.models._api_client, api_client.BaseApiClient) + + +def test_vertexai_apikey_combo2(monkeypatch): + # Vertex AI Express mode uses API key on Vertex AI. + api_key = "vertexai_api_key" + project_id = "fake_project_id" + location = "fake-location" + monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "") + monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", "") + monkeypatch.setenv("GOOGLE_API_KEY", api_key) + + # Explicit project/location takes precedence over implicit api_key. + client = Client(vertexai=True, project=project_id, location=location) + + assert client.models._api_client.vertexai + assert not client.models._api_client.api_key + assert client.models._api_client.project == project_id + assert client.models._api_client.location == location + assert "aiplatform" in client._api_client._http_options.base_url + assert isinstance(client.models._api_client, api_client.BaseApiClient) + + +def test_vertexai_apikey_combo3(monkeypatch): + # Vertex AI Express mode uses API key on Vertex AI. + project_id = "fake_project_id" + location = "fake-location" + api_key = "vertexai_api_key" + monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", project_id) + monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", location) + monkeypatch.setenv("GOOGLE_API_KEY", api_key) + + # Implicit project/location takes precedence over implicit api_key. + client = Client(vertexai=True) + + assert client.models._api_client.vertexai + assert not client.models._api_client.api_key + assert client.models._api_client.project == project_id + assert client.models._api_client.location == location + assert "aiplatform" in client._api_client._http_options.base_url + assert isinstance(client.models._api_client, api_client.BaseApiClient) + + +def test_vertexai_global_endpoint(monkeypatch): + # Vertex AI uses global endpoint when location is global. + project_id = "fake_project_id" + location = "global" + monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", project_id) + monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", location) + + client = Client(vertexai=True, location=location) + + assert client.models._api_client.vertexai + assert client.models._api_client.project == project_id + assert client.models._api_client.location == location + assert client.models._api_client._http_options.base_url == ( + "https://aiplatform.googleapis.com/" + ) + assert isinstance(client.models._api_client, api_client.BaseApiClient) + + +def test_client_logs_to_logger_instance(monkeypatch, caplog): + caplog.set_level(logging.DEBUG, logger="google_genai._api_client") + + project_id = "fake_project_id" + location = "fake-location" + api_key = "vertexai_api_key" + monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", project_id) + monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", location) + + _ = Client(vertexai=True, api_key=api_key) + + assert "INFO" in caplog.text + assert ( + "The user provided Vertex AI API key will take precedence" in caplog.text + ) + + +def test_client_ssl_context_implicit_initialization(): + client_args, async_client_args = ( + api_client.BaseApiClient._ensure_httpx_ssl_ctx(types.HttpOptions()) + ) + + assert client_args["verify"] + assert isinstance(client_args["verify"], ssl.SSLContext) + try: + import aiohttp # pylint: disable=g-import-not-at-top + + async_client_args = api_client.BaseApiClient._ensure_aiohttp_ssl_ctx( + types.HttpOptions() + ) + assert async_client_args["ssl"] + assert isinstance(async_client_args["ssl"], ssl.SSLContext) + except ImportError: + assert async_client_args["verify"] + assert isinstance(async_client_args["verify"], ssl.SSLContext) + + +def test_client_ssl_context_explicit_initialization_same_args(): + ctx = ssl.create_default_context( + cafile=os.environ.get("SSL_CERT_FILE", certifi.where()), + capath=os.environ.get("SSL_CERT_DIR"), + ) + + options = types.HttpOptions( + client_args={"verify": ctx}, async_client_args={"verify": ctx} + ) + client_args, async_client_args = ( + api_client.BaseApiClient._ensure_httpx_ssl_ctx(options) + ) + + assert client_args["verify"] == ctx + try: + import aiohttp # pylint: disable=g-import-not-at-top + + async_client_args = api_client.BaseApiClient._ensure_aiohttp_ssl_ctx( + options + ) + assert async_client_args["ssl"] + assert isinstance(async_client_args["ssl"], ssl.SSLContext) + except ImportError: + assert async_client_args["verify"] + assert isinstance(async_client_args["verify"], ssl.SSLContext) + + +def test_client_ssl_context_explicit_initialization_separate_args(): + ctx = ssl.create_default_context( + cafile=os.environ.get("SSL_CERT_FILE", certifi.where()), + capath=os.environ.get("SSL_CERT_DIR"), + ) + + async_ctx = ssl.create_default_context( + cafile=os.environ.get("SSL_CERT_FILE", certifi.where()), + capath=os.environ.get("SSL_CERT_DIR"), + ) + + options = types.HttpOptions( + client_args={"verify": ctx}, async_client_args={"verify": async_ctx} + ) + client_args, async_client_args = ( + api_client.BaseApiClient._ensure_httpx_ssl_ctx(options) + ) + + assert client_args["verify"] == ctx + try: + import aiohttp # pylint: disable=g-import-not-at-top + + async_client_args = api_client.BaseApiClient._ensure_aiohttp_ssl_ctx( + options + ) + assert async_client_args["ssl"] + assert isinstance(async_client_args["ssl"], ssl.SSLContext) + except ImportError: + assert async_client_args["verify"] + assert isinstance(async_client_args["verify"], ssl.SSLContext) + + +def test_client_ssl_context_explicit_initialization_sync_args(): + ctx = ssl.create_default_context( + cafile=os.environ.get("SSL_CERT_FILE", certifi.where()), + capath=os.environ.get("SSL_CERT_DIR"), + ) + + options = types.HttpOptions(client_args={"verify": ctx}) + client_args, async_client_args = ( + api_client.BaseApiClient._ensure_httpx_ssl_ctx(options) + ) + + assert client_args["verify"] == ctx + try: + import aiohttp # pylint: disable=g-import-not-at-top + + async_client_args = api_client.BaseApiClient._ensure_aiohttp_ssl_ctx( + options + ) + assert async_client_args["ssl"] + assert isinstance(async_client_args["ssl"], ssl.SSLContext) + except ImportError: + assert async_client_args["verify"] + assert isinstance(async_client_args["verify"], ssl.SSLContext) + + +def test_client_ssl_context_explicit_initialization_async_args(): + ctx = ssl.create_default_context( + cafile=os.environ.get("SSL_CERT_FILE", certifi.where()), + capath=os.environ.get("SSL_CERT_DIR"), + ) + + options = types.HttpOptions(async_client_args={"verify": ctx}) + client_args, async_client_args = ( + api_client.BaseApiClient._ensure_httpx_ssl_ctx(options) + ) + + assert client_args["verify"] == ctx + try: + import aiohttp # pylint: disable=g-import-not-at-top + + async_client_args = api_client.BaseApiClient._ensure_aiohttp_ssl_ctx( + options + ) + assert async_client_args["ssl"] + assert isinstance(async_client_args["ssl"], ssl.SSLContext) + except ImportError: + assert async_client_args["verify"] + assert isinstance(async_client_args["verify"], ssl.SSLContext) + + +def test_constructor_with_base_url_from_http_options(): + mldev_http_options = { + "base_url": "https://placeholder-fake-url.com/", + } + vertexai_http_options = { + "base_url": ( + "https://{self.location}-aiplatform.googleapis.com/{{api_version}}/" + ), + } + + mldev_client = Client( + api_key="google_api_key", http_options=mldev_http_options + ) + assert not mldev_client.models._api_client.vertexai + assert ( + mldev_client.models._api_client.get_read_only_http_options()["base_url"] + == "https://placeholder-fake-url.com/" + ) + + vertexai_client = Client( + vertexai=True, + project="fake_project_id", + location="fake-location", + http_options=vertexai_http_options, + ) + assert vertexai_client.models._api_client.vertexai + assert ( + vertexai_client.models._api_client.get_read_only_http_options()[ + "base_url" + ] + == "https://{self.location}-aiplatform.googleapis.com/{{api_version}}/" + ) + + +def test_constructor_with_base_url_from_set_default_base_urls(): + base_url.set_default_base_urls( + gemini_url="https://gemini-base-url.com/", + vertex_url="https://vertex-base-url.com/", + ) + mldev_client = Client(api_key="google_api_key") + assert not mldev_client.models._api_client.vertexai + assert ( + mldev_client.models._api_client.get_read_only_http_options()["base_url"] + == "https://gemini-base-url.com/" + ) + + vertexai_client = Client( + vertexai=True, + project="fake_project_id", + location="fake-location", + ) + assert vertexai_client.models._api_client.vertexai + assert ( + vertexai_client.models._api_client.get_read_only_http_options()[ + "base_url" + ] + == "https://vertex-base-url.com/" + ) + base_url.set_default_base_urls(gemini_url=None, vertex_url=None) + + +def test_constructor_with_constructor_base_url_overrides_set_default_base_urls(): + mldev_http_options = { + "base_url": "https://gemini-constructor-base-url.com/", + } + vertexai_http_options = { + "base_url": "https://vertex-constructor-base-url.com/", + } + + base_url.set_default_base_urls( + gemini_url="https://gemini-base-url.com/", + vertex_url="https://vertex-base-url.com/", + ) + mldev_client = Client( + api_key="google_api_key", http_options=mldev_http_options + ) + assert not mldev_client.models._api_client.vertexai + assert ( + mldev_client.models._api_client.get_read_only_http_options()["base_url"] + == "https://gemini-constructor-base-url.com/" + ) + + vertexai_client = Client( + vertexai=True, + project="fake_project_id", + location="fake-location", + http_options=vertexai_http_options, + ) + assert vertexai_client.models._api_client.vertexai + assert ( + vertexai_client.models._api_client.get_read_only_http_options()[ + "base_url" + ] + == "https://vertex-constructor-base-url.com/" + ) + base_url.set_default_base_urls(gemini_url=None, vertex_url=None) + + +def test_constructor_with_constructor_base_url_overrides_environment_variables( + monkeypatch, +): + monkeypatch.setenv( + "GOOGLE_GEMINI_BASE_URL", "https://gemini-env-base-url.com/" + ) + monkeypatch.setenv( + "GOOGLE_VERTEX_BASE_URL", "https://vertex-env-base-url.com/" + ) + + mldev_http_options = { + "base_url": "https://gemini-constructor-base-url.com/", + } + vertexai_http_options = { + "base_url": "https://vertex-constructor-base-url.com/", + } + + mldev_client = Client( + api_key="google_api_key", http_options=mldev_http_options + ) + assert not mldev_client.models._api_client.vertexai + assert ( + mldev_client.models._api_client.get_read_only_http_options()["base_url"] + == "https://gemini-constructor-base-url.com/" + ) + + vertexai_client = Client( + vertexai=True, + project="fake_project_id", + location="fake-location", + http_options=vertexai_http_options, + ) + assert vertexai_client.models._api_client.vertexai + assert ( + vertexai_client.models._api_client.get_read_only_http_options()[ + "base_url" + ] + == "https://vertex-constructor-base-url.com/" + ) + base_url.set_default_base_urls(gemini_url=None, vertex_url=None) + + +def test_constructor_with_base_url_from_set_default_base_urls_overrides_environment_variables( + monkeypatch, +): + monkeypatch.setenv( + "GOOGLE_GEMINI_BASE_URL", "https://gemini-env-base-url.com/" + ) + monkeypatch.setenv( + "GOOGLE_VERTEX_BASE_URL", "https://vertex-env-base-url.com/" + ) + + base_url.set_default_base_urls( + gemini_url="https://gemini-base-url.com/", + vertex_url="https://vertex-base-url.com/", + ) + mldev_client = Client(api_key="google_api_key") + assert not mldev_client.models._api_client.vertexai + assert ( + mldev_client.models._api_client.get_read_only_http_options()["base_url"] + == "https://gemini-base-url.com/" + ) + + vertexai_client = Client( + vertexai=True, + project="fake_project_id", + location="fake-location", + ) + assert vertexai_client.models._api_client.vertexai + assert ( + vertexai_client.models._api_client.get_read_only_http_options()[ + "base_url" + ] + == "https://vertex-base-url.com/" + ) + base_url.set_default_base_urls(gemini_url=None, vertex_url=None) + + +def test_constructor_with_base_url_from_environment_variables(monkeypatch): + monkeypatch.setenv("GOOGLE_GEMINI_BASE_URL", "https://gemini-base-url.com/") + monkeypatch.setenv("GOOGLE_VERTEX_BASE_URL", "https://vertex-base-url.com/") + + mldev_client = Client(api_key="google_api_key") + assert not mldev_client.models._api_client.vertexai + assert ( + mldev_client.models._api_client.get_read_only_http_options()["base_url"] + == "https://gemini-base-url.com/" + ) + + vertexai_client = Client( + vertexai=True, + project="fake_project_id", + location="fake-location", + ) + assert vertexai_client.models._api_client.vertexai + assert ( + vertexai_client.models._api_client.get_read_only_http_options()[ + "base_url" + ] + == "https://vertex-base-url.com/" + ) + + +def test_async_transport_absence_allows_aiohttp_to_be_used(): + client = Client( + vertexai=True, + project="fake_project_id", + location="fake-location", + ) + + api_client.has_aiohttp = False + assert not client._api_client._use_aiohttp() + + api_client.has_aiohttp = True + assert client._api_client._use_aiohttp() + + +def test_async_async_client_args_without_transport_allows_aiohttp_to_be_used(): + client = Client( + vertexai=True, + project="fake_project_id", + location="fake-location", + http_options=types.HttpOptions(async_client_args={}), + ) + + api_client.has_aiohttp = False + assert not client._api_client._use_aiohttp() + + api_client.has_aiohttp = True + assert client._api_client._use_aiohttp() + + +def test_async_transport_forces_httpx_regardless_of_aiohttp_availability(): + + client = Client( + vertexai=True, + project="fake_project_id", + location="fake-location", + http_options=types.HttpOptions( + async_client_args={"transport": httpx.AsyncBaseTransport()} + ), + ) + + api_client.has_aiohttp = False + assert not client._api_client._use_aiohttp() + + api_client.has_aiohttp = True + assert not client._api_client._use_aiohttp() + + +@pytest.mark.asyncio +async def test_get_async_auth_lock_basic_functionality(): + """Tests that _get_async_auth_lock returns an asyncio.Lock.""" + client = Client( + vertexai=True, project="fake_project_id", location="fake-location" + ) + + lock = await client._api_client._get_async_auth_lock() + assert isinstance(lock, asyncio.Lock) + assert client._api_client._async_auth_lock is lock + + +@pytest.mark.asyncio +async def test_get_async_auth_lock_returns_same_instance(): + """Tests that multiple calls return the same lock instance.""" + client = Client( + vertexai=True, project="fake_project_id", location="fake-location" + ) + lock1 = await client._api_client._get_async_auth_lock() + lock2 = await client._api_client._get_async_auth_lock() + lock3 = await client._api_client._get_async_auth_lock() + assert lock1 is lock2 + assert lock2 is lock3 + assert isinstance(lock1, asyncio.Lock) + + +def test_threaded_generate_content_locking(monkeypatch): + """Tests that synchronous API calls are thread-safe.""" + monkeypatch.delenv("GOOGLE_GENAI_CLIENT_MODE", raising=False) + # Mock credentials + mock_creds = mock.Mock(spec=credentials.Credentials) + mock_creds.token = "initial-token" + mock_creds.expired = False + mock_creds.quota_project_id = None + + # Mock google.auth.default + mock_auth_default = mock.Mock(return_value=(mock_creds, "test-project")) + monkeypatch.setattr(google.auth, "default", mock_auth_default) + + # Mock Credentials.refresh + def refresh_side_effect(request): + mock_creds.token = "refreshed-token" + mock_creds.expired = False + + mock_refresh = mock.Mock(side_effect=refresh_side_effect) + mock_creds.refresh = mock_refresh + + client = Client( + vertexai=True, project="fake_project_id", location="fake-location" + ) + # Mock the actual request to avoid network calls + if client._api_client._use_google_auth_sync(): + # Cloud environment enables mTLS and uses requests.Response + mock_http_response = requests.Response() + mock_http_response.status_code = 200 + mock_http_response.headers = {} + mock_http_response._content = ( + b'{"candidates": [{"content": {"parts": [{"text": "response"}]}}]}' + ) + mock_request = mock.Mock(return_value=mock_http_response) + monkeypatch.setattr( + google.auth.transport.requests.AuthorizedSession, "request", mock_request + ) + else: + # Non-cloud environment w/o certificates uses httpx.Response + mock_httpx_response = httpx.Response( + status_code=200, + headers={}, + text='{"candidates": [{"content": {"parts": [{"text": "response"}]}}]}', + ) + mock_request = mock.Mock(return_value=mock_httpx_response) + monkeypatch.setattr(api_client.SyncHttpxClient, "send", mock_request) + + # Reset credentials to test initialization to ensure the sync lock is tested. + client._api_client._credentials = None + + # 1. Test initial credential loading in multiple threads + with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor: + futures = [ + executor.submit( + client.models.generate_content, model="gemini-pro", contents=str(i) + ) + for i in range(10) + ] + for future in concurrent.futures.as_completed(futures): + assert future.result().text == "response" + + mock_auth_default.assert_called_once() + mock_refresh.assert_not_called() + assert len(mock_request.call_args_list) == 10 + + # 2. Test credential refreshing in multiple threads + mock_creds.expired = True + with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor: + futures = [ + executor.submit( + client.models.generate_content, model="gemini-pro", contents=str(i) + ) + for i in range(10) + ] + for future in concurrent.futures.as_completed(futures): + assert future.result().text == "response" + + mock_auth_default.assert_called_once() + mock_refresh.assert_called_once() + assert len(mock_request.call_args_list) == 20 + + +@pytest.mark.asyncio +async def test_async_access_token_locking(monkeypatch): + """Tests that _async_access_token uses locks to prevent race conditions.""" + # Mock credentials + mock_creds = mock.Mock(spec=credentials.Credentials) + mock_creds.token = "initial-token" + mock_creds.expired = False + mock_creds.quota_project_id = None + + # Mock google.auth.default + mock_auth_default = mock.Mock(return_value=(mock_creds, "test-project")) + monkeypatch.setattr(google.auth, "default", mock_auth_default) + + # Mock Credentials.refresh + def refresh_side_effect(request): + mock_creds.token = "refreshed-token" + mock_creds.expired = False + + mock_refresh = mock.Mock(side_effect=refresh_side_effect) + mock_creds.refresh = mock_refresh + + client = Client( + vertexai=True, project="fake_project_id", location="fake-location" + ) + # Reset credentials to test initialization to ensure the async lock is tested. + client._api_client._credentials = None + + # 1. Test initial credential loading + # Running them concurrently should result in only one call to load_auth. + tokens = await asyncio.gather( + client._api_client._async_access_token(), + client._api_client._async_access_token(), + client._api_client._async_access_token(), + ) + + assert tokens == ["initial-token", "initial-token", "initial-token"] + mock_auth_default.assert_called_once() + mock_refresh.assert_not_called() + + # 2. Test credential refreshing + # Now the token is "expired", so the next call should refresh it. + mock_creds.expired = True + + # Running them concurrently should result in only one call to refresh. + tokens = await asyncio.gather( + client._api_client._async_access_token(), + client._api_client._async_access_token(), + client._api_client._async_access_token(), + ) + + assert tokens == ["refreshed-token", "refreshed-token", "refreshed-token"] + # google.auth.default should still have been called only once in total. + mock_auth_default.assert_called_once() + mock_refresh.assert_called_once() + + +@pytest.mark.asyncio +async def test_get_async_auth_lock_concurrent_access(): + """Tests that concurrent access to _get_async_auth_lock is thread-safe.""" + client = Client( + vertexai=True, project="fake_project_id", location="fake-location" + ) + + # Run multiple concurrent calls + async def get_lock_task(task_id: int): + lock = await client._api_client._get_async_auth_lock() + return task_id, id(lock) + + tasks = [get_lock_task(i) for i in range(20)] + results = await asyncio.gather(*tasks) + + # All tasks should get the same lock instance + lock_ids = [result[1] for result in results] + assert all( + lock_id == lock_ids[0] for lock_id in lock_ids + ), "All tasks should get the same lock instance" + + # All tasks should complete + task_ids = [result[0] for result in results] + assert sorted(task_ids) == list(range(20)), "All tasks should complete" + + +@pytest.mark.asyncio +async def test_get_async_auth_lock_doesnt_block_other_operations(): + """Tests that _get_async_auth_lock doesn't interfere with other async operations.""" + client = Client( + vertexai=True, project="fake_project_id", location="fake-location" + ) + + # Track completion of other async operations + completed_operations = [] + + async def mock_async_operation(op_id: int): + await asyncio.sleep(0.01) # Small delay to simulate async work + completed_operations.append(op_id) + return f"operation_{op_id}" + + # Start auth lock requests and other operations simultaneously + start_time = asyncio.get_event_loop().time() + + auth_tasks = [client._api_client._get_async_auth_lock() for _ in range(10)] + work_tasks = [mock_async_operation(i) for i in range(15)] + + auth_results, work_results = await asyncio.gather( + asyncio.gather(*auth_tasks), asyncio.gather(*work_tasks) + ) + + end_time = asyncio.get_event_loop().time() + total_time = end_time - start_time + + # Verify all operations completed + assert len(auth_results) == 10, "All auth lock requests should complete" + assert len(work_results) == 15, "All work tasks should complete" + assert len(completed_operations) == 15, "All async operations should complete" + + # All auth requests should return the same lock + lock_ids = [id(lock) for lock in auth_results] + assert all(lock_id == lock_ids[0] for lock_id in lock_ids) + + # Should complete quickly since operations run concurrently + assert total_time < 0.1, ( + f"Operations took too long ({total_time:.3f}s), suggesting blocking" + " occurred" + ) + + +@pytest.mark.asyncio +async def test_get_async_auth_lock_creation_lock_lifecycle(): + """Tests the creation lock lifecycle and cleanup.""" + client = Client( + vertexai=True, project="fake_project_id", location="fake-location" + ) + + # Initially, both locks should be None + assert client._api_client._async_auth_lock is None + assert client._api_client._async_auth_lock_creation_lock is None + + # After first call, both should exist + lock1 = await client._api_client._get_async_auth_lock() + assert client._api_client._async_auth_lock is not None + assert client._api_client._async_auth_lock_creation_lock is not None + assert isinstance(lock1, asyncio.Lock) + + # Creation lock should be different from the auth lock + creation_lock = client._api_client._async_auth_lock_creation_lock + assert creation_lock is not lock1 + assert isinstance(creation_lock, asyncio.Lock) + + # Subsequent calls should reuse both locks + lock2 = await client._api_client._get_async_auth_lock() + assert lock2 is lock1 + assert client._api_client._async_auth_lock_creation_lock is creation_lock + + +@pytest.mark.asyncio +async def test_get_async_auth_lock_under_load(): + """Tests _get_async_auth_lock under heavy concurrent load.""" + client = Client( + vertexai=True, project="fake_project_id", location="fake-location" + ) + + num_concurrent_calls = 100 + + async def get_lock_with_timing(call_id: int): + start = asyncio.get_event_loop().time() + lock = await client._api_client._get_async_auth_lock() + end = asyncio.get_event_loop().time() + return call_id, id(lock), end - start + + # Run many concurrent calls + start_time = asyncio.get_event_loop().time() + tasks = [get_lock_with_timing(i) for i in range(num_concurrent_calls)] + results = await asyncio.gather(*tasks) + total_time = asyncio.get_event_loop().time() - start_time + + # Verify all calls succeeded and got the same lock + call_ids = [r[0] for r in results] + lock_ids = [r[1] for r in results] + call_times = [r[2] for r in results] + + assert len(results) == num_concurrent_calls + assert sorted(call_ids) == list(range(num_concurrent_calls)) + assert all( + lock_id == lock_ids[0] for lock_id in lock_ids + ), "All calls should get same lock" + + # Performance checks + max_call_time = max(call_times) + assert total_time < 1.0, f"Total time ({total_time:.3f}s) suggests blocking" + assert ( + max_call_time < 0.1 + ), f"Max individual call time ({max_call_time:.3f}s) too high" + + +@pytest.mark.asyncio +async def test_get_async_auth_lock_interleaved_with_auth_operations(): + """Tests _get_async_auth_lock working correctly with actual auth operations.""" + client = Client( + vertexai=True, project="fake_project_id", location="fake-location" + ) + + # Mock credentials for this test + mock_creds = mock.Mock(spec=credentials.Credentials) + mock_creds.token = "test-token" + mock_creds.expired = False + mock_creds.quota_project_id = None + client._api_client._credentials = mock_creds + + # Mix lock requests with simulated auth operations + async def auth_operation(op_id: int): + # This simulates what _async_access_token does + lock = await client._api_client._get_async_auth_lock() + async with lock: + await asyncio.sleep(0.001) # Simulate auth work + return f"auth_op_{op_id}" + + async def lock_request(req_id: int): + lock = await client._api_client._get_async_auth_lock() + return req_id, id(lock) + + # Interleave different types of operations + auth_tasks = [auth_operation(i) for i in range(10)] + lock_tasks = [lock_request(i) for i in range(10)] + + auth_results, lock_results = await asyncio.gather( + asyncio.gather(*auth_tasks), asyncio.gather(*lock_tasks) + ) + + # Verify all operations completed + assert len(auth_results) == 10 + assert len(lock_results) == 10 + + # All lock requests should return the same lock ID + lock_ids = [result[1] for result in lock_results] + assert all(lock_id == lock_ids[0] for lock_id in lock_ids) + + # Auth operations should complete successfully + assert all(result.startswith("auth_op_") for result in auth_results) + + +@pytest.mark.asyncio +async def test_get_async_auth_lock_with_event_loop_switch(): + """Tests that _get_async_auth_lock works correctly with event loop context.""" + + async def create_client_and_get_lock(): + client = Client( + vertexai=True, project="fake_project_id", location="fake-location" + ) + lock = await client._api_client._get_async_auth_lock() + return client, lock + + # Create client and get lock in current event loop + client, lock1 = await create_client_and_get_lock() + + # Get lock again in same event loop + lock2 = await client._api_client._get_async_auth_lock() + + assert lock1 is lock2 + assert isinstance(lock1, asyncio.Lock) + + # Verify the locks work correctly + async def test_lock_functionality(): + async with lock1: + await asyncio.sleep(0.001) + return "success" + + result = await test_lock_functionality() + assert result == "success" + + +@pytest.mark.asyncio +async def test_get_async_auth_lock_double_checked_locking(): + """Tests the double-checked locking pattern implementation.""" + client = Client( + vertexai=True, project="fake_project_id", location="fake-location" + ) + + original_lock_init = asyncio.Lock.__init__ + lock_creation_count = [0] + + def counting_lock_init(self): + lock_creation_count[0] += 1 + return original_lock_init(self) + + # Patch asyncio.Lock to count creations + asyncio.Lock.__init__ = counting_lock_init + + try: + # Run many concurrent requests + tasks = [client._api_client._get_async_auth_lock() for _ in range(50)] + locks = await asyncio.gather(*tasks) + + # All should be the same instance + assert all(lock is locks[0] for lock in locks) + + # Should only create 2 locks: creation_lock + auth_lock + # (Could be slightly more due to asyncio internals, but should be minimal) + assert ( + lock_creation_count[0] <= 5 + ), f"Created {lock_creation_count[0]} locks, expected ~2" + + finally: + asyncio.Lock.__init__ = original_lock_init + + +@pytest.mark.asyncio +async def test_get_async_auth_lock_memory_efficiency(): + """Tests that _get_async_auth_lock doesn't leak memory under repeated use.""" + client = Client( + vertexai=True, project="fake_project_id", location="fake-location" + ) + initial_lock = await client._api_client._get_async_auth_lock() + initial_creation_lock = client._api_client._async_auth_lock_creation_lock + + # Run many operations + for _ in range(100): + lock = await client._api_client._get_async_auth_lock() + assert lock is initial_lock + assert ( + client._api_client._async_auth_lock_creation_lock + is initial_creation_lock + ) + # Verify no new objects were created + final_lock = await client._api_client._get_async_auth_lock() + final_creation_lock = client._api_client._async_auth_lock_creation_lock + + assert final_lock is initial_lock + assert final_creation_lock is initial_creation_lock + + +@requires_aiohttp +@pytest.mark.asyncio +async def test_get_aiohttp_session(): + """Tests that _get_async_auth_lock works correctly with aiohttp session lock.""" + + client = Client( + vertexai=True, project="fake_project_id", location="fake-location" + ) + api_client.has_aiohttp = True + initial_session = await client._api_client._get_aiohttp_session() + assert initial_session is not None + session = await client._api_client._get_aiohttp_session() + assert session is initial_session diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/client/test_client_requests.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/client/test_client_requests.py new file mode 100644 index 0000000000000000000000000000000000000000..4bbc3549251c52381becf15b95d3e569777204a7 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/client/test_client_requests.py @@ -0,0 +1,221 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for client behavior when issuing requests.""" + +from ... import _api_client as api_client +from ... import Client +from ... import types + + +def build_test_client(monkeypatch): + monkeypatch.setenv('GOOGLE_API_KEY', 'google_api_key') + return Client() + + +def test_join_url_path_base_url_with_trailing_slash_and_path_with_leading_slash(): + base_url = 'https://fake-url.com/some_path/' + path = '/v1beta/models' + assert ( + api_client.join_url_path(base_url, path) + == 'https://fake-url.com/some_path/v1beta/models' + ) + + +def test_join_url_path_with_base_url_with_trailing_slash_and_path_without_leading_slash(): + base_url = 'https://fake-url.com/some_path/' + path = 'v1beta/models' + assert ( + api_client.join_url_path(base_url, path) + == 'https://fake-url.com/some_path/v1beta/models' + ) + + +def test_join_url_path_with_base_url_without_trailing_slash_and_path_with_leading_slash(): + base_url = 'https://fake-url.com/some_path' + path = '/v1beta/models' + assert ( + api_client.join_url_path(base_url, path) + == 'https://fake-url.com/some_path/v1beta/models' + ) + + +def test_join_url_path_with_base_url_without_trailing_slash_and_path_without_leading_slash(): + base_url = 'https://fake-url.com/some_path' + path = 'v1beta/models' + assert ( + api_client.join_url_path(base_url, path) + == 'https://fake-url.com/some_path/v1beta/models' + ) + + +def test_join_url_path_base_url_without_path_with_trailing_slash(): + base_url = 'https://fake-url.com/' + path = 'v1beta/models' + assert ( + api_client.join_url_path(base_url, path) + == 'https://fake-url.com/v1beta/models' + ) + + +def test_join_url_path_base_url_without_path_without_trailing_slash(): + base_url = 'https://fake-url.com' + path = 'v1beta/models' + assert ( + api_client.join_url_path(base_url, path) + == 'https://fake-url.com/v1beta/models' + ) + + +def test_build_request_sets_library_version_headers(monkeypatch): + request_client = build_test_client(monkeypatch).models._api_client + request = request_client._build_request('GET', 'test/path', {'key': 'value'}) + assert 'google-genai-sdk/' in request.headers['user-agent'] + assert 'gl-python/' in request.headers['user-agent'] + assert 'google-genai-sdk/' in request.headers['x-goog-api-client'] + assert 'gl-python/' in request.headers['x-goog-api-client'] + + +def test_build_request_appends_to_user_agent_headers(monkeypatch): + request_client = build_test_client(monkeypatch).models._api_client + request = request_client._build_request( + 'GET', + 'test/path', + {'key': 'value'}, + types.HttpOptionsDict( + base_url='test/url', + api_version='1', + headers={'user-agent': 'test-user-agent'}, + ), + ) + assert 'test-user-agent' in request.headers['user-agent'] + assert 'google-genai-sdk/' in request.headers['user-agent'] + assert 'gl-python/' in request.headers['user-agent'] + assert 'google-genai-sdk/' in request.headers['x-goog-api-client'] + + +def test_build_request_appends_to_goog_api_client_headers(monkeypatch): + request_client = build_test_client(monkeypatch).models._api_client + request = request_client._build_request( + 'GET', + 'test/path', + {'key': 'value'}, + types.HttpOptionsDict( + base_url='test/url', + api_version='1', + headers={'x-goog-api-client': 'test-goog-api-client'}, + ), + ) + assert 'google-genai-sdk/' in request.headers['user-agent'] + assert 'test-goog-api-client' in request.headers['x-goog-api-client'] + assert 'google-genai-sdk/' in request.headers['x-goog-api-client'] + assert 'gl-python/' in request.headers['x-goog-api-client'] + + +def test_build_request_keeps_sdk_version_headers(monkeypatch): + headers_to_inject = {} + api_client.append_library_version_headers(headers_to_inject) + assert 'google-genai-sdk/' in headers_to_inject['user-agent'] + request_client = build_test_client(monkeypatch).models._api_client + request = request_client._build_request( + 'GET', + 'test/path', + {'key': 'value'}, + types.HttpOptionsDict( + base_url='test/url', + api_version='1', + headers=headers_to_inject, + ), + ) + assert 'google-genai-sdk/' in request.headers['user-agent'] + assert 'gl-python/' in request.headers['x-goog-api-client'] + assert 'google-genai-sdk/' in request.headers['x-goog-api-client'] + assert 'gl-python/' in request.headers['x-goog-api-client'] + + +def test_build_request_with_resource_scope(monkeypatch): + monkeypatch.delenv('GOOGLE_API_KEY', raising=False) + monkeypatch.delenv('GEMINI_API_KEY', raising=False) + monkeypatch.delenv('GOOGLE_CLOUD_PROJECT', raising=False) + monkeypatch.delenv('GOOGLE_CLOUD_LOCATION', raising=False) + + client = Client( + vertexai=True, + http_options=types.HttpOptionsDict( + base_url='https://custom-base-url.com', + base_url_resource_scope=types.ResourceScope.COLLECTION, + ), + ) + + request = client.models._api_client._build_request( + 'post', + 'publishers/google/models/gemini-3-pro-preview', + {'key': 'value'}, + ) + assert request.url == 'https://custom-base-url.com/publishers/google/models/gemini-3-pro-preview' + + +def test_build_request_with_resource_scope_with_project_and_location( + monkeypatch, +): + monkeypatch.delenv('GOOGLE_API_KEY', raising=False) + monkeypatch.delenv('GEMINI_API_KEY', raising=False) + monkeypatch.delenv('GOOGLE_CLOUD_PROJECT', raising=False) + monkeypatch.delenv('GOOGLE_CLOUD_LOCATION', raising=False) + + client = Client( + vertexai=True, + project='test-project', + location='test-location', + http_options=types.HttpOptionsDict( + base_url='https://custom-base-url.com', + base_url_resource_scope=types.ResourceScope.COLLECTION, + ), + ) + + request = client.models._api_client._build_request( + 'post', + 'publishers/google/models/gemini-3-pro-preview', + {'key': 'value'}, + ) + assert request.url == 'https://custom-base-url.com/publishers/google/models/gemini-3-pro-preview' + + + +def build_test_client_no_env_vars(monkeypatch): + monkeypatch.delenv('GOOGLE_API_KEY', raising=False) + monkeypatch.delenv('GEMINI_API_KEY', raising=False) + monkeypatch.delenv('GOOGLE_CLOUD_PROJECT', raising=False) + monkeypatch.delenv('GOOGLE_CLOUD_LOCATION', raising=False) + return Client( + vertexai=True, + http_options=types.HttpOptionsDict( + base_url='https://custom-base-url.com', + headers={'Authorization': 'Bearer fake_access_token'}, + ), + ) + + +def test_build_request_with_custom_base_url_no_env_vars(monkeypatch): + request_client = ( + build_test_client_no_env_vars(monkeypatch).models._api_client + ) + request = request_client._build_request( + 'GET', + 'test/path', + {'key': 'value'}, + ) + assert request.url == 'https://custom-base-url.com' \ No newline at end of file diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/client/test_custom_client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/client/test_custom_client.py new file mode 100644 index 0000000000000000000000000000000000000000..ebb360ea27922237b7d06636f16985f0e40a57ac --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/client/test_custom_client.py @@ -0,0 +1,104 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +"""Tests for custom clients.""" +import asyncio +from unittest import mock + +from google.oauth2 import credentials +import httpx +import pytest + +from ... import _api_client as api_client +from ... import Client + + +try: + import aiohttp + + AIOHTTP_NOT_INSTALLED = False +except ImportError: + AIOHTTP_NOT_INSTALLED = True + aiohttp = mock.MagicMock() + +requires_aiohttp = pytest.mark.skipif( + AIOHTTP_NOT_INSTALLED, reason='aiohttp is not installed, skipping test.' +) + + +# Httpx +def test_constructor_with_httpx_clients(): + mldev_http_options = { + 'httpx_client': httpx.Client(trust_env=False), + 'httpx_async_client': httpx.AsyncClient(trust_env=False), + } + vertexai_http_options = { + 'httpx_client': httpx.Client(trust_env=False), + 'httpx_async_client': httpx.AsyncClient(trust_env=False), + } + + # Even if aiohttp is installed, expect it to be disabled when httpx clients + # are provided. + api_client.has_aiohttp = True + + mldev_client = Client( + api_key='google_api_key', http_options=mldev_http_options + ) + assert not mldev_client.models._api_client._httpx_client.trust_env + assert not mldev_client.models._api_client._async_httpx_client.trust_env + # Expect aiohttp to be disabled when httpx clients are provided, regardless of + # whether aiohttp is installed. + assert not mldev_client.models._api_client._use_aiohttp() + + vertexai_client = Client( + vertexai=True, + project='fake_project_id', + location='fake-location', + http_options=vertexai_http_options, + ) + assert not vertexai_client.models._api_client._httpx_client.trust_env + assert not vertexai_client.models._api_client._async_httpx_client.trust_env + # Expect aiohttp to be disabled when httpx clients are provided, regardless of + # whether aiohttp is installed. + assert not mldev_client.models._api_client._use_aiohttp() + + +# Aiohttp +@requires_aiohttp +@pytest.mark.asyncio +@pytest.mark.skipif( + AIOHTTP_NOT_INSTALLED, reason='aiohttp is not installed, skipping test.' +) +async def test_constructor_with_aiohttp_clients(): + api_client.has_aiohttp = True + mldev_http_options = { + 'aiohttp_client': aiohttp.ClientSession(trust_env=False), + } + vertexai_http_options = { + 'aiohttp_client': aiohttp.ClientSession(trust_env=False), + } + mldev_client = Client( + api_key='google_api_key', http_options=mldev_http_options + ) + assert not mldev_client.models._api_client._aiohttp_session.trust_env + + vertexai_client = Client( + vertexai=True, + project='fake_project_id', + location='fake-location', + http_options=vertexai_http_options, + ) + assert not vertexai_client.models._api_client._aiohttp_session.trust_env + diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/client/test_http_options.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/client/test_http_options.py new file mode 100644 index 0000000000000000000000000000000000000000..e27808142deb19a350c203959131b7148b217843 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/client/test_http_options.py @@ -0,0 +1,182 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for client behavior when issuing requests.""" + +import pytest + +from ... import _api_client +from ... import types + + +def test_patch_http_options_with_copies_all_fields(): + patch_options = types.HttpOptions( + base_url='https://fake-url.com/', + api_version='v1', + headers={'X-Custom-Header': 'custom_value'}, + timeout=10000, + client_args={'http2': True}, + async_client_args={'http1': True}, + extra_body={'key': 'value'}, + retry_options=types.HttpRetryOptions(attempts=10), + base_url_resource_scope=types.ResourceScope.COLLECTION, + ) + options = types.HttpOptions() + patched = _api_client.patch_http_options(options, patch_options) + http_options_keys = types.HttpOptions.model_fields.keys() + + for key in http_options_keys: + assert hasattr(patched, key) + if key not in [ + 'httpx_client', + 'httpx_async_client', + 'aiohttp_client', + ]: + assert getattr(patched, key) is not None + assert patched.base_url == 'https://fake-url.com/' + assert patched.api_version == 'v1' + assert patched.headers['X-Custom-Header'] == 'custom_value' + assert patched.timeout == 10000 + assert patched.retry_options.attempts == 10 + assert patched.client_args['http2'] + assert patched.async_client_args['http1'] + + +def test_patch_http_options_merges_headers(): + original_options = types.HttpOptions( + headers={ + 'X-Custom-Header': 'different_value', + 'X-different-header': 'different_value', + } + ) + patch_options = types.HttpOptions( + base_url='https://fake-url.com/', + api_version='v1', + headers={'X-Custom-Header': 'custom_value'}, + timeout=10000, + ) + patched = _api_client.patch_http_options(original_options, patch_options) + # If the header is present in both the original and patch options, the patch + # options value should be used + assert patched.headers['X-Custom-Header'] == 'custom_value' + assert patched.headers['X-different-header'] == 'different_value' + assert patched.base_url == 'https://fake-url.com/' + assert patched.api_version == 'v1' + assert patched.timeout == 10000 + + +def test_patch_http_options_appends_version_headers(): + original_options = types.HttpOptions( + headers={ + 'X-Custom-Header': 'different_value', + 'X-different-header': 'different_value', + } + ) + patch_options = types.HttpOptions( + base_url='https://fake-url.com/', + api_version='v1', + headers={'X-Custom-Header': 'custom_value'}, + timeout=10000, + ) + patched = _api_client.patch_http_options(original_options, patch_options) + assert 'user-agent' in patched.headers + assert 'x-goog-api-client' in patched.headers + + +def test_setting_timeout_populates_server_timeout_header(): + api_client = _api_client.BaseApiClient( + vertexai=False, + api_key='test_api_key', + http_options=types.HttpOptions(timeout=10000), + ) + request = api_client._build_request( + http_method='POST', + path='sample/path', + request_dict={}, + ) + assert 'X-Server-Timeout' in request.headers + assert request.headers['X-Server-Timeout'] == '10' + + +def test_timeout_rounded_to_nearest_second(): + api_client = _api_client.BaseApiClient( + vertexai=False, + api_key='test_api_key', + ) + http_options = types.HttpOptions(timeout=7300) + request = api_client._build_request( + http_method='POST', + path='sample/path', + request_dict={}, + http_options=http_options, + ) + assert request.headers['X-Server-Timeout'] == '8' + + +def test_server_timeout_not_overwritten(): + api_client = _api_client.BaseApiClient( + vertexai=False, + api_key='test_api_key', + ) + http_options = types.HttpOptions( + headers={'X-Server-Timeout': '3'}, + timeout=11000) + request = api_client._build_request( + http_method='POST', + path='sample/path', + request_dict={}, + http_options=http_options, + ) + assert request.headers['X-Server-Timeout'] == '3' + + +def test_server_timeout_not_set_by_default(): + api_client = _api_client.BaseApiClient( + vertexai=False, + api_key='test_api_key', + ) + request = api_client._build_request( + http_method='POST', + path='sample/path', + request_dict={}, + ) + assert not 'X-Server-Timeout' in request.headers + + +def test_resource_scope_without_base_url_raises_error(): + with pytest.raises(ValueError): + _api_client.BaseApiClient( + vertexai=True, + http_options=types.HttpOptions( + base_url_resource_scope=types.ResourceScope.COLLECTION, + ), + ) + + +def test_base_url_resource_scope_not_set_by_default(): + api_client = _api_client.BaseApiClient( + vertexai=True, + http_options=types.HttpOptions( + base_url='https://fake-url.com/', + ), + ) + + assert api_client._http_options.base_url_resource_scope is None + + +def test_retry_options_not_set_by_default(): + options = types.HttpOptions() + assert options.retry_options is None diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/client/test_replay_client_equality.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/client/test_replay_client_equality.py new file mode 100644 index 0000000000000000000000000000000000000000..893c02c9f1c7798da13ef93eab4b9a250d88e515 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/client/test_replay_client_equality.py @@ -0,0 +1,168 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests replay client correctly compares requests ignoring key casing.""" + +from ... import _replay_api_client +from ... import types + + +def test_equal_objects_with_same_casing_returns_true(): + obj1 = [{ + 'contents': [{'parts': [{'text': 'What is your name?'}], 'role': 'user'}], + 'generationConfig': {'topK': 2.0, 'maxOutputTokens': 3}, + }] + obj2 = [{ + 'contents': [{'parts': [{'text': 'What is your name?'}], 'role': 'user'}], + 'generationConfig': {'topK': 2.0, 'maxOutputTokens': 3}, + }] + + assert _replay_api_client._equals_ignore_key_case(obj1, obj2) + + +def test_equal_objects_with_different_casing_returns_true(): + obj1 = [{ + 'contents': [{'parts': [{'text': 'What is your name?'}], 'role': 'user'}], + 'generationConfig': {'topK': 2.0, 'maxOutputTokens': 3}, + }] + obj2 = [{ + 'contents': [{'parts': [{'text': 'What is your name?'}], 'role': 'user'}], + 'generation_config': {'topK': 2.0, 'max_output_tokens': 3}, + }] + + assert _replay_api_client._equals_ignore_key_case(obj1, obj2) + + +def test_equal_objects_with_different_nested_casing_returns_true(): + obj1 = [{ + 'contents': [{'parts': [{'text': 'What is your name?'}], 'role': 'user'}], + 'generationConfig': {'topK': 2.0, 'maxOutputTokens': 3}, + }] + obj2 = [{ + 'contents': [{'parts': [{'text': 'What is your name?'}], 'role': 'user'}], + 'generationConfig': {'top_k': 2.0, 'maxOutputTokens': 3}, + }] + + assert _replay_api_client._equals_ignore_key_case(obj1, obj2) + +def test_equal_int_float_values_returns_true(): + obj1 = [{ + 'contents': [{'parts': [{'text': 'What is your name?'}], 'role': 'user'}], + 'generationConfig': {'topK': 2.0, 'maxOutputTokens': 3}, + }] + obj2 = [{ + 'contents': [{'parts': [{'text': 'What is your name?'}], 'role': 'user'}], + 'generation_config': {'topK': 2, 'max_output_tokens': 3}, + }] + + assert _replay_api_client._equals_ignore_key_case(obj1, obj2) + + +def test_equal_enum_string_values_returns_true(): + obj1 = [{ + 'contents': [{'parts': [{'text': 'What is your name?'}], 'role': 'user'}], + 'generationConfig': { + 'topK': 2.0, + 'maxOutputTokens': 3, + 'type': types.Type.STRING, + }, + }] + obj2 = [{ + 'contents': [{'parts': [{'text': 'What is your name?'}], 'role': 'user'}], + 'generation_config': { + 'topK': 2, + 'max_output_tokens': 3, + 'type': 'STRING', + }, + }] + + assert _replay_api_client._equals_ignore_key_case(obj1, obj2) + + +def test_equal_enum_values_returns_true(): + obj1 = [{ + 'contents': [{'parts': [{'text': 'What is your name?'}], 'role': 'user'}], + 'generationConfig': { + 'topK': 2.0, + 'maxOutputTokens': 3, + 'type': types.Type.STRING, + }, + }] + obj2 = [{ + 'contents': [{'parts': [{'text': 'What is your name?'}], 'role': 'user'}], + 'generation_config': { + 'topK': 2, + 'max_output_tokens': 3, + 'type': types.Type.STRING, + }, + }] + + assert _replay_api_client._equals_ignore_key_case(obj1, obj2) + + +def test_different_number_value_returns_false(): + obj1 = [{ + 'contents': [{'parts': [{'text': 'What is your name?'}], 'role': 'user'}], + 'generationConfig': {'topK': 3, 'maxOutputTokens': 3}, + }] + obj2 = [{ + 'contents': [{'parts': [{'text': 'What is your name?'}], 'role': 'user'}], + 'generation_config': {'topK': 2.0, 'max_output_tokens': 3}, + }] + + assert not _replay_api_client._equals_ignore_key_case( + obj1, obj2 + ) + + +def test_different_string_value_returns_false(): + obj1 = [{ + 'contents': [{'parts': [{'text': 'What is your name?'}], 'role': 'user'}], + 'generationConfig': {'topK': 3, 'maxOutputTokens': 3}, + }] + obj2 = [{ + 'contents': [ + {'parts': [{'text': 'What is your name?'}], 'role': 'model'} + ], + 'generation_config': {'topK': 3, 'max_output_tokens': 3}, + }] + + assert not _replay_api_client._equals_ignore_key_case( + obj1, obj2 + ) + + +def test_different_enum_values_returns_false(): + obj1 = [{ + 'contents': [{'parts': [{'text': 'What is your name?'}], 'role': 'user'}], + 'generationConfig': { + 'topK': 2.0, + 'maxOutputTokens': 3, + 'type': types.Type.STRING, + }, + }] + obj2 = [{ + 'contents': [{'parts': [{'text': 'What is your name?'}], 'role': 'user'}], + 'generation_config': { + 'topK': 2, + 'max_output_tokens': 3, + 'type': types.Type.OBJECT, + }, + }] + + assert not _replay_api_client._equals_ignore_key_case( + obj1, obj2 + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/client/test_retries.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/client/test_retries.py new file mode 100644 index 0000000000000000000000000000000000000000..49af5264b020069d6f6ed96638de6eae1259d6d4 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/client/test_retries.py @@ -0,0 +1,1363 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +"""Tests for http retries.""" + +import asyncio +from collections.abc import Sequence +import datetime +from unittest import mock +import pytest + +try: + import aiohttp + from google.auth.aio.transport.aiohttp import Response as AsyncAuthorizedSessionResponse + from google.auth.aio.transport.sessions import AsyncAuthorizedSession + from google.auth.aio.credentials import StaticCredentials + + AIOHTTP_NOT_INSTALLED = False +except ImportError: + AIOHTTP_NOT_INSTALLED = True + aiohttp = mock.MagicMock() + AsyncAuthorizedSessionResponse = mock.MagicMock() + StaticCredentials = mock.MagicMock() + AsyncAuthorizedSession = mock.MagicMock() + +from google.oauth2 import credentials +import httpx +import tenacity + +from ... import _api_client as api_client +from ... import errors +from ... import types + + +requires_aiohttp = pytest.mark.skipif( + AIOHTTP_NOT_INSTALLED, reason="aiohttp is not installed, skipping test." +) + + +_RETRIED_CODES = ( + 408, # Request timeout. + 429, # Too many requests. + 500, # Internal server error. + 502, # Bad gateway. + 503, # Service unavailable. + 504, # Gateway timeout. +) + + +@pytest.fixture(autouse=True) +def reset_has_aiohttp(): + yield + api_client.has_aiohttp = False + + +def _final_codes(retried_codes: Sequence[int] = _RETRIED_CODES): + return [code for code in range(100, 600) if code not in retried_codes] + + +def _httpx_response(code: int): + return httpx.Response( + status_code=code, + headers={'status-code': str(code)}, + content=b'', + ) + + +# Args + + +def test_retry_args_disabled(): + args = api_client.retry_args(None) + + assert set(args.keys()) == {'stop', 'reraise'} + assert args['stop'].max_attempt_number == 1 + assert args['reraise'] + + +def test_retry_args_enabled_with_defaults(): + # Empty options means use the default values whereas None means no retries. + args = api_client.retry_args(types.HttpRetryOptions()) + + assert set(args.keys()) == { + 'stop', + 'retry', + 'wait', + 'reraise', + 'before_sleep', + } + + assert args['stop'].max_attempt_number == 5 + + wait = args['wait'] + assert wait.exp_base == 2 + assert wait.initial == 1 + assert wait.jitter == 1 + assert wait.max == 60 + + retry = args['retry'] + for code in _RETRIED_CODES: + try: + errors.APIError.raise_for_response(_httpx_response(code)) + assert False, 'Expected APIError to be raised.' + except errors.APIError as e: + assert retry.predicate(e) + + for code in _final_codes(): + try: + errors.APIError.raise_for_response(_httpx_response(code)) + # Does not raise for some codes. + except errors.APIError as e: + # Does not retry for error codes outside of the retried codes list. + assert not retry.predicate(e) + + assert args['reraise'] + + +def test_retry_wait(): + timestamps = [] + + def fn(): + now = datetime.datetime.now() + timestamps.append(now) + raise errors.APIError.raise_for_response(_httpx_response(429)) + + retrying = tenacity.Retrying( + **api_client.retry_args(types.HttpRetryOptions()) + ) + + try: + retrying(fn) + assert False, 'Expected APIError to be raised.' + except errors.APIError: + pass + + assert len(timestamps) == 5 + assert timestamps[1] - timestamps[0] >= datetime.timedelta(seconds=1) + assert timestamps[2] - timestamps[1] >= datetime.timedelta(seconds=2) + assert timestamps[3] - timestamps[2] >= datetime.timedelta(seconds=4) + assert timestamps[4] - timestamps[3] >= datetime.timedelta(seconds=8) + + +def test_retry_args_enabled_with_custom_values_are_not_overridden(): + options = types.HttpRetryOptions( + attempts=10, + initial_delay=10, + max_delay=100, + exp_base=1.5, + jitter=0.5, + http_status_codes=[408, 429], + ) + retry_args = api_client.retry_args(options) + assert retry_args['stop'].max_attempt_number == 10 + + wait = retry_args['wait'] + assert wait.initial == 10 + assert wait.max == 100 + assert wait.exp_base == 1.5 + assert wait.jitter == 0.5 + + retry = retry_args['retry'] + for code in [408, 429]: + try: + errors.APIError.raise_for_response(_httpx_response(code)) + assert False, 'Expected APIError to be raised.' + except errors.APIError as e: + assert retry.predicate(e) + + for code in _final_codes([408, 429]): + try: + errors.APIError.raise_for_response(_httpx_response(code)) + # Does not raise for some codes. + except errors.APIError as e: + # Does not retry for error codes outside of the retried codes list. + assert not retry.predicate(e) + + +def _patch_auth_default(): + return mock.patch( + 'google.auth.default', + return_value=(credentials.Credentials('magic_token'), 'test_project'), + autospec=True, + ) + + +def _transport_options(http_options=None, transport=None, async_transport=None): + http_options = http_options or types.HttpOptions() + http_options.client_args = {'transport': transport} + http_options.async_client_args = {'transport': async_transport} + return http_options + + +# Sync + + +def test_disabled_retries_successful_request_executes_once(): + mock_transport = mock.Mock(spec=httpx.BaseTransport) + mock_transport.handle_request.return_value = _httpx_response(200) + + client = api_client.BaseApiClient( + vertexai=True, + project='test_project', + location='global', + http_options=_transport_options(transport=mock_transport), + ) + + with _patch_auth_default(): + response = client.request(http_method='GET', path='path', request_dict={}) + mock_transport.handle_request.assert_called_once() + assert response.headers['status-code'] == '200' + + +def test_disabled_retries_failed_request_executes_once(): + mock_transport = mock.Mock(spec=httpx.BaseTransport) + mock_transport.handle_request.return_value = _httpx_response(429) + + client = api_client.BaseApiClient( + vertexai=True, + project='test_project', + location='global', + http_options=_transport_options(transport=mock_transport), + ) + + with _patch_auth_default(): + try: + client.request(http_method='GET', path='path', request_dict={}) + assert False, 'Expected APIError to be raised.' + except errors.APIError as e: + assert e.code == 429 + mock_transport.handle_request.assert_called_once() + + +_RETRY_OPTIONS = types.HttpRetryOptions( + attempts=2, + initial_delay=0, + max_delay=1, + exp_base=0.1, + jitter=0.1, + http_status_codes=[429, 504], +) + + +def test_retries_successful_request_executes_once(): + mock_transport = mock.Mock(spec=httpx.BaseTransport) + mock_transport.handle_request.return_value = _httpx_response(200) + + client = api_client.BaseApiClient( + vertexai=True, + project='test_project', + location='global', + http_options=_transport_options( + http_options=types.HttpOptions(retry_options=_RETRY_OPTIONS), + transport=mock_transport, + ), + ) + + with _patch_auth_default(): + response = client.request(http_method='GET', path='path', request_dict={}) + mock_transport.handle_request.assert_called_once() + assert response.headers['status-code'] == '200' + + +def test_retries_failed_request_retries_successfully(): + mock_transport = mock.Mock(spec=httpx.BaseTransport) + mock_transport.handle_request.side_effect = ( + _httpx_response(429), + _httpx_response(200), + ) + + client = api_client.BaseApiClient( + vertexai=True, + project='test_project', + location='global', + http_options=_transport_options( + http_options=types.HttpOptions(retry_options=_RETRY_OPTIONS), + transport=mock_transport, + ), + ) + + with _patch_auth_default(): + response = client.request(http_method='GET', path='path', request_dict={}) + mock_transport.handle_request.assert_called() + assert response.headers['status-code'] == '200' + + +def test_retries_failed_request_retries_successfully_at_request_level(): + mock_transport = mock.Mock(spec=httpx.BaseTransport) + mock_transport.handle_request.side_effect = ( + _httpx_response(429), + _httpx_response(200), + ) + + client = api_client.BaseApiClient( + vertexai=True, + project='test_project', + location='global', + http_options=_transport_options( + transport=mock_transport, + ), + ) + + with _patch_auth_default(): + response = client.request( + http_method='GET', + path='path', + request_dict={}, + http_options=types.HttpOptions( + retry_options=_RETRY_OPTIONS + ), # At request level. + ) + mock_transport.handle_request.assert_called() + assert response.headers['status-code'] == '200' + + +def test_retries_failed_request_retries_unsuccessfully(): + mock_transport = mock.Mock(spec=httpx.BaseTransport) + mock_transport.handle_request.side_effect = ( + _httpx_response(429), + _httpx_response(504), + ) + + client = api_client.BaseApiClient( + vertexai=True, + project='test_project', + location='global', + http_options=_transport_options( + http_options=types.HttpOptions(retry_options=_RETRY_OPTIONS), + transport=mock_transport, + ), + ) + + with _patch_auth_default(): + try: + client.request(http_method='GET', path='path', request_dict={}) + assert False, 'Expected APIError to be raised.' + except errors.APIError as e: + assert e.code == 504 + mock_transport.handle_request.assert_called() + + +def test_retries_failed_request_no_retries_unsuccessfully(): + mock_transport = mock.Mock(spec=httpx.BaseTransport) + mock_transport.handle_request.side_effect = ( + _httpx_response(429), + ) + + client = api_client.BaseApiClient( + vertexai=True, + project='test_project', + location='global', + http_options=_transport_options( + http_options=types.HttpOptions( + retry_options=types.HttpRetryOptions(attempts=0) + ), + transport=mock_transport, + ), + ) + + with _patch_auth_default(): + try: + client.request(http_method='GET', path='path', request_dict={}) + assert False, 'Expected APIError to be raised.' + except errors.APIError as e: + assert e.code == 429 + mock_transport.handle_request.assert_called() + + +def test_retries_failed_request_retries_unsuccessfully_at_request_level(): + mock_transport = mock.Mock(spec=httpx.BaseTransport) + mock_transport.handle_request.side_effect = ( + _httpx_response(429), + _httpx_response(504), + ) + + client = api_client.BaseApiClient( + vertexai=True, + project='test_project', + location='global', + http_options=_transport_options( + transport=mock_transport, + ), + ) + + with _patch_auth_default(): + try: + client.request( + http_method='GET', + path='path', + request_dict={}, + http_options={'retry_options': _RETRY_OPTIONS}, # At request level. + ) + assert False, 'Expected APIError to be raised.' + except errors.APIError as e: + assert e.code == 504 + mock_transport.handle_request.assert_called() + + +# Async httpx + + +def test_async_disabled_retries_successful_request_executes_once(): + api_client.has_aiohttp = False + + async def run(): + mock_transport = mock.Mock(spec=httpx.AsyncBaseTransport) + mock_transport.handle_async_request.return_value = _httpx_response(200) + + client = api_client.BaseApiClient( + vertexai=True, + project='test_project', + location='global', + http_options=_transport_options(async_transport=mock_transport), + ) + + with _patch_auth_default(): + response = await client.async_request( + http_method='GET', path='path', request_dict={} + ) + mock_transport.handle_async_request.assert_called_once() + assert response.headers['status-code'] == '200' + + asyncio.run(run()) + + +def test_async_disabled_retries_failed_request_executes_once(): + api_client.has_aiohttp = False + + async def run(): + mock_transport = mock.Mock(spec=httpx.AsyncBaseTransport) + mock_transport.handle_async_request.return_value = _httpx_response(429) + + client = api_client.BaseApiClient( + vertexai=True, + project='test_project', + location='global', + http_options=_transport_options(async_transport=mock_transport), + ) + + with _patch_auth_default(): + try: + await client.async_request( + http_method='GET', path='path', request_dict={} + ) + assert False, 'Expected APIError to be raised.' + except errors.APIError as e: + assert e.code == 429 + mock_transport.handle_async_request.assert_called_once() + + asyncio.run(run()) + + +def test_async_retries_successful_request_executes_once(): + api_client.has_aiohttp = False + + async def run(): + mock_transport = mock.Mock(spec=httpx.AsyncBaseTransport) + mock_transport.handle_async_request.return_value = _httpx_response(200) + + client = api_client.BaseApiClient( + vertexai=True, + project='test_project', + location='global', + http_options=_transport_options( + http_options=types.HttpOptions(retry_options=_RETRY_OPTIONS), + async_transport=mock_transport, + ), + ) + + with _patch_auth_default(): + response = await client.async_request( + http_method='GET', path='path', request_dict={} + ) + mock_transport.handle_async_request.assert_called_once() + assert response.headers['status-code'] == '200' + + asyncio.run(run()) + + +def test_async_retries_failed_request_retries_successfully(): + api_client.has_aiohttp = False + + async def run(): + mock_transport = mock.Mock(spec=httpx.AsyncBaseTransport) + mock_transport.handle_async_request.side_effect = ( + _httpx_response(429), + _httpx_response(200), + ) + + client = api_client.BaseApiClient( + vertexai=True, + project='test_project', + location='global', + http_options=_transport_options( + http_options=types.HttpOptions(retry_options=_RETRY_OPTIONS), + async_transport=mock_transport, + ), + ) + + with _patch_auth_default(): + response = await client.async_request( + http_method='GET', path='path', request_dict={} + ) + mock_transport.handle_async_request.assert_called() + assert response.headers['status-code'] == '200' + + asyncio.run(run()) + + +def test_async_retries_failed_request_retries_successfully_at_request_level(): + api_client.has_aiohttp = False + + async def run(): + mock_transport = mock.Mock(spec=httpx.AsyncBaseTransport) + mock_transport.handle_async_request.side_effect = ( + _httpx_response(429), + _httpx_response(200), + ) + + client = api_client.BaseApiClient( + vertexai=True, + project='test_project', + location='global', + http_options=_transport_options( + async_transport=mock_transport, + ), + ) + + with _patch_auth_default(): + response = await client.async_request( + http_method='GET', + path='path', + request_dict={}, + http_options=types.HttpOptions( + retry_options=_RETRY_OPTIONS + ), # At request level. + ) + mock_transport.handle_async_request.assert_called() + assert response.headers['status-code'] == '200' + + asyncio.run(run()) + + +def test_async_retries_failed_request_retries_unsuccessfully(): + api_client.has_aiohttp = False + + async def run(): + mock_transport = mock.Mock(spec=httpx.AsyncBaseTransport) + mock_transport.handle_async_request.side_effect = ( + _httpx_response(429), + _httpx_response(504), + ) + + client = api_client.BaseApiClient( + vertexai=True, + project='test_project', + location='global', + http_options=_transport_options( + http_options=types.HttpOptions(retry_options=_RETRY_OPTIONS), + async_transport=mock_transport, + ), + ) + + with _patch_auth_default(): + try: + await client.async_request( + http_method='GET', path='path', request_dict={} + ) + assert False, 'Expected APIError to be raised.' + except errors.APIError as e: + assert e.code == 504 + mock_transport.handle_async_request.assert_called() + + asyncio.run(run()) + + +def test_async_retries_failed_request_retries_unsuccessfully_at_request_level(): + api_client.has_aiohttp = False + + async def run(): + mock_transport = mock.Mock(spec=httpx.AsyncBaseTransport) + mock_transport.handle_async_request.side_effect = ( + _httpx_response(429), + _httpx_response(504), + ) + + client = api_client.BaseApiClient( + vertexai=True, + project='test_project', + location='global', + http_options=_transport_options( + async_transport=mock_transport, + ), + ) + + with _patch_auth_default(): + try: + await client.async_request( + http_method='GET', + path='path', + request_dict={}, + http_options=types.HttpOptions(retry_options=_RETRY_OPTIONS), + ) + assert False, 'Expected APIError to be raised.' + except errors.APIError as e: + assert e.code == 504 + mock_transport.handle_async_request.assert_called() + + asyncio.run(run()) + + +# Async aiohttp + +async def _aiohttp_async_response(status: int, streamable: bool = False): + """Has to return a coroutine hence async.""" + response = mock.Mock(spec=aiohttp.ClientResponse) + response.status = status + response.headers = {'status-code': str(status)} + response.json.return_value = {} + response.text.return_value = 'test' + if streamable: + response.content = mock.Mock() + response.content.readline = mock.AsyncMock(return_value=b'') + response.release = mock.MagicMock() + return response + + +@requires_aiohttp +@mock.patch.object(aiohttp.ClientSession, 'request', autospec=True) +def test_aiohttp_disabled_retries_successful_request_executes_once( + mock_request, +): + api_client.has_aiohttp = True # Force aiohttp + + async def run(): + mock_request.return_value = _aiohttp_async_response(200) + + client = api_client.BaseApiClient( + vertexai=True, + project='test_project', + location='global', + ) + + with _patch_auth_default(): + response = await client.async_request( + http_method='GET', path='path', request_dict={} + ) + mock_request.assert_called_once() + assert response.headers['status-code'] == '200' + + asyncio.run(run()) + + +@requires_aiohttp +@mock.patch.object(aiohttp.ClientSession, 'request', autospec=True) +def test_aiohttp_disabled_retries_failed_request_executes_once(mock_request): + api_client.has_aiohttp = True + + async def run(): + mock_request.return_value = _aiohttp_async_response(429) + + client = api_client.BaseApiClient( + vertexai=True, + project='test_project', + location='global', + ) + + with _patch_auth_default(): + try: + await client.async_request( + http_method='GET', path='path', request_dict={} + ) + assert False, 'Expected APIError to be raised.' + except errors.APIError as e: + assert e.code == 429 + mock_request.assert_called_once() + + asyncio.run(run()) + + +@requires_aiohttp +@mock.patch.object(aiohttp.ClientSession, 'request', autospec=True) +def test_aiohttp_retries_successful_request_executes_once(mock_request): + api_client.has_aiohttp = True + + async def run(): + mock_request.return_value = _aiohttp_async_response(200) + + client = api_client.BaseApiClient( + vertexai=True, + project='test_project', + location='global', + http_options=_transport_options( + http_options=types.HttpOptions(retry_options=_RETRY_OPTIONS), + ), + ) + + with _patch_auth_default(): + response = await client.async_request( + http_method='GET', path='path', request_dict={} + ) + mock_request.assert_called_once() + assert response.headers['status-code'] == '200' + + asyncio.run(run()) + + +@requires_aiohttp +@mock.patch.object(aiohttp.ClientSession, 'request', autospec=True) +def test_aiohttp_retries_failed_request_retries_successfully(mock_request): + api_client.has_aiohttp = True + + async def run(): + mock_request.side_effect = ( + _aiohttp_async_response(429), + _aiohttp_async_response(200), + ) + + client = api_client.BaseApiClient( + vertexai=True, + project='test_project', + location='global', + http_options=_transport_options( + http_options=types.HttpOptions( + retry_options=_RETRY_OPTIONS, + async_client_args={'trust_env': False}, + ), + ), + ) + + with _patch_auth_default(): + response = await client.async_request( + http_method='GET', path='path', request_dict={} + ) + mock_request.assert_called() + assert response.headers['status-code'] == '200' + + asyncio.run(run()) + + +@requires_aiohttp +@mock.patch.object( + aiohttp.ClientSession, + 'request', + autospec=True, +) +def test_aiohttp_retries_failed_request_retries_successfully_at_request_level( + mock_request, +): + api_client.has_aiohttp = True + + async def run(): + mock_request.side_effect = ( + _aiohttp_async_response(429), + _aiohttp_async_response(200), + ) + + client = api_client.BaseApiClient( + vertexai=True, + project='test_project', + location='global', + ) + + with _patch_auth_default(): + response = await client.async_request( + http_method='GET', + path='path', + request_dict={}, + http_options=types.HttpOptions( + retry_options=_RETRY_OPTIONS + ), # At request level. + ) + mock_request.assert_called() + assert response.headers['status-code'] == '200' + + asyncio.run(run()) + + +@requires_aiohttp +@mock.patch.object(aiohttp.ClientSession, 'request', autospec=True) +def test_aiohttp_retries_failed_request_retries_unsuccessfully(mock_request): + api_client.has_aiohttp = True + + async def run(): + mock_request.side_effect = ( + _aiohttp_async_response(429), + _aiohttp_async_response(504), + ) + + client = api_client.BaseApiClient( + vertexai=True, + project='test_project', + location='global', + http_options=_transport_options( + http_options=types.HttpOptions( + retry_options=_RETRY_OPTIONS, + async_client_args={'trust_env': False}, + ), + ), + ) + + with _patch_auth_default(): + try: + await client.async_request( + http_method='GET', path='path', request_dict={} + ) + assert False, 'Expected APIError to be raised.' + except errors.APIError as e: + assert e.code == 504 + mock_request.assert_called() + + asyncio.run(run()) + + +@requires_aiohttp +@mock.patch.object( + aiohttp.ClientSession, + 'request', + autospec=True, +) +def test_aiohttp_retries_failed_request_retries_unsuccessfully_at_request_level( + mock_request, +): + api_client.has_aiohttp = True + + async def run(): + mock_request.side_effect = ( + _aiohttp_async_response(429), + _aiohttp_async_response(504), + ) + + client = api_client.BaseApiClient( + vertexai=True, + project='test_project', + location='global', + ) + + with _patch_auth_default(): + try: + await client.async_request( + http_method='GET', + path='path', + request_dict={}, + http_options={'retry_options': _RETRY_OPTIONS}, # At request level. + ) + assert False, 'Expected APIError to be raised.' + except errors.APIError as e: + assert e.code == 504 + mock_request.assert_called() + + asyncio.run(run()) + + +# Sync Streaming + + +def test_retries_streamed_failed_request_retries_successfully(): + mock_transport = mock.Mock(spec=httpx.BaseTransport) + mock_transport.handle_request.side_effect = ( + _httpx_response(429), + _httpx_response(200), + ) + + client = api_client.BaseApiClient( + vertexai=True, + project='test_project', + location='global', + http_options=_transport_options( + http_options=types.HttpOptions(retry_options=_RETRY_OPTIONS), + transport=mock_transport, + ), + ) + + with _patch_auth_default(): + stream = client.request_streamed( + http_method='GET', path='path', request_dict={} + ) + list(stream) + mock_transport.handle_request.assert_called() + assert mock_transport.handle_request.call_count == 2 + + +def test_retries_streamed_failed_request_retries_successfully_at_request_level(): + mock_transport = mock.Mock(spec=httpx.BaseTransport) + mock_transport.handle_request.side_effect = ( + _httpx_response(429), + _httpx_response(200), + ) + + client = api_client.BaseApiClient( + vertexai=True, + project='test_project', + location='global', + http_options=_transport_options( + transport=mock_transport, + ), + ) + + with _patch_auth_default(): + stream = client.request_streamed( + http_method='GET', + path='path', + request_dict={}, + http_options=types.HttpOptions(retry_options=_RETRY_OPTIONS), + ) + list(stream) + mock_transport.handle_request.assert_called() + assert mock_transport.handle_request.call_count == 2 + + +def test_retries_streamed_failed_request_retries_unsuccessfully(): + mock_transport = mock.Mock(spec=httpx.BaseTransport) + mock_transport.handle_request.side_effect = ( + _httpx_response(429), + _httpx_response(504), + ) + + client = api_client.BaseApiClient( + vertexai=True, + project='test_project', + location='global', + http_options=_transport_options( + http_options=types.HttpOptions(retry_options=_RETRY_OPTIONS), + transport=mock_transport, + ), + ) + + with _patch_auth_default(): + try: + stream = client.request_streamed( + http_method='GET', path='path', request_dict={} + ) + list(stream) + assert False, 'Expected APIError to be raised.' + except errors.APIError as e: + assert e.code == 504 + mock_transport.handle_request.assert_called() + + +def test_retries_streamed_failed_request_retries_unsuccessfully_at_request_level(): + mock_transport = mock.Mock(spec=httpx.BaseTransport) + mock_transport.handle_request.side_effect = ( + _httpx_response(429), + _httpx_response(504), + ) + + client = api_client.BaseApiClient( + vertexai=True, + project='test_project', + location='global', + http_options=_transport_options( + transport=mock_transport, + ), + ) + + with _patch_auth_default(): + try: + stream = client.request_streamed( + http_method='GET', + path='path', + request_dict={}, + http_options={'retry_options': _RETRY_OPTIONS}, + ) + list(stream) + assert False, 'Expected APIError to be raised.' + except errors.APIError as e: + assert e.code == 504 + mock_transport.handle_request.assert_called() + + +# Async httpx Streaming + + +def test_async_retries_streamed_failed_request_retries_successfully(): + api_client.has_aiohttp = False + + async def run(): + mock_transport = mock.Mock(spec=httpx.AsyncBaseTransport) + mock_transport.handle_async_request.side_effect = ( + _httpx_response(429), + _httpx_response(200), + ) + + client = api_client.BaseApiClient( + vertexai=True, + project='test_project', + location='global', + http_options=_transport_options( + http_options=types.HttpOptions(retry_options=_RETRY_OPTIONS), + async_transport=mock_transport, + ), + ) + + with _patch_auth_default(): + stream = await client.async_request_streamed( + http_method='GET', path='path', request_dict={} + ) + async for _ in stream: + pass + mock_transport.handle_async_request.assert_called() + assert mock_transport.handle_async_request.call_count == 2 + + asyncio.run(run()) + + +def test_async_retries_streamed_failed_request_retries_successfully_at_request_level(): + api_client.has_aiohttp = False + + async def run(): + mock_transport = mock.Mock(spec=httpx.AsyncBaseTransport) + mock_transport.handle_async_request.side_effect = ( + _httpx_response(429), + _httpx_response(200), + ) + + client = api_client.BaseApiClient( + vertexai=True, + project='test_project', + location='global', + http_options=_transport_options( + async_transport=mock_transport, + ), + ) + + with _patch_auth_default(): + stream = await client.async_request_streamed( + http_method='GET', + path='path', + request_dict={}, + http_options=types.HttpOptions(retry_options=_RETRY_OPTIONS), + ) + async for _ in stream: + pass + mock_transport.handle_async_request.assert_called() + assert mock_transport.handle_async_request.call_count == 2 + + asyncio.run(run()) + + +def test_async_retries_streamed_failed_request_retries_unsuccessfully(): + api_client.has_aiohttp = False + + async def run(): + mock_transport = mock.Mock(spec=httpx.AsyncBaseTransport) + mock_transport.handle_async_request.side_effect = ( + _httpx_response(429), + _httpx_response(504), + ) + + client = api_client.BaseApiClient( + vertexai=True, + project='test_project', + location='global', + http_options=_transport_options( + http_options=types.HttpOptions(retry_options=_RETRY_OPTIONS), + async_transport=mock_transport, + ), + ) + + with _patch_auth_default(): + try: + stream = await client.async_request_streamed( + http_method='GET', path='path', request_dict={} + ) + async for _ in stream: + pass + assert False, 'Expected APIError to be raised.' + except errors.APIError as e: + assert e.code == 504 + mock_transport.handle_async_request.assert_called() + + asyncio.run(run()) + + +def test_async_retries_streamed_failed_request_retries_unsuccessfully_at_request_level(): + api_client.has_aiohttp = False + + async def run(): + mock_transport = mock.Mock(spec=httpx.AsyncBaseTransport) + mock_transport.handle_async_request.side_effect = ( + _httpx_response(429), + _httpx_response(504), + ) + + client = api_client.BaseApiClient( + vertexai=True, + project='test_project', + location='global', + http_options=_transport_options( + async_transport=mock_transport, + ), + ) + + with _patch_auth_default(): + try: + stream = await client.async_request_streamed( + http_method='GET', + path='path', + request_dict={}, + http_options=types.HttpOptions(retry_options=_RETRY_OPTIONS), + ) + async for _ in stream: + pass + assert False, 'Expected APIError to be raised.' + except errors.APIError as e: + assert e.code == 504 + mock_transport.handle_async_request.assert_called() + + asyncio.run(run()) + + +# Async aiohttp Streaming + + +@requires_aiohttp +@mock.patch.object(aiohttp.ClientSession, 'request', autospec=True) +def test_aiohttp_retries_streamed_failed_request_retries_successfully( + mock_request, +): + api_client.has_aiohttp = True + + async def run(): + mock_request.side_effect = ( + _aiohttp_async_response(429), + _aiohttp_async_response(200, streamable=True), + ) + + client = api_client.BaseApiClient( + vertexai=True, + project='test_project', + location='global', + http_options=_transport_options( + http_options=types.HttpOptions(retry_options=_RETRY_OPTIONS), + ), + ) + + with _patch_auth_default(): + stream = await client.async_request_streamed( + http_method='GET', path='path', request_dict={} + ) + async for _ in stream: + pass + mock_request.assert_called() + assert mock_request.call_count == 2 + + asyncio.run(run()) + + +@requires_aiohttp +@mock.patch.object(aiohttp.ClientSession, 'request', autospec=True) +def test_aiohttp_retries_streamed_failed_request_retries_successfully_at_request_level( + mock_request, +): + api_client.has_aiohttp = True + + async def run(): + mock_request.side_effect = ( + _aiohttp_async_response(429), + _aiohttp_async_response(200, streamable=True), + ) + + client = api_client.BaseApiClient( + vertexai=True, + project='test_project', + location='global', + ) + + with _patch_auth_default(): + stream = await client.async_request_streamed( + http_method='GET', + path='path', + request_dict={}, + http_options=types.HttpOptions( + retry_options=_RETRY_OPTIONS, + async_client_args={'trust_env': False}, + ), + ) + async for _ in stream: + pass + mock_request.assert_called() + assert mock_request.call_count == 2 + + asyncio.run(run()) + + +@requires_aiohttp +@mock.patch.object( + aiohttp.ClientSession, + 'request', + autospec=True, +) +def test_aiohttp_retries_streamed_failed_request_retries_unsuccessfully( + mock_request, +): + api_client.has_aiohttp = True + + async def run(): + mock_request.side_effect = ( + _aiohttp_async_response(429), + _aiohttp_async_response(504), + ) + + client = api_client.BaseApiClient( + vertexai=True, + project='test_project', + location='global', + http_options=_transport_options( + http_options=types.HttpOptions(retry_options=_RETRY_OPTIONS), + ), + ) + + with _patch_auth_default(): + try: + stream = await client.async_request_streamed( + http_method='GET', path='path', request_dict={} + ) + async for _ in stream: + pass + assert False, 'Expected APIError to be raised.' + except errors.APIError as e: + assert e.code == 504 + mock_request.assert_called() + + asyncio.run(run()) + + +@requires_aiohttp +@mock.patch.object(aiohttp.ClientSession, 'request', autospec=True) +def test_aiohttp_retries_streamed_failed_request_retries_unsuccessfully_at_request_level( + mock_request, +): + api_client.has_aiohttp = True + + async def run(): + mock_request.side_effect = ( + _aiohttp_async_response(429), + _aiohttp_async_response(504), + ) + + client = api_client.BaseApiClient( + vertexai=True, + project='test_project', + location='global', + http_options=types.HttpOptions( + async_client_args={'trust_env': False}, + ), + ) + + with _patch_auth_default(): + try: + stream = await client.async_request_streamed( + http_method='GET', + path='path', + request_dict={}, + http_options={'retry_options': _RETRY_OPTIONS}, + ) + async for _ in stream: + pass + assert False, 'Expected APIError to be raised.' + except errors.APIError as e: + assert e.code == 504 + mock_request.assert_called() + + asyncio.run(run()) + + +@requires_aiohttp +@mock.patch.object( + aiohttp.ClientSession, + 'request', + autospec=True, +) +def test_aiohttp_retries_client_connector_error_retries_successfully( + mock_request, +): + api_client.has_aiohttp = True + + async def run(): + mock_request.side_effect = ( + aiohttp.ClientConnectorError( + connection_key=aiohttp.client_reqrep.ConnectionKey( + 'localhost', 80, False, True, None, None, None + ), + os_error=OSError, + ), + _aiohttp_async_response(200), + ) + # The request will be automatically retried once, if catching the + # ClientConnectorError. + + client = api_client.BaseApiClient( + vertexai=True, + project='test_project', + location='global', + ) + + with _patch_auth_default(): + response = await client.async_request( + http_method='GET', path='path', request_dict={} + ) + mock_request.assert_called() + assert response.headers['status-code'] == '200' + + asyncio.run(run()) + + +@requires_aiohttp +@mock.patch.object(AsyncAuthorizedSession, 'request', autospec=True) +def test_aiohttp_retries_failed_request_retries_unsuccessfully_mtls( + mock_request, +): + api_client.has_aiohttp = True + + async def run(): + # 1. Setup mocked aiohttp responses + res429 = await _aiohttp_async_response(429) + res504 = await _aiohttp_async_response(504) + + # 2. Wrap them in the AsyncAuthorizedSessionResponse expected by the SDK + mock_auth_res429 = mock.Mock(spec=AsyncAuthorizedSessionResponse) + mock_auth_res429._response = res429 + + mock_auth_res504 = mock.Mock(spec=AsyncAuthorizedSessionResponse) + mock_auth_res504._response = res504 + + # AsyncAuthorizedSession.request is an async method + mock_request.side_effect = [mock_auth_res429, mock_auth_res504] + + client = api_client.BaseApiClient( + vertexai=True, + project='test_project', + location='global', + http_options=types.HttpOptions( + retry_options=_RETRY_OPTIONS, + ), + ) + + # Force the mTLS path to be active for this test + with mock.patch( + 'google.auth.transport.mtls.should_use_client_cert', return_value=True + ): + with _patch_auth_default(): + try: + await client.async_request( + http_method='GET', path='path', request_dict={} + ) + assert False, 'Expected APIError to be raised.' + except errors.APIError as e: + assert e.code == 504 + mock_request.assert_called() + + asyncio.run(run()) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/client/test_upload_errors.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/client/test_upload_errors.py new file mode 100644 index 0000000000000000000000000000000000000000..897913ca7f3644f74801f23ebc971994aa5a811f --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/client/test_upload_errors.py @@ -0,0 +1,197 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +"""Tests for error handling in the client api client layer for uploads.""" + +import io +import json +from unittest import mock +import pytest + +import httpx + +from ... import _api_client as api_client +from ... import errors +from ... import types + +try: + import aiohttp + AIOHTTP_NOT_INSTALLED = False +except ImportError: + AIOHTTP_NOT_INSTALLED = True + +def _httpx_response(code: int, headers: dict = None, content: bytes = b''): + headers = headers or {} + headers['status-code'] = str(code) + return httpx.Response( + status_code=code, + headers=headers, + content=content, + ) + +@pytest.fixture +def client(): + return api_client.BaseApiClient(vertexai=False, api_key='test_api_key') + + +def test_upload_url_rewrite(client: api_client.BaseApiClient): + mock_httpx_client = mock.MagicMock(spec=httpx.Client) + mock_httpx_client.request.side_effect = [ + _httpx_response( + 200, headers={"X-Goog-Upload-Status": "final"} + ), # Upload request succeeding + ] + client._httpx_client = mock_httpx_client + + http_options = types.HttpOptions(base_url="https://my-proxy.company.com") + + with io.BytesIO(b"test") as f: + client._upload_fd( + f, + "https://generativelanguage.googleapis.com/upload/v1beta/files?uploadType=resumable", + 4, + http_options=http_options, + ) + + assert mock_httpx_client.request.call_count == 1 + call_args = mock_httpx_client.request.call_args[1] + assert ( + call_args["url"] + == "https://my-proxy.company.com/upload/v1beta/files?uploadType=resumable" + ) + + +def test_upload_fd_error(client: api_client.BaseApiClient): + error_content = json.dumps({ + "error": { + "code": 400, + "message": "Unsupported MIME type: bad/mime_type", + "status": "INVALID_ARGUMENT" + } + }).encode('utf-8') + + mock_httpx_client = mock.MagicMock(spec=httpx.Client) + mock_httpx_client.request.side_effect = [ + _httpx_response(200, headers={"X-Goog-Upload-URL": "http://fake/upload"}), # Initial request to get upload URL + _httpx_response(400, content=error_content, headers={"X-Goog-Upload-Status": "final"}), # Upload request failing + ] + client._httpx_client = mock_httpx_client + + with pytest.raises(errors.APIError, match='Unsupported MIME type: bad/mime_type'), io.BytesIO(b"test") as f: + client._upload_fd( + f, # Pass file object directly + "http://fake/upload", + 4, + http_options=types.HttpOptions(), + ) + + assert mock_httpx_client.request.call_count == 2 + + +@pytest.mark.asyncio +async def test_async_upload_url_rewrite_httpx(client: api_client.BaseApiClient): + mock_async_httpx_client = mock.MagicMock(spec=httpx.AsyncClient) + mock_async_httpx_client.request = mock.AsyncMock( + side_effect=[ + _httpx_response( + 200, headers={"X-Goog-Upload-Status": "final"} + ), # Upload request + ] + ) + client._async_httpx_client = mock_async_httpx_client + + http_options = types.HttpOptions(base_url="https://my-proxy.company.com") + + with mock.patch.object( + client, "_use_aiohttp", return_value=False + ), io.BytesIO(b"test") as f: + await client._async_upload_fd( + f, + "https://generativelanguage.googleapis.com/upload/v1beta/files?uploadType=resumable", + 4, + http_options=http_options, + ) + + assert mock_async_httpx_client.request.call_count == 1 + call_args = mock_async_httpx_client.request.call_args[1] + assert ( + call_args["url"] + == "https://my-proxy.company.com/upload/v1beta/files?uploadType=resumable" + ) + + +@pytest.mark.asyncio +async def test_async_upload_fd_error_httpx(client: api_client.BaseApiClient): + error_content = json.dumps({ + "error": { + "code": 400, + "message": "Unsupported MIME type: bad/mime_type", + "status": "INVALID_ARGUMENT" + } + }).encode('utf-8') + + # Mock for httpx.AsyncClient + mock_async_httpx_client = mock.MagicMock(spec=httpx.AsyncClient) + mock_async_httpx_client.request = mock.AsyncMock(side_effect=[ + _httpx_response(200, headers={"X-Goog-Upload-URL": "http://fake/upload"}), # Initial request + _httpx_response(400, content=error_content, headers={"X-Goog-Upload-Status": "final"}), # Upload request + ]) + client._async_httpx_client = mock_async_httpx_client + + # Patch the _use_aiohttp method to control which client is used + with mock.patch.object(client, '_use_aiohttp', return_value=False), \ + pytest.raises(errors.APIError, match='Unsupported MIME type: bad/mime_type'), \ + io.BytesIO(b"test") as f: + await client._async_upload_fd( + f, # Pass file object directly + "http://fake/upload", + 4, + http_options=types.HttpOptions(), + + ) + assert mock_async_httpx_client.request.call_count == 2 + +@pytest.mark.asyncio +@pytest.mark.skipif( + AIOHTTP_NOT_INSTALLED, reason="aiohttp is not installed, skipping test." +) +async def test_async_upload_fd_error_aiohttp(client: api_client.BaseApiClient): + error_content = json.dumps({ + "error": { + "code": 400, + "message": "Unsupported MIME type: bad/mime_type", + "status": "INVALID_ARGUMENT" + } + }).encode('utf-8') + + # Mock for aiohttp.ClientSession + mock_aiohttp_session = mock.MagicMock() + mock_aiohttp_session.request = mock.AsyncMock(side_effect=[ + _httpx_response(200, headers={"X-Goog-Upload-URL": "http://fake/upload"}), # Initial request + _httpx_response(400, content=error_content, headers={"X-Goog-Upload-Status": "final"}), # Upload request + ]) + + with mock.patch.object(client, '_use_aiohttp', return_value=True), \ + mock.patch.object(client, '_get_aiohttp_session', return_value=mock_aiohttp_session), \ + pytest.raises(errors.APIError, match='Unsupported MIME type: bad/mime_type'), \ + io.BytesIO(b"test") as f: + await client._async_upload_fd( + f, # Pass file object directly + "http://fake/upload", + 4, + http_options=types.HttpOptions(), + ) + assert mock_aiohttp_session.request.call_count == 2 + diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/common/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/common/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..17b8a5cc24f1de6c30a14fc6895b16baec3f4aa7 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/common/__init__.py @@ -0,0 +1,17 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for the Google GenAI SDK's _common module.""" \ No newline at end of file diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/common/test_common.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/common/test_common.py new file mode 100644 index 0000000000000000000000000000000000000000..1ead6e46dbd67b7af24378142c37bfcbfbb8e720 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/common/test_common.py @@ -0,0 +1,954 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests tools in the _common module.""" + +from enum import Enum +import inspect +import logging +import textwrap +import typing +from typing import List, Optional +import warnings + +import pydantic +import pytest + +from ... import _common +from ... import types +from ... import errors + + +def test_warn_once(): + @_common.experimental_warning('Warning!') + def func(): + pass + + with warnings.catch_warnings(record=True) as w: + func() + func() + + assert len(w) == 1 + assert w[0].category == errors.ExperimentalWarning + +def test_warn_at_call_line(): + @_common.experimental_warning('Warning!') + def func(): + pass + + with warnings.catch_warnings(record=True) as captured_warnings: + call_line = inspect.currentframe().f_lineno + 1 + func() + + assert captured_warnings[0].lineno == call_line + + +def test_is_struct_type(): + assert _common._is_struct_type(list[dict[str, typing.Any]]) + assert _common._is_struct_type(typing.List[typing.Dict[str, typing.Any]]) + assert not _common._is_struct_type(list[dict[str, int]]) + assert not _common._is_struct_type(list[dict[int, typing.Any]]) + assert not _common._is_struct_type(list[str]) + assert not _common._is_struct_type(dict[str, typing.Any]) + assert not _common._is_struct_type(typing.List[typing.Dict[str, int]]) + assert not _common._is_struct_type(typing.List[typing.Dict[int, typing.Any]]) + assert not _common._is_struct_type(typing.List[str]) + assert not _common._is_struct_type(typing.Dict[str, typing.Any]) + + + +@pytest.mark.parametrize( + "test_id, initial_target, update_dict, expected_target", + [ + ( + "simple_update", + {"a": 1, "b": 2}, + {"b": 3, "c": 4}, + {"a": 1, "b": 3, "c": 4}, + ), + ( + "nested_update", + {"a": 1, "b": {"x": 10, "y": 20}}, + {"b": {"y": 30, "z": 40}, "c": 3}, + {"a": 1, "b": {"x": 10, "y": 30, "z": 40}, "c": 3}, + ), + ( + "add_new_nested_dict", + {"a": 1}, + {"b": {"x": 10, "y": 20}}, + {"a": 1, "b": {"x": 10, "y": 20}}, + ), + ( + "empty_target", + {}, + {"a": 1, "b": {"x": 10}}, + {"a": 1, "b": {"x": 10}}, + ), + ( + "empty_update", + {"a": 1, "b": {"x": 10}}, + {}, + {"a": 1, "b": {"x": 10}}, + ), + ( + "overwrite_non_dict_with_dict", + {"a": 1, "b": 2}, + {"b": {"x": 10}}, + {"a": 1, "b": {"x": 10}}, + ), + ( + "overwrite_dict_with_non_dict", + {"a": 1, "b": {"x": 10}}, + {"b": 2}, + {"a": 1, "b": 2}, + ), + ( + "deeper_nesting", + {"a": {"b": {"c": 1, "d": 2}, "e": 3}}, + {"a": {"b": {"d": 4, "f": 5}, "g": 6}, "h": 7}, + {"a": {"b": {"c": 1, "d": 4, "f": 5}, "e": 3, "g": 6}, "h": 7}, + ), + ( + "different_value_types", + {"key1": "string_val", "key2": {"nested_int": 100}}, + {"key1": 123, "key2": {"nested_list": [1, 2, 3]}, "key3": True}, + { + "key1": 123, + "key2": {"nested_int": 100, "nested_list": [1, 2, 3]}, + "key3": True, + }, + ), + ( + "update_with_empty_nested_dict", # Existing nested dict in target should not be cleared + {"a": {"b": 1}}, + {"a": {}}, + {"a": {"b": 1}}, + ), + ( + "target_with_empty_nested_dict", + {"a": {}}, + {"a": {"b": 1}}, + {"a": {"b": 1}}, + ), + ( + "key_case_alignment_check", + {"first_name": "John", "contact_info": {"email_address": "john@example.com"}}, + {"firstName": "Jane", "contact_info": {"email_address": "jane@example.com", "phone_number": "123"}}, + {"first_name": "Jane", "contact_info": {"email_address": "jane@example.com", "phone_number": "123"}}, + ) + ], +) +def test_recursive_dict_update( + test_id: str, initial_target: dict, update_dict: dict, expected_target: dict +): + _common.recursive_dict_update(initial_target, update_dict) + assert initial_target == expected_target + + +@pytest.mark.parametrize( + "test_id, initial_target, update_dict, expected_target, expect_warning, expected_log_message_part", + [ + ( + "type_match_int", + {"a": 1}, + {"a": 2}, + {"a": 2}, + False, + "", + ), + ( + "type_match_dict", + {"a": {"b": 1}}, + {"a": {"b": 2}}, + {"a": {"b": 2}}, + False, + "", + ), + ( + "type_mismatch_int_to_str", + {"a": 1}, + {"a": "hello"}, + {"a": "hello"}, + True, + "Type mismatch for key 'a'. Existing type: , new type: . Overwriting.", + ), + ( + "type_mismatch_dict_to_int", + {"a": {"b": 1}}, + {"a": 100}, + {"a": 100}, + True, + "Type mismatch for key 'a'. Existing type: , new type: . Overwriting.", + ), + ( + "type_mismatch_int_to_dict", + {"a": 100}, + {"a": {"b": 1}}, + {"a": {"b": 1}}, + True, + "Type mismatch for key 'a'. Existing type: , new type: . Overwriting.", + ), + ("add_new_key", {"a": 1}, {"b": "new"}, {"a": 1, "b": "new"}, False, ""), + ], +) +def test_recursive_dict_update_type_warnings(test_id, initial_target, update_dict, expected_target, expect_warning, expected_log_message_part, caplog): + _common.recursive_dict_update(initial_target, update_dict) + assert initial_target == expected_target + if expect_warning: + assert len(caplog.records) == 1 + assert caplog.records[0].levelname == "WARNING" + assert expected_log_message_part in caplog.records[0].message + else: + for record in caplog.records: + if record.levelname == "WARNING" and expected_log_message_part in record.message: + pytest.fail(f"Unexpected warning logged for {test_id}: {record.message}") + + +@pytest.mark.parametrize( + "test_id, target_dict, update_dict, expected_aligned_dict", + [ + ( + "simple_snake_to_camel", + {"first_name": "John", "last_name": "Doe"}, + {"firstName": "Jane", "lastName": "Doe"}, + {"first_name": "Jane", "last_name": "Doe"}, + ), + ( + "simple_camel_to_snake", + {"firstName": "John", "lastName": "Doe"}, + {"first_name": "Jane", "last_name": "Doe"}, + {"firstName": "Jane", "lastName": "Doe"}, + ), + ( + "nested_dict_alignment", + {"user_info": {"contact_details": {"email_address": ""}}}, + {"userInfo": {"contactDetails": {"emailAddress": "test@example.com"}}}, + {"user_info": {"contact_details": {"email_address": "test@example.com"}}}, + ), + ( + "list_of_dicts_alignment", + {"users_list": [{"user_id": 0, "user_name": ""}]}, + {"usersList": [{"userId": 1, "userName": "Alice"}]}, + {"users_list": [{"userId": 1, "userName": "Alice"}]}, + ), + ( + "list_of_dicts_alignment_mixed_case_in_update", + {"users_list": [{"user_id": 0, "user_name": ""}]}, + {"usersList": [{"user_id": 1, "UserName": "Alice"}]}, + {"users_list": [{"user_id": 1, "UserName": "Alice"}]}, + ), + ( + "list_of_dicts_different_lengths_update_longer", + {"items_data": [{"item_id": 0}]}, + {"itemsData": [{"itemId": 1}, {"item_id": 2, "itemName": "Extra"}]}, + {"items_data": [{"itemId": 1}, {"item_id": 2, "itemName": "Extra"}]}, + ), + ( + "list_of_dicts_different_lengths_target_longer", + {"items_data": [{"item_id": 0, "item_name": ""}, {"item_id": 1}]}, + {"itemsData": [{"itemId": 10}]}, + {"items_data": [{"itemId": 10}]}, + ), + ( + "no_matching_keys_preserves_update_case", + {"key_one": 1}, + {"KEY_TWO": 2, "keyThree": 3}, + {"KEY_TWO": 2, "keyThree": 3}, + ), + ( + "mixed_match_and_no_match", + {"first_name": "John", "age_years": 30}, + {"firstName": "Jane", "AGE_YEARS": 28, "occupation_title": "Engineer"}, + {"first_name": "Jane", "age_years": 28, "occupation_title": "Engineer"}, + ), + ( + "empty_target_dict", + {}, + {"new_key": "new_value", "anotherKey": "anotherValue"}, + {"new_key": "new_value", "anotherKey": "anotherValue"}, + ), + ( + "empty_update_dict", + {"existing_key": "value"}, + {}, + {}, + ), + ( + "target_has_non_dict_value_for_nested_key", + {"config_settings": 123}, + {"configSettings": {"themeName": "dark"}}, + {"config_settings": {"themeName": "dark"}}, # Overwrites as per recursive_dict_update logic + ), + ( + "update_has_non_dict_value_for_nested_key", + {"config_settings": {"theme_name": "light"}}, + {"configSettings": "dark_theme_string"}, + {"config_settings": "dark_theme_string"}, # Overwrites + ), + ( + "deeply_nested_with_lists", + {"level_one": {"list_items": [{"item_name": "", "item_value": 0}]}}, + {"levelOne": {"listItems": [{"itemName": "Test", "itemValue": 100}, {"itemName": "Test2", "itemValue": 200}]}}, + {"level_one": {"list_items": [{"itemName": "Test", "itemValue": 100}, {"itemName": "Test2", "itemValue": 200}]}}, + ), + ], +) +def test_align_key_case( + test_id: str, target_dict: dict, update_dict: dict, expected_aligned_dict: dict +): + aligned_dict = _common.align_key_case(target_dict, update_dict) + assert aligned_dict == expected_aligned_dict, f"Test failed for: {test_id}" + + + +class SimpleModel(_common.BaseModel): + name: str + value: int + is_active: bool = True + none_field: Optional[str] = None + + +class Chain(_common.BaseModel): + id: int + child: Optional["Chain"] = None + + +Chain.model_rebuild() + + +class Tree(_common.BaseModel): + id: int + children: List["Tree"] = pydantic.Field(default_factory=list) + + +Tree.model_rebuild() + + +class ReprFalseModel(_common.BaseModel): + visible: str + hidden: str = pydantic.Field("secret", repr=False) + + +class NonPydantic: + + def __repr__(self): + return "NonPydantic(\n attr='value'\n)" + + +class MyEnum(Enum): + ONE = 1 + TWO = 2 + + +class EmptyModel(_common.BaseModel): + pass + + +def test_repr_simple_model_defaults_and_no_none(): + obj = SimpleModel(name="Test Name", value=123) + expected = textwrap.dedent(""" + SimpleModel( + is_active=True, + name='Test Name', + value=123 + ) + """).strip() + assert repr(obj) == expected + + +def test_repr_empty_model(): + obj = EmptyModel() + expected = "EmptyModel()" + assert repr(obj) == expected + + +def test_repr_nested_model(): + obj = Chain(id=1, child=Chain(id=2)) + expected = textwrap.dedent(""" + Chain( + child=Chain( + id=2 + ), + id=1 + ) + """).strip() + assert repr(obj) == expected + + +def test_repr_circular_model(): + obj1 = Chain(id=1) + obj2 = Chain(id=2) + obj1.child = obj2 + obj2.child = obj1 # Circular reference + expected = textwrap.dedent(""" + Chain( + child=Chain( + child=<... Circular reference ...>, + id=2 + ), + id=1 + ) + """).strip() + + assert repr(obj1) == expected + + +def test_repr_circular_list(): + my_list = [1, 2] + my_list.append(my_list) + expected = textwrap.dedent(""" + [ + 1, + 2, + <... Circular reference ...>, + ] + """).strip() + assert _common._pretty_repr(my_list) == expected + + +def test_repr_circular_dict(): + my_dict = {"a": 1} + my_dict["self"] = my_dict + expected = textwrap.dedent(""" + { + 'a': 1, + 'self': <... Circular reference ...> + } + """).strip() + assert _common._pretty_repr(my_dict) == expected + + +def test_repr_max_items(): + lst = list(range(10)) + dct = {i: i for i in range(10)} + st = set(range(10)) + tpl = tuple(range(10)) + + assert ( + "<... 5 more items ...>" in + _common._pretty_repr(lst, max_items=5) + ) + assert ( + "" in _common._pretty_repr(dct, max_items=5)) + assert ( + "<... 5 more items ...>" in _common._pretty_repr(st, max_items=5) + ) + assert ( + "<... 5 more items ...>" in _common._pretty_repr(tpl, max_items=5) + ) + + +def test_repr_max_len_bytes(): + b_data = b"a" * 100 + assert len(_common._pretty_repr(b_data, max_len=90)) == 90 + 3 + assert repr(b_data) == _common._pretty_repr(b_data, max_len=200) + + +def test_repr_max_depth_dict(): + nested = {'a': {'a': {'a': {'a': 'a', 'b': 'b'}}}} + assert "{<... 2 items at Max depth ...>}" in _common._pretty_repr(nested, depth=3) + + +def test_repr_max_depth_list(): + nested = [[[["d", "e", "e", "p"]]]] + assert "[<... 4 items at Max depth ...>]" in _common._pretty_repr(nested, depth=3) + + +def test_repr_collections(): + obj = { + "set": {3, 1, 2}, + "tuple": (4, 5, 6), + "dict": {"b": 2, "a": 1}, + "list": [7, 8, 9], + } + expected = textwrap.dedent(""" + { + 'dict': { + 'a': 1, + 'b': 2 + }, + 'list': [ + 7, + 8, + 9, + ], + 'set': { + 1, + 2, + 3, + }, + 'tuple': ( + 4, + 5, + 6, + ) + } + """).strip() + assert _common._pretty_repr(obj) == expected + + +def test_tuple_collections(): + obj = { + "tuple0": (), + "tuple1": (1,), + "tuple2": (1, 2), + } + expected = textwrap.dedent(""" + { + 'tuple0': (), + 'tuple1': ( + 1, + ), + 'tuple2': ( + 1, + 2, + ) + } + """).strip() + assert _common._pretty_repr(obj) == expected + + +def test_repr_empty_collections(): + assert _common._pretty_repr([]) == "[]" + assert _common._pretty_repr({}) == "{}" + assert ( + _common._pretty_repr(set()) == "set()" + ) + assert _common._pretty_repr(tuple()) == "()" + assert ( + _common._pretty_repr({"empty_set": set()}) == + textwrap.dedent(""" + { + 'empty_set': set() + } + """).strip() + ) + + +def test_repr_strings(): + s1 = "line one" + exp1 = "'line one'" + assert _common._pretty_repr(s1) == exp1 + + s2 = 'line one\nline two with """ inside' + exp2 = '"""line one\nline two with \\"\\"\\" inside"""' + assert _common._pretty_repr(s2) == exp2 + + s3 = 'A string with """ inside' + exp3 = '\'A string with """ inside\'' + assert _common._pretty_repr(s3) == exp3 + + +def test_repr_repr_false(): + obj = ReprFalseModel(visible="show", hidden="hide") + result = repr(obj) + assert "visible='show'" in result + assert "hidden" not in result + expected = textwrap.dedent(""" + ReprFalseModel( + visible='show' + ) + """).strip() + assert result == expected + + +def test_repr_none_fields(): + obj = SimpleModel(name="Only Name", value=0, none_field=None) + result = repr(obj) + assert "none_field" not in result + expected = textwrap.dedent(""" + SimpleModel( + is_active=True, + name='Only Name', + value=0 + ) + """).strip() + assert result == expected + + +def test_repr_other_types(): + np = NonPydantic() + en = MyEnum.TWO + obj = {"np": np, "en": en} + expected = textwrap.dedent(""" + { + 'en': , + 'np': NonPydantic( + attr='value' + ) + } + """).strip() + assert _common._pretty_repr(obj) == expected + + +def test_repr_indent_delta(): + obj = SimpleModel(name="Indent Test", value=1) + expected = textwrap.dedent(""" + SimpleModel( + is_active=True, + name='Indent Test', + value=1 + ) + """).strip() + assert _common._pretty_repr(obj, indent_delta=4) == expected + + +def test_repr_complex_object(): + obj = types.GenerateContentResponse( + automatic_function_calling_history=[], + candidates=[ + types.Candidate( + content=types.Content( + parts=[ + types.Part( + text="""There isn't a single "best" LLM, as the ideal choice highly depends on your specific needs, use case, budget, and priorities. The field is evolving incredibly fast, with new models and improvements being released constantly. + +However, we can talk about the **leading contenders** and what they are generally known for:...""" + ) + ], + role="model" + ), + finish_reason=types.FinishReason.STOP, + index=0 + ) + ], + model_version='models/gemini-2.5-flash-preview-05-20', + usage_metadata=types.GenerateContentResponseUsageMetadata( + candidates_token_count=1086, + prompt_token_count=7, + prompt_tokens_details=[ + types.ModalityTokenCount( + modality=types.MediaModality.TEXT, + token_count=7 + ) + ], + thoughts_token_count=860, + total_token_count=1953 + ) + ) + + expected = textwrap.dedent(""" + GenerateContentResponse( + automatic_function_calling_history=[], + candidates=[ + Candidate( + content=Content( + parts=[ + Part( + text=\"\"\"There isn't a single "best" LLM, as the ideal choice highly depends on your specific needs, use case, budget, and priorities. The field is evolving incredibly fast, with new models and improvements being released constantly. + + However, we can talk about the **leading contenders** and what they are generally known for:...\"\"\" + ), + ], + role='model' + ), + finish_reason=, + index=0 + ), + ], + model_version='models/gemini-2.5-flash-preview-05-20', + usage_metadata=GenerateContentResponseUsageMetadata( + candidates_token_count=1086, + prompt_token_count=7, + prompt_tokens_details=[ + ModalityTokenCount( + modality=, + token_count=7 + ), + ], + thoughts_token_count=860, + total_token_count=1953 + ) + ) + """).strip() + assert repr(obj) == expected + + +def test_move_value_by_path(): + """Test move_value_by_path function with array wildcard notation.""" + data = { + "requests": [ + { + "request": { + "content": { + "parts": [ + { + "text": "1" + } + ] + } + }, + "outputDimensionality": 64 + }, + { + "request": { + "content": { + "parts": [ + { + "text": "2" + } + ] + } + }, + "outputDimensionality": 64 + }, + { + "request": { + "content": { + "parts": [ + { + "text": "3" + } + ] + } + }, + "outputDimensionality": 64 + } + ] + } + + paths = {'requests[].*': 'requests[].request.*'} + _common.move_value_by_path(data, paths) + + expected = { + "requests": [ + { + "request": { + "content": { + "parts": [ + { + "text": "1" + } + ] + }, + "outputDimensionality": 64 + } + }, + { + "request": { + "content": { + "parts": [ + { + "text": "2" + } + ] + }, + "outputDimensionality": 64 + } + }, + { + "request": { + "content": { + "parts": [ + { + "text": "3" + } + ] + }, + "outputDimensionality": 64 + } + } + ] + } + + assert data == expected + + +def test_check_field_type_mismatches_no_warning_for_correct_types(caplog): + """Test that no warning is logged when types match.""" + + class ModelA(_common.BaseModel): + value: int + + class TestModel(_common.BaseModel): + model_a: ModelA + + # Should not warn - dict will be converted to ModelA by Pydantic + data = {"model_a": {"value": 123}} + + with caplog.at_level(logging.WARNING, logger="google_genai._common"): + result = TestModel.model_validate(data) + + assert result.model_a.value == 123 + assert len(caplog.records) == 0 + + +def test_check_field_type_mismatches_warns_on_pydantic_type_mismatch(caplog): + """Test that warning is logged when Pydantic model types mismatch.""" + + class ModelA(_common.BaseModel): + value: int + + class ModelB(_common.BaseModel): + value: str + + class TestModel(_common.BaseModel): + model_field: ModelA + + # Create an instance of ModelB (wrong type) + model_b_instance = ModelB(value="test") + + # Pass the wrong Pydantic model instance + data = {"model_field": model_b_instance} + + with caplog.at_level(logging.WARNING, logger="google_genai._common"): + TestModel._check_field_type_mismatches(data) + + assert len(caplog.records) == 1 + assert "Type mismatch in TestModel.model_field" in caplog.records[0].message + assert "expected ModelA, got ModelB" in caplog.records[0].message + + +def test_check_field_type_mismatches_no_warning_for_none_values(caplog): + """Test that no warning is logged for None values.""" + + class ModelA(_common.BaseModel): + value: int + + class TestModel(_common.BaseModel): + model_field: Optional[ModelA] = None + + data = {"model_field": None} + + with caplog.at_level(logging.WARNING, logger="google_genai._common"): + result = TestModel.model_validate(data) + + assert result.model_field is None + assert len(caplog.records) == 0 + + +def test_check_field_type_mismatches_no_warning_for_missing_fields(caplog): + """Test that no warning is logged for missing fields.""" + + class ModelA(_common.BaseModel): + value: int + + class TestModel(_common.BaseModel): + model_field: Optional[ModelA] = None + + data = {} + + with caplog.at_level(logging.WARNING, logger="google_genai._common"): + result = TestModel.model_validate(data) + + assert result.model_field is None + assert len(caplog.records) == 0 + + +def test_check_field_type_mismatches_no_warning_for_primitive_types(caplog): + """Test that no warning is logged for primitive type mismatches.""" + + class TestModel(_common.BaseModel): + int_field: int + str_field: str + + # Even though we're passing wrong primitive types, we should not warn + # (Pydantic will handle validation) + data = {"int_field": "123", "str_field": "test"} + + with caplog.at_level(logging.WARNING, logger="google_genai._common"): + # This will succeed because Pydantic can coerce "123" to int + result = TestModel.model_validate(data) + + assert result.int_field == 123 + assert result.str_field == "test" + assert len(caplog.records) == 0 + + +def test_check_field_type_mismatches_handles_optional_unwrapping(caplog): + """Test that Optional types are properly unwrapped before checking.""" + + class ModelA(_common.BaseModel): + value: int + + class ModelB(_common.BaseModel): + value: str + + class TestModel(_common.BaseModel): + model_field: Optional[ModelA] = None + + # Pass wrong Pydantic model type + model_b_instance = ModelB(value="test") + data = {"model_field": model_b_instance} + + with caplog.at_level(logging.WARNING, logger="google_genai._common"): + TestModel._check_field_type_mismatches(data) + + assert len(caplog.records) == 1 + assert "expected ModelA, got ModelB" in caplog.records[0].message + + +def test_check_field_type_mismatches_no_warning_for_correct_pydantic_instance(caplog): + """Test that no warning is logged when correct Pydantic instance is provided.""" + + class ModelA(_common.BaseModel): + value: int + + class TestModel(_common.BaseModel): + model_field: ModelA + + # Pass correct Pydantic model instance + model_a_instance = ModelA(value=42) + data = {"model_field": model_a_instance} + + with caplog.at_level(logging.WARNING, logger="google_genai._common"): + result = TestModel.model_validate(data) + + assert result.model_field.value == 42 + assert len(caplog.records) == 0 + + +def test_check_field_type_mismatches_with_multiple_fields(caplog): + """Test checking multiple fields with mixed scenarios.""" + + class ModelA(_common.BaseModel): + value: int + + class ModelB(_common.BaseModel): + value: str + + class TestModel(_common.BaseModel): + field_a: ModelA + field_b: Optional[ModelA] = None + field_c: str + + model_b_instance = ModelB(value="wrong") + data = { + "field_a": model_b_instance, # Wrong type - should warn + "field_b": None, # None - should not warn + "field_c": "test", # Primitive - should not warn + } + + with caplog.at_level(logging.WARNING, logger="google_genai._common"): + TestModel._check_field_type_mismatches(data) + + # Should only warn about field_a + assert len(caplog.records) == 1 + assert "field_a" in caplog.records[0].message + assert "expected ModelA, got ModelB" in caplog.records[0].message + + +def test_check_field_type_mismatches_generic_type_no_error(caplog): + """Test that validation doesn't crash on generic types like list[str].""" + class TestModel(_common.BaseModel): + tags: list[str] + + data = {"tags": ["a", "b"]} + + with caplog.at_level(logging.WARNING, logger="google_genai._common"): + TestModel.model_validate(data) + + assert len(caplog.records) == 0 diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/common/test_duck_type.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/common/test_duck_type.py new file mode 100644 index 0000000000000000000000000000000000000000..bddee485c54ec3b078d065c5ed7c6a692deb6a37 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/common/test_duck_type.py @@ -0,0 +1,96 @@ +import unittest + +import pydantic + +from ... import _common + + +class TestIsDuckTypeOf(unittest.TestCase): + + class FakePydanticModel(pydantic.BaseModel): + field1: str + field2: int + field3: str + field4: str + field5: str + + class FakePydanticModelWithLessFields(pydantic.BaseModel): + field1: str + field2: int + field3: str + field4: str + + def test_is_duck_type_of_true_for_pydantic_object(self): + obj = self.FakePydanticModel( + field1="a", + field2=1, + field3="b", + field4="c", + field5="d", + ) + self.assertTrue(_common.is_duck_type_of(obj, self.FakePydanticModel)) + + def test_is_duck_type_of_true_for_duck_typed_object(self): + class DuckTypedObject: + + def __init__(self): + self.field1 = "a" + self.field2 = 1 + self.field3 = "b" + self.field4 = "c" + self.field5 = "d" + + obj = DuckTypedObject() + self.assertTrue(_common.is_duck_type_of(obj, self.FakePydanticModel)) + + def test_is_duck_type_of_false_for_different_many_fields(self): + class DifferentFieldsObject: + + def __init__(self): + self.fielda = "a" + + obj = DifferentFieldsObject() + self.assertFalse( + _common.is_duck_type_of(obj, self.FakePydanticModel) + ) + + def test_is_duck_type_of_false_for_missing_fields(self): + + obj = self.FakePydanticModelWithLessFields( + field1="a", field2=1, field3="b", field4="c" + ) + self.assertFalse(_common.is_duck_type_of(obj, self.FakePydanticModel)) + + def test_is_duck_type_of_false_for_dict(self): + obj = {"field1": "a", "field2": 1} + self.assertFalse( + _common.is_duck_type_of(obj, self.FakePydanticModel) + ) + + def test_is_duck_type_of_false_for_non_pydantic_class(self): + class NonPydanticModel: + pass + + class SomeObject: + pass + + obj = SomeObject() + self.assertFalse(_common.is_duck_type_of(obj, NonPydanticModel)) + + def test_is_duck_type_of_true_with_extra_fields(self): + class ExtraFieldsObject: + + def __init__(self): + self.field1 = "a" + self.field2 = 1 + self.field3 = "extra" + self.field4 = "extra" + self.field5 = "extra" + self.field6 = "extra" + + obj = ExtraFieldsObject() + self.assertTrue(_common.is_duck_type_of(obj, self.FakePydanticModel)) + + +if __name__ == "__main__": + unittest.main() diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/conftest.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..03b8136315766cd2c7a24c93c6b3d9432faff45a --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/conftest.py @@ -0,0 +1,162 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Conftest for google.genai tests.""" + +import datetime +import os +from unittest import mock +import uuid +import pytest + +from .. import _common +from .. import _replay_api_client +from .. import client as google_genai_client_module + + +def pytest_addoption(parser): + parser.addoption( + '--mode', + action='store', + default='auto', + help="""Replay mode. + One of: + * auto: Replay if replay files exist, otherwise record. + * record: Always call the API and record. + * replay: Always replay, fail if replay files do not exist. + * api: Always call the API and do not record. + * tap: Always replay, fail if replay files do not exist. Also sets default values for the API key and replay directory. +""", + ) + parser.addoption( + '--private', + action='store_true', + default=False, + help='Run private tests.', + ) + + +# Overridden via parameterized test. +@pytest.fixture +def use_vertex(): + return False + + +# Overridden at the module level for each test file. +@pytest.fixture +def replays_prefix(): + return 'test' + + +def _get_replay_id(use_vertex: bool, replays_prefix: str) -> str: + test_name_ending = os.environ.get('PYTEST_CURRENT_TEST').split('::')[-1] + test_name = ( + test_name_ending.split(' ')[0].split('[')[0] + + '.' + + ('vertex' if use_vertex else 'mldev') + ) + return '/'.join([replays_prefix, test_name]) + + +@pytest.fixture +def client(use_vertex, replays_prefix, http_options, request): + mode = request.config.getoption('--mode') + if mode not in ['auto', 'record', 'replay', 'api', 'tap']: + raise ValueError('Invalid mode: ' + mode) + test_function_name = request.function.__name__ + test_filename = os.path.splitext(os.path.basename(request.path))[0] + if test_function_name.startswith(test_filename): + raise ValueError(f""" + {test_function_name}: + Do not include the test filename in the test function name. + keep the test function name short.""") + for word in ['mldev', 'ml_dev', 'vertex']: + if word in test_function_name: + raise ValueError(f""" + {test_function_name}: + You should never ever include api types in the file name (mldev or vertex). + All tests should run against all apis. + Assert an exception if the test is not supported in an API.""") + replay_id = _get_replay_id(use_vertex, replays_prefix) + + if mode == 'tap': + mode = 'replay' + + # Set various environment variables to ensure that the test runs. + os.environ['GOOGLE_API_KEY'] = 'dummy-api-key' + os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = os.path.join( + os.path.dirname(__file__), + 'credentials.json', + ) + os.environ['GOOGLE_CLOUD_PROJECT'] = 'project-id' + os.environ['GOOGLE_CLOUD_LOCATION'] = 'location' + + # Set the replay directory to the root directory of the replays. + # This is needed to ensure that the replay files are found. + replays_root_directory = os.path.abspath( + os.path.join( + os.path.dirname(__file__), + '../../../../../google/cloud/aiplatform/sdk/genai/replays', + ) + ) + os.environ['GOOGLE_GENAI_REPLAYS_DIRECTORY'] = replays_root_directory + # Get private arg. + private = request.config.getoption('--private') + replay_client = _replay_api_client.ReplayApiClient( + mode=mode, + replay_id=replay_id, + vertexai=use_vertex, + http_options=http_options, + private=private, + ) + + with mock.patch.object( + google_genai_client_module.Client, '_get_api_client' + ) as patch_method: + patch_method.return_value = replay_client + google_genai_client = google_genai_client_module.Client(vertexai=use_vertex) + + # Yield the client so that cleanup can be completed at the end of the test. + yield google_genai_client + + # Save the replay after the test if we were in recording mode. + google_genai_client._api_client.close() + + +@pytest.fixture +def mock_timestamped_unique_name(): + with mock.patch.object( + _common, + 'timestamped_unique_name', + return_value='20240101000000_bd656', + ) as unique_name_mock: + yield unique_name_mock + + +@pytest.fixture +def image_jpeg(): + import PIL.Image + image_path = os.path.join(os.path.dirname(__file__), 'data', 'google.jpg') + with PIL.Image.open(image_path) as img: + yield img + + +@pytest.fixture +def image_png(): + import PIL.Image + image_path = os.path.join(os.path.dirname(__file__), 'data', 'google.png') + with PIL.Image.open(image_path) as img: + yield img diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/documents/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/documents/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6755796439d16ff1d17c166c76ed00f9834ad502 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/documents/__init__.py @@ -0,0 +1,17 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for the Google GenAI SDK's documents module.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/documents/test_delete.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/documents/test_delete.py new file mode 100644 index 0000000000000000000000000000000000000000..589e4df0082f5233065e06051abc9b2053c0f57c --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/documents/test_delete.py @@ -0,0 +1,51 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +"""Tests for documents.delete().""" + +import pytest + +from ... import types +from .. import pytest_helper + +# All tests will be run for both Vertex and MLDev. +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name="test_delete", + parameters=types._DeleteDocumentParameters( + name=( + "fileSearchStores/fr3l0ri2so25-a3r1ump9x821/documents/asurveyofmodernistpoetrytxt-01zyb2rig5gu" + ), + config=types.DeleteDocumentConfig(force=True), + ), + exception_if_vertex="only supported in the Gemini Developer client", + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method="file_search_stores.documents.delete", + test_table=test_table, +) + + +@pytest.mark.asyncio +async def test_async_delete(client): + with pytest_helper.exception_if_vertex(client, ValueError): + await client.aio.file_search_stores.documents.delete( + name="fileSearchStores/fr3l0ri2so25-a3r1ump9x821/documents/asurveyofmodernistpoetrytxt-uvmqjtmkm1h2", + config=types.DeleteDocumentConfig(force=True), + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/documents/test_get.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/documents/test_get.py new file mode 100644 index 0000000000000000000000000000000000000000..8f1ebb44a81ffd1bf2b12a34d4d04488af7b03fb --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/documents/test_get.py @@ -0,0 +1,85 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for file_search_stores.documents.get().""" + +import pytest + +from ... import types +from .. import pytest_helper + +# A Document name known to exist in the test environment. +# Replace with a real one from your test setup. +_EXISTING_DOCUMENT_NAME = "fileSearchStores/fr3l0ri2so25-a3r1ump9x821/documents/asurveyofmodernistpoetrytxt-uvmqjtmkm1h2" +_NON_EXISTENT_DOCUMENT_NAME = ( + "fileSearchStores/fr3l0ri2so25-a3r1ump9x821/documents/non-existent-document" +) +_INVALID_DOCUMENT_NAME = "fileSearchStores/fr3l0ri2so25-a3r1ump9x821/documents/_invalid_document_name" +_NOT_A_DOCUMENT_NAME = "genai-test-document" + +# All tests will be run for both Vertex and MLDev. +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name="test_get_success", + parameters=types._GetDocumentParameters(name=_EXISTING_DOCUMENT_NAME), + exception_if_vertex="only supported in the Gemini Developer client", + ), + pytest_helper.TestTableItem( + name="test_get_not_found", + parameters=types._GetDocumentParameters( + name=_NON_EXISTENT_DOCUMENT_NAME + ), + exception_if_vertex="only supported in the Gemini Developer client", + exception_if_mldev="Documents does not exist", + ), + pytest_helper.TestTableItem( + name="test_get_invalid_name", + parameters=types._GetDocumentParameters(name=_INVALID_DOCUMENT_NAME), + exception_if_vertex="only supported in the Gemini Developer client", + # Validation should catch this before the API call + exception_if_mldev="INVALID_ARGUMENT", + ), + pytest_helper.TestTableItem( + name="test_get_not_a_document_name", + parameters=types._GetDocumentParameters(name=_NOT_A_DOCUMENT_NAME), + exception_if_vertex="only supported in the Gemini Developer client", + exception_if_mldev="Not Found", + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method="file_search_stores.documents.get", + test_table=test_table, +) + + +@pytest.mark.asyncio +async def test_async_get(client): + with pytest_helper.exception_if_vertex(client, ValueError): + # This test relies on the mocking/replays set up by pytest_helper + # For a success case: + try: + document = await client.aio.file_search_stores.documents.get( + name=_EXISTING_DOCUMENT_NAME + ) + assert document is not None + assert document.name == _EXISTING_DOCUMENT_NAME + except Exception as e: + # Depending on the mock setup, errors might be raised directly + print(f"Async get failed: {e}") + raise diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/documents/test_list.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/documents/test_list.py new file mode 100644 index 0000000000000000000000000000000000000000..5caf120203a34799b6117041bd6ae20051171b90 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/documents/test_list.py @@ -0,0 +1,72 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +"""Tests for file_search_stores.documents.list().""" + +import pytest + +from ... import types +from .. import pytest_helper + +_FILE_SEARCH_STORE_NAME = "fileSearchStores/gzn7kdl2wpxl-4z2yqvuxbcxw" + +# All tests will be run for both Vertex and MLDev. +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name="test_list_default", + parameters=types._ListDocumentsParameters( + parent=_FILE_SEARCH_STORE_NAME + ), + exception_if_vertex="only supported in the Gemini Developer client", + ), + pytest_helper.TestTableItem( + name="test_list_with_page_size", + parameters=types._ListDocumentsParameters( + parent=_FILE_SEARCH_STORE_NAME, + config=types.ListDocumentsConfig( + page_size=2, + ), + ), + exception_if_vertex="only supported in the Gemini Developer client", + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method="file_search_stores.documents.list", + test_table=test_table, + http_options={ + "base_url": "https://autopush-generativelanguage.sandbox.googleapis.com/", + } +) + + +def test_pager(client): + with pytest_helper.exception_if_vertex(client, ValueError): + # Iterate through the first page. + for document in client.file_search_stores.documents.list( + parent=_FILE_SEARCH_STORE_NAME, config={"page_size": 2} + ): + assert isinstance(document, types.Document) + +@pytest.mark.asyncio +async def test_async_pager(client): + with pytest_helper.exception_if_vertex(client, ValueError): + # Iterate through the first page. + async for document in await client.aio.file_search_stores.documents.list( + parent=_FILE_SEARCH_STORE_NAME, config={"page_size": 2} + ): + assert isinstance(document, types.Document) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/errors/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/errors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..38d793ec16dcf705e47ddc1d2790edb28239618b --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/errors/__init__.py @@ -0,0 +1 @@ +"""Unit Tests for the error modules.""" \ No newline at end of file diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/errors/test_api_error.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/errors/test_api_error.py new file mode 100644 index 0000000000000000000000000000000000000000..bb269da433012f079a5d1ae4c8cdc93c905671c7 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/errors/test_api_error.py @@ -0,0 +1,454 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Unit Tests for the APIError class. + +End to end tests should be in models/test_generate_content.py. +""" + +import pickle + +import httpx +import pytest + +from ... import errors + + +def test_constructor_code_none_error_in_json_code_in_error(): + + actual_error = errors.APIError( + None, + { + 'error': { + 'code': 400, + 'message': 'error message', + 'status': 'INVALID_ARGUMENT', + } + }, + httpx.Response(status_code=400), + ) + + assert actual_error.code == 400 + assert actual_error.message == 'error message' + assert actual_error.status == 'INVALID_ARGUMENT' + assert actual_error.details == { + 'error': { + 'code': 400, + 'message': 'error message', + 'status': 'INVALID_ARGUMENT', + } + } + + +def test_constructor_code_none_error_in_json_code_outside_error(): + + actual_error = errors.APIError( + None, + { + 'code': 400, + 'error': { + 'code': 500, + 'message': 'error message', + 'status': 'INVALID_ARGUMENT', + }, + }, + httpx.Response(status_code=400), + ) + + assert actual_error.code == 400 + assert actual_error.message == 'error message' + assert actual_error.status == 'INVALID_ARGUMENT' + assert actual_error.details == { + 'code': 400, + 'error': { + 'code': 500, + 'message': 'error message', + 'status': 'INVALID_ARGUMENT', + }, + } + + +def test_constructor_code_not_present(): + + actual_error = errors.APIError( + None, + { + 'error': { + 'message': 'error message', + 'status': 'INVALID_ARGUMENT', + } + }, + httpx.Response(status_code=400), + ) + + assert actual_error.code is None + assert actual_error.message == 'error message' + assert actual_error.status == 'INVALID_ARGUMENT' + assert actual_error.details == { + 'error': { + 'message': 'error message', + 'status': 'INVALID_ARGUMENT', + } + } + + +def test_constructor_code_exist_error_in_json(): + + actual_error = errors.APIError( + 400, + { + 'error': { + 'code': 400, + 'message': 'error message', + 'status': 'INVALID_ARGUMENT', + } + }, + httpx.Response(status_code=400), + ) + + assert actual_error.code == 400 + assert actual_error.message == 'error message' + assert actual_error.status == 'INVALID_ARGUMENT' + assert actual_error.details == { + 'error': { + 'code': 400, + 'message': 'error message', + 'status': 'INVALID_ARGUMENT', + } + } + + +def test_constructor_error_not_in_json(): + + actual_error = errors.APIError( + 400, + { + 'message': 'error message', + 'status': 'INVALID_ARGUMENT', + 'code': 400, + }, + httpx.Response(status_code=400), + ) + + assert actual_error.code == 400 + assert actual_error.message == 'error message' + assert actual_error.status == 'INVALID_ARGUMENT' + assert actual_error.details == { + 'message': 'error message', + 'status': 'INVALID_ARGUMENT', + 'code': 400, + } + + +def test_constructor_error_in_json_status_outside_error(): + + actual_error = errors.APIError( + 400, + { + 'status': 'OUTER_INVALID_ARGUMENT_STATUS', + 'error': { + 'code': 400, + 'message': 'error message', + 'status': 'INNER_INVALID_ARGUMENT_STATUS', + }, + }, + httpx.Response(status_code=400), + ) + + assert actual_error.code == 400 + assert actual_error.message == 'error message' + assert actual_error.status == 'OUTER_INVALID_ARGUMENT_STATUS' + assert actual_error.details == { + 'status': 'OUTER_INVALID_ARGUMENT_STATUS', + 'error': { + 'code': 400, + 'message': 'error message', + 'status': 'INNER_INVALID_ARGUMENT_STATUS', + }, + } + + +def test_constructor_status_not_present(): + + actual_error = errors.APIError( + 400, + { + 'error': { + 'code': 400, + 'message': 'error message', + } + }, + httpx.Response(status_code=400), + ) + + assert actual_error.code == 400 + assert actual_error.message == 'error message' + assert actual_error.status == None + assert actual_error.details == { + 'error': { + 'code': 400, + 'message': 'error message', + } + } + + +def test_constructor_error_in_json_message_outside_error(): + + actual_error = errors.APIError( + 400, + { + 'message': 'OUTER_ERROR_MESSAGE', + 'error': { + 'code': 400, + 'message': 'INNER_ERROR_MESSAGE', + 'status': 'INVALID_ARGUMENT', + }, + }, + httpx.Response(status_code=400), + ) + + assert actual_error.code == 400 + assert actual_error.message == 'OUTER_ERROR_MESSAGE' + assert actual_error.status == 'INVALID_ARGUMENT' + assert actual_error.details == { + 'message': 'OUTER_ERROR_MESSAGE', + 'error': { + 'code': 400, + 'message': 'INNER_ERROR_MESSAGE', + 'status': 'INVALID_ARGUMENT', + }, + } + + +def test_constructor_message_not_present(): + + actual_error = errors.APIError( + 400, + { + 'error': { + 'code': 400, + 'status': 'INVALID_ARGUMENT', + } + }, + httpx.Response(status_code=400), + ) + + assert actual_error.code == 400 + assert actual_error.message is None + assert actual_error.status == 'INVALID_ARGUMENT' + assert actual_error.details == { + 'error': { + 'code': 400, + 'status': 'INVALID_ARGUMENT', + } + } + + +def test_constructor_with_websocket_connection_closed_error(): + actual_error = errors.APIError( + 1007, + 'At most one response modality can be specified in the setup request.' + ' To enable simultaneous transcription and audio output,', + None, + ) + assert actual_error.code == 1007 + assert ( + actual_error.details + == 'At most one response modality can be specified in the setup request.' + ' To enable simultaneous transcription and audio output,' + ) + assert actual_error.status == None + assert actual_error.message == None + + +def test_raise_for_websocket_connection_closed_error(): + try: + errors.APIError.raise_error( + 1007, + 'At most one response modality can be specified in the setup request.' + ' To enable simultaneous transcription and audio output,', + None, + ) + except errors.APIError as actual_error: + assert actual_error.code == 1007 + assert ( + actual_error.details + == 'At most one response modality can be specified in the setup' + ' request.' + ' To enable simultaneous transcription and audio output,' + ) + assert actual_error.status == None + assert actual_error.message == None + + +def test_raise_for_response_code_exist_json_decoder_error(): + class FakeResponse(httpx.Response): + + def read(self) -> bytes: + self._content = b'{"data": {"key1": "value1", "key2"}' + return self._content + + try: + errors.APIError.raise_for_response( + FakeResponse( + status_code=503, + extensions={'reason_phrase': b'Service Unavailable'}, + ) + ) + except errors.ServerError as actual_error: + assert actual_error.code == 503 + assert actual_error.message == '{"data": {"key1": "value1", "key2"}' + assert actual_error.status == 'Service Unavailable' + assert actual_error.details == { + 'message': '{"data": {"key1": "value1", "key2"}', + 'status': 'Service Unavailable', + } + + +def test_raise_for_response_client_error(): + class FakeResponse(httpx.Response): + + def read(self) -> bytes: + self._content = ( + b'{"error": {"code": 400, "message": "error message", "status":' + b' "INVALID_ARGUMENT"}}' + ) + return self._content + + try: + errors.APIError.raise_for_response(FakeResponse(status_code=400)) + except errors.ClientError as actual_error: + assert actual_error.code == 400 + assert actual_error.message == 'error message' + assert actual_error.status == 'INVALID_ARGUMENT' + assert actual_error.details == { + 'error': { + 'code': 400, + 'message': 'error message', + 'status': 'INVALID_ARGUMENT', + } + } + + +def test_raise_for_response_server_error(): + class FakeResponse(httpx.Response): + + def read(self) -> bytes: + self._content = ( + b'{"error": {"code": 500, "message": "error message", "status":' + b' "SERVER_INTERNAL ERROR"}}' + ) + return self._content + + try: + errors.APIError.raise_for_response(FakeResponse(status_code=500)) + except errors.ServerError as actual_error: + assert actual_error.code == 500 + assert actual_error.message == 'error message' + assert actual_error.status == 'SERVER_INTERNAL ERROR' + assert actual_error.details == { + 'error': { + 'code': 500, + 'message': 'error message', + 'status': 'SERVER_INTERNAL ERROR', + } + } + + +def test_api_error_is_picklable(): + pickled_error = pickle.loads(pickle.dumps(errors.APIError(1, {}))) + assert isinstance(pickled_error, errors.APIError) + + +@pytest.mark.asyncio +async def test_raise_for_async_response_client_error(): + class FakeResponse(httpx.Response): + + async def aread(self) -> bytes: + self._content = ( + b'{"error": {"code": 400, "message": "error message", "status":' + b' "INVALID_ARGUMENT"}}' + ) + return self._content + + try: + await errors.APIError.raise_for_async_response( + FakeResponse(status_code=400) + ) + except errors.ClientError as actual_error: + assert actual_error.code == 400 + assert actual_error.message == 'error message' + assert actual_error.status == 'INVALID_ARGUMENT' + assert actual_error.details == { + 'error': { + 'code': 400, + 'message': 'error message', + 'status': 'INVALID_ARGUMENT', + } + } + + +@pytest.mark.asyncio +async def test_raise_for_async_response_server_error(): + class FakeResponse(httpx.Response): + + async def aread(self) -> bytes: + self._content = ( + b'{"error": {"code": 500, "message": "error message", "status":' + b' "SERVER_INTERNAL ERROR"}}' + ) + return self._content + + try: + await errors.APIError.raise_for_async_response( + FakeResponse(status_code=500) + ) + except errors.ServerError as actual_error: + assert actual_error.code == 500 + assert actual_error.message == 'error message' + assert actual_error.status == 'SERVER_INTERNAL ERROR' + assert actual_error.details == { + 'error': { + 'code': 500, + 'message': 'error message', + 'status': 'SERVER_INTERNAL ERROR', + } + } + + +@pytest.mark.asyncio +async def test_raise_for_async_response_code_exist_json_decoder_error(): + class FakeResponse(httpx.Response): + + async def aread(self) -> bytes: + self._content = b'{"data": {"key1": "value1", "key2"}' + return self._content + + try: + await errors.APIError.raise_for_async_response( + FakeResponse( + status_code=503, + extensions={'reason_phrase': b'Service Unavailable'}, + ) + ) + except errors.ServerError as actual_error: + assert actual_error.code == 503 + assert actual_error.message == '{"data": {"key1": "value1", "key2"}' + assert actual_error.status == 'Service Unavailable' + assert actual_error.details == { + 'message': '{"data": {"key1": "value1", "key2"}', + 'status': 'Service Unavailable', + } diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/file_search_stores/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/file_search_stores/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f145f7beca07a5e1a6d3abd5e952800cb441b0aa --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/file_search_stores/__init__.py @@ -0,0 +1,17 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for the Google GenAI SDK's file search stores module.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/file_search_stores/test_create.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/file_search_stores/test_create.py new file mode 100644 index 0000000000000000000000000000000000000000..940f62a821095f75b8f59f714692d3e571c8eb3c --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/file_search_stores/test_create.py @@ -0,0 +1,66 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for file_search_stores.create().""" + +import pytest + +from ... import types +from .. import pytest_helper + +# All tests will be run for both Vertex and MLDev. +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name="test_display_name", + parameters=types._CreateFileSearchStoreParameters( + config=types.CreateFileSearchStoreConfig( + display_name="My File Search Store" + ) + ), + exception_if_vertex="only supported in the Gemini Developer client", + ), + pytest_helper.TestTableItem( + name="test_basic", + parameters=types._CreateFileSearchStoreParameters(), + exception_if_vertex="only supported in the Gemini Developer client", + ), +] + +pytestmark = [ + pytest.mark.usefixtures("mock_timestamped_unique_name"), + pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method="file_search_stores.create", + test_table=test_table, + ), +] + + +@pytest.mark.asyncio +async def test_async_display_name(client): + with pytest_helper.exception_if_vertex(client, ValueError): + file_search_store = await client.aio.file_search_stores.create( + config=types.CreateFileSearchStoreConfig( + display_name="My File Search Store" + ) + ) + + +@pytest.mark.asyncio +async def test_async_basic(client): + with pytest_helper.exception_if_vertex(client, ValueError): + file_search_store = await client.aio.file_search_stores.create() diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/file_search_stores/test_delete.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/file_search_stores/test_delete.py new file mode 100644 index 0000000000000000000000000000000000000000..97487c831f8844e47fae3937a09842d24e259973 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/file_search_stores/test_delete.py @@ -0,0 +1,64 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +"""Tests for file_search_stores.delete().""" + +import pytest + +from ... import types +from .. import pytest_helper + +# All tests will be run for both Vertex and MLDev. +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name="test_delete_with_name", + parameters=types._DeleteFileSearchStoreParameters( + name="fileSearchStores/acxjj7m366ln-aw6xyp94icll", + ), + exception_if_vertex="only supported in the Gemini Developer client", + ), + pytest_helper.TestTableItem( + name="test_delete_with_name_and_force", + parameters=types._DeleteFileSearchStoreParameters( + name="fileSearchStores/7igesc9r2zw9-0mpxpsqubv7s", + config=types.DeleteFileSearchStoreConfig(force=True), + ), + exception_if_vertex="only supported in the Gemini Developer client", + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method="file_search_stores.delete", + test_table=test_table, +) + + +@pytest.mark.asyncio +async def test_async_delete(client): + with pytest_helper.exception_if_vertex(client, ValueError): + await client.aio.file_search_stores.delete( + name="fileSearchStores/my-file-search-store-l65kcyel9lkz" + ) + + +@pytest.mark.asyncio +async def test_async_force_delete(client): + with pytest_helper.exception_if_vertex(client, ValueError): + await client.aio.file_search_stores.delete( + name="fileSearchStores/my-file-search-store-vjtrjw6re8oz", + config=types.DeleteFileSearchStoreConfig(force=True), + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/file_search_stores/test_get.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/file_search_stores/test_get.py new file mode 100644 index 0000000000000000000000000000000000000000..897c7381a1ac311a3a87f8db0ff8065de7f1e2b4 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/file_search_stores/test_get.py @@ -0,0 +1,94 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for file_search_stores.get().""" + +import pytest + +from ... import types +from .. import pytest_helper + +# A FileSearchStore name known to exist in the test environment. +# Replace with a real one from your test setup. +_EXISTING_FILE_SEARCH_STORE_NAME = "fileSearchStores/5en07ei3kojo-yo8sjqgvx2xf" +_NON_EXISTENT_FILE_SEARCH_STORE_NAME = ( + "fileSearchStores/non-existent-file-search-store" +) +_INVALID_FILE_SEARCH_STORE_NAME = ( + "fileSearchStores/_invalid_file_search_store_name" +) +_NOT_A_FILE_SEARCH_STORE_NAME = "genai-test-file-search-store" + +# All tests will be run for both Vertex and MLDev. +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name="test_get_success", + parameters=types._GetFileSearchStoreParameters( + name=_EXISTING_FILE_SEARCH_STORE_NAME + ), + exception_if_vertex="only supported in the Gemini Developer client", + ), + pytest_helper.TestTableItem( + name="test_get_not_found", + parameters=types._GetFileSearchStoreParameters( + name=_NON_EXISTENT_FILE_SEARCH_STORE_NAME + ), + exception_if_vertex="only supported in the Gemini Developer client", + # Expect an exception to be raised by the mock + exception_if_mldev="PERMISSION_DENIED", + ), + pytest_helper.TestTableItem( + name="test_get_invalid_name", + parameters=types._GetFileSearchStoreParameters( + name=_INVALID_FILE_SEARCH_STORE_NAME + ), + exception_if_vertex="only supported in the Gemini Developer client", + # Validation should catch this before the API call + exception_if_mldev="INVALID_ARGUMENT", + ), + pytest_helper.TestTableItem( + name="test_get_not_a_file_search_store_name", + parameters=types._GetFileSearchStoreParameters( + name=_NOT_A_FILE_SEARCH_STORE_NAME + ), + exception_if_vertex="only supported in the Gemini Developer client", + exception_if_mldev="Not Found", + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method="file_search_stores.get", + test_table=test_table, +) + + +@pytest.mark.asyncio +async def test_async_get(client): + with pytest_helper.exception_if_vertex(client, ValueError): + # This test relies on the mocking/replays set up by pytest_helper + # For a success case: + try: + file_search_store = await client.aio.file_search_stores.get( + name=_EXISTING_FILE_SEARCH_STORE_NAME + ) + assert file_search_store is not None + assert file_search_store.name == _EXISTING_FILE_SEARCH_STORE_NAME + except Exception as e: + # Depending on the mock setup, errors might be raised directly + print(f"Async get failed: {e}") + raise diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/file_search_stores/test_import_file.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/file_search_stores/test_import_file.py new file mode 100644 index 0000000000000000000000000000000000000000..50c81a037a4bee47300f46a01916fe1ca1b5a4ef --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/file_search_stores/test_import_file.py @@ -0,0 +1,112 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for file_search_stores.upload_to_file_search_store().""" + +import io +import pathlib +import pytest +from ... import types +from .. import pytest_helper + +_FILE_SEARCH_STORE_NAME = 'fileSearchStores/my-store-37cbhu1nw16r' +_FILE_NAME = 'files/mk4h34zkv33d' + +test_table: list[pytest_helper.TestTableItem] = [] +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='filesearchstores.import_file', + test_table=test_table, +) + + +def test_import(client): + with pytest_helper.exception_if_vertex(client, ValueError): + operation = client.file_search_stores.import_file( + file_search_store_name=_FILE_SEARCH_STORE_NAME, file_name=_FILE_NAME + ) + + +def test_chunking(client): + with pytest_helper.exception_if_vertex(client, ValueError): + operation = client.file_search_stores.import_file( + file_search_store_name=_FILE_SEARCH_STORE_NAME, + file_name=_FILE_NAME, + config=types.ImportFileConfig( + chunking_config=types.ChunkingConfig( + white_space_config=types.WhiteSpaceConfig( + max_tokens_per_chunk=200, + max_overlap_tokens=20, + ) + ), + ), + ) + + +def test_metadata(client): + with pytest_helper.exception_if_vertex(client, ValueError): + operation = client.file_search_stores.import_file( + file_search_store_name=_FILE_SEARCH_STORE_NAME, + file_name=_FILE_NAME, + config=types.ImportFileConfig( + custom_metadata=[ + types.CustomMetadata(key='year', numeric_value=2024), + types.CustomMetadata(key='tag', string_value='story'), + ], + ), + ) + + +@pytest.mark.asyncio +async def test_async_import(client): + with pytest_helper.exception_if_vertex(client, ValueError): + operation = await client.aio.file_search_stores.import_file( + file_search_store_name=_FILE_SEARCH_STORE_NAME, + file_name=_FILE_NAME, + ) + + +@pytest.mark.asyncio +async def test_async_chunking(client): + with pytest_helper.exception_if_vertex(client, ValueError): + operation = await client.aio.file_search_stores.import_file( + file_search_store_name=_FILE_SEARCH_STORE_NAME, + file_name=_FILE_NAME, + config=types.ImportFileConfig( + chunking_config=types.ChunkingConfig( + white_space_config=types.WhiteSpaceConfig( + max_tokens_per_chunk=200, + max_overlap_tokens=20, + ) + ), + ), + ) + + +@pytest.mark.asyncio +async def test_async_metadata(client): + with pytest_helper.exception_if_vertex(client, ValueError): + operation = await client.aio.file_search_stores.import_file( + file_search_store_name=_FILE_SEARCH_STORE_NAME, + file_name=_FILE_NAME, + config=types.ImportFileConfig( + custom_metadata=[ + types.CustomMetadata(key='year', numeric_value=2024), + types.CustomMetadata(key='tag', string_value='story'), + ], + ), + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/file_search_stores/test_list.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/file_search_stores/test_list.py new file mode 100644 index 0000000000000000000000000000000000000000..7b26071313ea2eee52846ad4b6fb9289e9933e18 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/file_search_stores/test_list.py @@ -0,0 +1,57 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +"""Tests for file_search_stores.list().""" + +import pytest + +from ... import types +from .. import pytest_helper + +# All tests will be run for both Vertex and MLDev. +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name="test_list_default", + parameters=types._ListFileSearchStoresParameters(), + exception_if_vertex="only supported in the Gemini Developer client", + ), + pytest_helper.TestTableItem( + name="test_list_with_page_size", + parameters=types._ListFileSearchStoresParameters( + config=types.ListFileSearchStoresConfig( + page_size=5, + ), + ), + exception_if_vertex="only supported in the Gemini Developer client", + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method="file_search_stores.list", + test_table=test_table, +) + + +@pytest.mark.asyncio +async def test_async_pager(client): + with pytest_helper.exception_if_vertex(client, ValueError): + # Iterate through the first page. + async for file_search_store in await client.aio.file_search_stores.list( + config={"page_size": 2} + ): + assert isinstance(file_search_store, types.FileSearchStore) + break # Only check one item diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/file_search_stores/test_upload_to_file_search_store.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/file_search_stores/test_upload_to_file_search_store.py new file mode 100644 index 0000000000000000000000000000000000000000..15f10eb566e4903b4de0c171183df90aad16bc0e --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/file_search_stores/test_upload_to_file_search_store.py @@ -0,0 +1,141 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for file_search_stores.upload_to_file_search_store().""" + +import io +import pathlib +import pytest +from ... import types +from .. import pytest_helper + +_FILE_SEARCH_STORE_NAME = 'fileSearchStores/my-store-37cbhu1nw16r' + +test_table: list[pytest_helper.TestTableItem] = [] +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='filesearchstores.upload_to_file_search_store', + test_table=test_table, +) + + +def test_file_path(client): + with pytest_helper.exception_if_vertex(client, ValueError): + operation = client.file_search_stores.upload_to_file_search_store( + file_search_store_name=_FILE_SEARCH_STORE_NAME, + file='tests/data/story.pdf', + ) + + +def test_bytesio(client): + with pytest_helper.exception_if_vertex(client, ValueError): + with open('tests/data/story.pdf', 'rb') as f: + with io.BytesIO(f.read()) as buffer: + operation = client.file_search_stores.upload_to_file_search_store( + file_search_store_name=_FILE_SEARCH_STORE_NAME, + file=buffer, + config=types.UploadToFileSearchStoreConfig( + mime_type='application/pdf', + ), + ) + + +def test_chunking(client): + with pytest_helper.exception_if_vertex(client, ValueError): + operation = client.file_search_stores.upload_to_file_search_store( + file_search_store_name=_FILE_SEARCH_STORE_NAME, + file='tests/data/story.pdf', + config=types.UploadToFileSearchStoreConfig( + chunking_config=types.ChunkingConfig( + white_space_config=types.WhiteSpaceConfig( + max_tokens_per_chunk=200, + max_overlap_tokens=20, + ) + ), + ), + ) + + +def test_metadata(client): + with pytest_helper.exception_if_vertex(client, ValueError): + operation = client.file_search_stores.upload_to_file_search_store( + file_search_store_name=_FILE_SEARCH_STORE_NAME, + file='tests/data/story.pdf', + config=types.UploadToFileSearchStoreConfig( + custom_metadata=[ + types.CustomMetadata(key='year', numeric_value=2024), + types.CustomMetadata(key='tag', string_value='story'), + ], + ), + ) + + +@pytest.mark.asyncio +async def test_async_file_path(client): + with pytest_helper.exception_if_vertex(client, ValueError): + operation = await client.aio.file_search_stores.upload_to_file_search_store( + file_search_store_name=_FILE_SEARCH_STORE_NAME, + file='tests/data/story.pdf', + ) + + +@pytest.mark.asyncio +async def test_async_bytesio(client): + with pytest_helper.exception_if_vertex(client, ValueError): + with open('tests/data/story.pdf', 'rb') as f: + with io.BytesIO(f.read()) as buffer: + operation = ( + await client.aio.file_search_stores.upload_to_file_search_store( + file_search_store_name=_FILE_SEARCH_STORE_NAME, + file=buffer, + config=types.UploadToFileSearchStoreConfig( + mime_type='application/pdf', + ), + ) + ) + + +@pytest.mark.asyncio +async def test_async_chunking(client): + with pytest_helper.exception_if_vertex(client, ValueError): + operation = await client.aio.file_search_stores.upload_to_file_search_store( + file_search_store_name=_FILE_SEARCH_STORE_NAME, + file='tests/data/story.pdf', + config=types.UploadToFileSearchStoreConfig( + chunking_config=types.ChunkingConfig( + white_space_config=types.WhiteSpaceConfig( + max_tokens_per_chunk=200, + max_overlap_tokens=20, + ) + ), + ), + ) + + +@pytest.mark.asyncio +async def test_async_metadata(client): + with pytest_helper.exception_if_vertex(client, ValueError): + operation = await client.aio.file_search_stores.upload_to_file_search_store( + file_search_store_name=_FILE_SEARCH_STORE_NAME, + file='tests/data/story.pdf', + config=types.UploadToFileSearchStoreConfig( + custom_metadata=[ + types.CustomMetadata(key='year', numeric_value=2024), + types.CustomMetadata(key='tag', string_value='story'), + ], + ), + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/files/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/files/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8c2ca27aefd02f96f15a4e4a49cdd5195d11afb7 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/files/__init__.py @@ -0,0 +1,17 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for the Google GenAI SDK's files module.""" \ No newline at end of file diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/files/test_delete.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/files/test_delete.py new file mode 100644 index 0000000000000000000000000000000000000000..d3c3113b0009bd0e8634df6f4b6273c381fd056d --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/files/test_delete.py @@ -0,0 +1,46 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Test files delete method.""" + +import pytest +from ... import types +from .. import pytest_helper + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_delete', + parameters=types._DeleteFileParameters(name='files/1g583ke2xdsn'), + exception_if_vertex='only supported in the Gemini Developer client', + skip_in_api_mode=( + 'The files have a TTL, they cannot be reliably retrieved for a long' + ' time.' + ), + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='files.delete', + test_table=test_table, +) + + +@pytest.mark.asyncio +async def test_async(client): + with pytest_helper.exception_if_vertex(client, ValueError): + file = await client.aio.files.get(name='files/n1gls7dyh90q') diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/files/test_download.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/files/test_download.py new file mode 100644 index 0000000000000000000000000000000000000000..1a1627e4ffb43f924839d43c5309cdad72259080 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/files/test_download.py @@ -0,0 +1,85 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Test files upload method.""" + + +import pathlib +import pytest +from ... import _transformers as t +from ... import types +from .. import pytest_helper + + +test_table: list[pytest_helper.TestTableItem] = [] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='t.t_file_name', + test_table=test_table, +) + +pytest_plugins = ('pytest_asyncio',) + + +def test_name_transform_name(client): + with pytest_helper.exception_if_vertex(client, ValueError): + for file in client.files.list(): + if file.download_uri is not None: + break + else: + raise ValueError('No files found with a `download_uri`.') + + file_id = file.name.split('/')[-1] + video = types.Video(uri=file.download_uri) + generated_video = types.GeneratedVideo(video=video) + for f in [ + file, + file_id, + file.name, + file.uri, + file.download_uri, + video, + generated_video, + ]: + name = t.t_file_name(f) + assert name == file_id + + +def test_basic_download(client): + with pytest_helper.exception_if_vertex(client, ValueError): + for file in client.files.list(): + if file.download_uri is not None: + break + else: + raise ValueError('No files found with a `download_uri`.') + + content = client.files.download(file=file) + assert content[4:8] == b'ftyp' + + +@pytest.mark.asyncio +async def test_basic_download_async(client): + with pytest_helper.exception_if_vertex(client, ValueError): + async for file in await client.aio.files.list(): + if file.download_uri is not None: + break + else: + raise ValueError('No files found with a `download_uri`.') + + content = await client.aio.files.download(file=file) + assert content[4:8] == b'ftyp' diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/files/test_get.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/files/test_get.py new file mode 100644 index 0000000000000000000000000000000000000000..7de4172db3aaa25a671be3b3ff4bc82e8777a259 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/files/test_get.py @@ -0,0 +1,46 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Test files get method.""" + +import pytest +from ... import types +from .. import pytest_helper + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_get', + parameters=types._GetFileParameters(name='files/vjvu9fwk2qj8'), + exception_if_vertex='only supported in the Gemini Developer client', + skip_in_api_mode=( + 'The files have a TTL, they cannot be reliably retrieved for a long' + ' time.' + ), + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='files.get', + test_table=test_table, +) + + +@pytest.mark.asyncio +async def test_async(client): + with pytest_helper.exception_if_vertex(client, ValueError): + file = await client.aio.files.get(name='files/vjvu9fwk2qj8') diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/files/test_list.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/files/test_list.py new file mode 100644 index 0000000000000000000000000000000000000000..e90c307a1f1aaf2294b761397d3e0820b184b2f6 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/files/test_list.py @@ -0,0 +1,72 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Test files list method.""" + +import pytest + +from ... import types +from .. import pytest_helper + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_not_empty', + exception_if_vertex='only supported in the Gemini Developer client', + parameters=types._ListFilesParameters( + config=types.ListFilesConfig( + page_size=2, + ), + ), + ), +] +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='files.list', + test_table=test_table, +) + + +def test_pager(client): + with pytest_helper.exception_if_vertex(client, ValueError): + files = client.files.list(config={'page_size': 2}) + assert 'content-type' in files.sdk_http_response.headers + assert files.name == 'files' + assert files.page_size == 2 + assert len(files) <= 2 + + # Iterate through all the pages. Then next_page() should raise an exception. + for _ in files: + pass + with pytest.raises(IndexError, match='No more pages to fetch.'): + files.next_page() + + +@pytest.mark.asyncio +async def test_async_pager(client): + with pytest_helper.exception_if_vertex(client, ValueError): + files = await client.aio.files.list(config={'page_size': 2}) + + assert 'Content-Type' in files.sdk_http_response.headers + assert files.name == 'files' + assert files.page_size == 2 + assert len(files) <= 2 + + # Iterate through all the pages. Then next_page() should raise an exception. + async for _ in files: + pass + with pytest.raises(IndexError, match='No more pages to fetch.'): + await files.next_page() diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/files/test_register.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/files/test_register.py new file mode 100644 index 0000000000000000000000000000000000000000..eeebe90accc37be2e3560632345b155985c9c89c --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/files/test_register.py @@ -0,0 +1,272 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Test files register method.""" + +import json +from unittest import mock + +from google.auth import credentials +import httpx +import pytest + +from ... import _api_client +from ... import Client +from ... import types +from .. import pytest_helper + + +class FakeCredentials(credentials.Credentials): + + def __init__(self, token="fake_token", expired=False, quota_project_id=None): + super().__init__() + self.token = token + self._expired = expired + self._quota_project_id = quota_project_id + self.refresh_count = 0 + + @property + def expired(self): + return self._expired + + @property + def quota_project_id(self): + return self._quota_project_id + + def refresh(self, request): + self.refresh_count += 1 + self.token = "refreshed_token" + self._expired = False + + +@mock.patch.object(_api_client.BaseApiClient, "_request_once", autospec=True) +def test_simple_token(mock_request): + client = Client(api_key="dummy_key") + captured_request = None + + def side_effect(self, http_request, stream=False): + nonlocal captured_request + captured_request = http_request + return _api_client.HttpResponse( + headers={}, + response_stream=[json.dumps({"files": [{"uri": "files/abc"}]})], + ) + + mock_request.side_effect = side_effect + + with pytest_helper.exception_if_vertex(client, ValueError): + response = client.files.register_files( + auth=FakeCredentials(token="test_token"), + uris=["gs://test-bucket/test-file-1.txt"], + ) + + assert len(response.files) == 1 + assert response.files[0].uri == "files/abc" + assert captured_request.headers["authorization"] == "Bearer test_token" + + +@mock.patch.object(_api_client.BaseApiClient, "_request_once", autospec=True) +def test_token_refresh(mock_request): + client = Client(api_key="dummy_key") + captured_request = None + + def side_effect(self, http_request, stream=False): + nonlocal captured_request + captured_request = http_request + return _api_client.HttpResponse( + headers={}, + response_stream=[json.dumps({"files": [{"uri": "files/abc"}]})], + ) + + mock_request.side_effect = side_effect + + with pytest_helper.exception_if_vertex(client, ValueError): + creds = FakeCredentials(expired=True) + response = client.files.register_files( + auth=creds, + uris=["gs://test-bucket/test-file-1.txt"], + ) + assert creds.refresh_count == 1 + assert len(response.files) == 1 + assert response.files[0].uri == "files/abc" + assert captured_request.headers["authorization"] == "Bearer refreshed_token" + + +@mock.patch.object(_api_client.BaseApiClient, "_request_once", autospec=True) +def test_quota_project(mock_request): + client = Client(api_key="dummy_key") + captured_request = None + + def side_effect(self, http_request, stream=False): + nonlocal captured_request + captured_request = http_request + return _api_client.HttpResponse( + headers={}, + response_stream=[json.dumps({"files": [{"uri": "files/abc"}]})], + ) + + mock_request.side_effect = side_effect + + with pytest_helper.exception_if_vertex(client, ValueError): + creds = FakeCredentials(quota_project_id="test_project") + response = client.files.register_files( + auth=creds, + uris=["gs://test-bucket/test-file-1.txt"], + ) + assert len(response.files) == 1 + assert response.files[0].uri == "files/abc" + assert captured_request.headers["x-goog-user-project"] == "test_project" + + +@mock.patch.object(_api_client.BaseApiClient, "_request_once", autospec=True) +def test_multiple_uris(mock_request): + client = Client(api_key="dummy_key") + + def side_effect(self, http_request, stream=False): + return _api_client.HttpResponse( + headers={}, + response_stream=[ + json.dumps({"files": [{"uri": "files/abc"}, {"uri": "files/def"}]}) + ], + ) + + mock_request.side_effect = side_effect + + with pytest_helper.exception_if_vertex(client, ValueError): + response = client.files.register_files( + auth=FakeCredentials(), + uris=[ + "gs://test-bucket/test-file-1.txt", + "gs://test-bucket/test-file-2.txt", + ], + ) + assert len(response.files) == 2 + assert response.files[0].uri == "files/abc" + assert response.files[1].uri == "files/def" + + +@pytest.mark.asyncio +@mock.patch.object( + _api_client.BaseApiClient, "_async_request_once", autospec=True +) +async def test_async_single(mock_request): + client = Client(api_key="dummy_key") + + async def side_effect(self, http_request, stream=False): + return _api_client.HttpResponse( + headers={}, + response_stream=[json.dumps({"files": [{"uri": "files/abc"}]})], + ) + + mock_request.side_effect = side_effect + + with pytest_helper.exception_if_vertex(client, ValueError): + response = await client.aio.files.register_files( + auth=FakeCredentials(), + uris=["gs://test-bucket/test-file-1.txt"], + ) + + assert len(response.files) == 1 + assert response.files[0].uri == "files/abc" + + +@pytest.mark.asyncio +@mock.patch.object( + _api_client.BaseApiClient, "_async_request_once", autospec=True +) +async def test_async_token_refresh(mock_request): + client = Client(api_key="dummy_key") + captured_request = None + + async def side_effect(self, http_request, stream=False): + nonlocal captured_request + captured_request = http_request + return _api_client.HttpResponse( + headers={}, + response_stream=[json.dumps({"files": [{"uri": "files/abc"}]})], + ) + + mock_request.side_effect = side_effect + + with pytest_helper.exception_if_vertex(client, ValueError): + creds = FakeCredentials(expired=True) + response = await client.aio.files.register_files( + auth=creds, + uris=["gs://test-bucket/test-file-1.txt"], + ) + assert creds.refresh_count == 1 + assert len(response.files) == 1 + assert response.files[0].uri == "files/abc" + assert captured_request.headers["authorization"] == "Bearer refreshed_token" + + +@pytest.mark.asyncio +@mock.patch.object( + _api_client.BaseApiClient, "_async_request_once", autospec=True +) +async def test_async_quota_project(mock_request): + client = Client(api_key="dummy_key") + captured_request = None + + async def side_effect(self, http_request, stream=False): + nonlocal captured_request + captured_request = http_request + return _api_client.HttpResponse( + headers={}, + response_stream=[json.dumps({"files": [{"uri": "files/abc"}]})], + ) + + mock_request.side_effect = side_effect + + with pytest_helper.exception_if_vertex(client, ValueError): + creds = FakeCredentials(quota_project_id="test_project") + response = await client.aio.files.register_files( + auth=creds, + uris=["gs://test-bucket/test-file-1.txt"], + ) + assert len(response.files) == 1 + assert response.files[0].uri == "files/abc" + assert captured_request.headers["x-goog-user-project"] == "test_project" + + +@pytest.mark.asyncio +@mock.patch.object( + _api_client.BaseApiClient, "_async_request_once", autospec=True +) +async def test_async_multiple_uris(mock_request): + client = Client(api_key="dummy_key") + + async def side_effect(self, http_request, stream=False): + return _api_client.HttpResponse( + headers={}, + response_stream=[ + json.dumps({"files": [{"uri": "files/abc"}, {"uri": "files/def"}]}) + ], + ) + + mock_request.side_effect = side_effect + + with pytest_helper.exception_if_vertex(client, ValueError): + response = await client.aio.files.register_files( + auth=FakeCredentials(), + uris=[ + "gs://test-bucket/test-file-1.txt", + "gs://test-bucket/test-file-2.txt", + ], + ) + assert len(response.files) == 2 + assert response.files[0].uri == "files/abc" + assert response.files[1].uri == "files/def" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/files/test_register_table.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/files/test_register_table.py new file mode 100644 index 0000000000000000000000000000000000000000..5a8e43ae4736e21ed538a3e3a90dde9b82ac0ef4 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/files/test_register_table.py @@ -0,0 +1,70 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Test files get method.""" + +import pytest +from ... import types +from ... import Client +from ... import _api_client +from .. import pytest_helper +import google.auth + + +# $ gcloud config set project vertex-sdk-dev +# $ gcloud auth application-default login --no-launch-browser --scopes="https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/devstorage.read_only" +def get_headers(): + try: + credentials, _ = google.auth.default() + token = _api_client.get_token_from_credentials(None, credentials) + headers = { + "Authorization": f"Bearer {token}",} + if credentials.quota_project_id: + headers["x-goog-user-project"] = credentials.quota_project_id + except google.auth.exceptions.DefaultCredentialsError: + # So this can run in replay mode without credentials. + headers = {} + + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_register', + parameters=types._InternalRegisterFilesParameters(uris=['gs://unified-genai-dev/image.jpg']), + exception_if_vertex='only supported in the Gemini Developer client', + skip_in_api_mode=( + 'The files have a TTL, they cannot be reliably retrieved for a long' + ' time.' + ), + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='files._register_files', + test_table=test_table, + http_options={ + 'headers': get_headers(), + }, +) + + +@pytest.mark.asyncio +async def test_async(client): + with pytest_helper.exception_if_vertex(client, ValueError): + files = await client.aio.files._register_files(uris=['gs://unified-genai-dev/image.jpg']) + assert files.files + assert files.files[0].mime_type == 'image/jpeg' diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/files/test_upload.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/files/test_upload.py new file mode 100644 index 0000000000000000000000000000000000000000..c4e7826fffd540fb208097cf594769a8695ba402 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/files/test_upload.py @@ -0,0 +1,255 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Test files upload method.""" + + +import io +import pathlib +import pytest +from ... import types +from ... import errors +from .. import pytest_helper + +# Upload method is not pydantic. +test_table: list[pytest_helper.TestTableItem] = [] +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='files.upload', + test_table=test_table, +) + + +def test_image_png_upload(client): + with pytest_helper.exception_if_vertex(client, ValueError): + file = client.files.upload(file='tests/data/google.png') + assert file.name.startswith('files/') + +def test_image_png_upload_with_path(client): + with pytest_helper.exception_if_vertex(client, ValueError): + p = pathlib.Path('tests/data/google.png') + file = client.files.upload( + file=p, + config=types.UploadFileConfig(display_name='test_image_png_path'), + ) + assert file.name.startswith('files/') + +def test_image_png_upload_with_bytesio(client): + with pytest_helper.exception_if_vertex(client, ValueError): + with open('tests/data/google.png', 'rb') as f: + with io.BytesIO(f.read()) as buffer: + file = client.files.upload( + file=buffer, + config=types.UploadFileConfig(mime_type='image/png'), + ) + + assert file.name.startswith('files/') + +def test_image_png_upload_with_fd(client): + with pytest_helper.exception_if_vertex(client, ValueError): + with open('tests/data/google.png', 'rb') as f: + file = client.files.upload( + file=f, + config=types.UploadFileConfig(mime_type='image/png'), + ) + + assert file.name.startswith('files/') + +def test_image_png_upload_with_config(client): + with pytest_helper.exception_if_vertex(client, ValueError): + file = client.files.upload( + file='tests/data/google.png', + config=types.UploadFileConfig(display_name='test_image_png'), + ) + assert file.name.startswith('files/') + + +def test_image_png_upload_with_config_dict(client): + with pytest_helper.exception_if_vertex(client, ValueError): + file = client.files.upload( + file='tests/data/google.png', config={'display_name': 'test_image_png'} + ) + assert file.name.startswith('files/') + + +def test_image_jpg_upload(client): + with pytest_helper.exception_if_vertex(client, ValueError): + file = client.files.upload(file='tests/data/google.jpg') + assert file.name.startswith('files/') + + +def test_image_jpg_upload_with_config(client): + with pytest_helper.exception_if_vertex(client, ValueError): + file = client.files.upload( + file='tests/data/google.jpg', + config=types.UploadFileConfig(display_name='test_image_jpg'), + ) + assert file.name.startswith('files/') + + +def test_image_jpg_upload_with_config_dict(client): + with pytest_helper.exception_if_vertex(client, ValueError): + file = client.files.upload( + file='tests/data/google.jpg', config={'display_name': 'test_image_jpg'} + ) + assert file.name.startswith('files/') + + +def test_application_pdf_file_upload(client): + with pytest_helper.exception_if_vertex(client, ValueError): + file = client.files.upload(file='tests/data/story.pdf') + assert file.name.startswith('files/') + + +def test_application_pdf_upload_with_config(client): + with pytest_helper.exception_if_vertex(client, ValueError): + file = client.files.upload( + file='tests/data/story.pdf', + config=types.UploadFileConfig(display_name='test_application_pdf'), + ) + assert file.name.startswith('files/') + + +def test_application_pdf_upload_with_config_dict(client): + with pytest_helper.exception_if_vertex(client, ValueError): + file = client.files.upload( + file='tests/data/story.pdf', + config={'display_name': 'test_application_pdf'}, + ) + assert file.name.startswith('files/') + + +def test_video_mp4_file_upload(client): + with pytest_helper.exception_if_vertex(client, ValueError): + file = client.files.upload(file='tests/data/animal.mp4') + assert file.name.startswith('files/') + + +def test_video_mp4_upload_with_config(client): + with pytest_helper.exception_if_vertex(client, ValueError): + file = client.files.upload( + file='tests/data/animal.mp4', + config=types.UploadFileConfig(display_name='test_video_mp4'), + ) + assert file.name.startswith('files/') + + +def test_video_mp4_upload_with_config_dict(client): + with pytest_helper.exception_if_vertex(client, ValueError): + file = client.files.upload( + file='tests/data/animal.mp4', config={'display_name': 'test_video_mp4'} + ) + assert file.name.startswith('files/') + + +def test_audio_m4a_file_upload(client): + with pytest_helper.exception_if_vertex(client, ValueError): + file = client.files.upload( + file='tests/data/pixel.m4a', + config=types.UploadFileConfig(mime_type='audio/mp4'), + ) + assert file.name.startswith('files/') + + +def test_audio_m4a_upload_with_config(client): + with pytest_helper.exception_if_vertex(client, ValueError): + file = client.files.upload( + file='tests/data/pixel.m4a', + config=types.UploadFileConfig( + display_name='test_audio_m4a', mime_type='audio/mp4' + ), + ) + assert file.name.startswith('files/') + + +def test_audio_m4a_upload_with_config_dict(client): + with pytest_helper.exception_if_vertex(client, ValueError): + file = client.files.upload( + file='tests/data/pixel.m4a', + config={'display_name': 'test_audio_m4a', 'mime_type': 'audio/mp4'}, + ) + assert file.name.startswith('files/') + + +def test_bad_mime_type(client): + with pytest_helper.exception_if_vertex(client, ValueError): + with pytest.raises(errors.APIError, match="Unsupported MIME"): + file = client.files.upload( + file=io.BytesIO(b'test'), + config={'mime_type': 'bad/mime_type'}, + ) + + +@pytest.mark.asyncio +async def test_image_upload_async(client): + with pytest_helper.exception_if_vertex(client, ValueError): + file = await client.aio.files.upload(file='tests/data/google.png') + assert file.name.startswith('files/') + + +@pytest.mark.asyncio +async def test_image_upload_with_config_async(client): + with pytest_helper.exception_if_vertex(client, ValueError): + file = await client.aio.files.upload( + file='tests/data/google.png', + config=types.UploadFileConfig(display_name='test_image'), + ) + assert file.name.startswith('files/') + + +@pytest.mark.asyncio +async def test_image_upload_with_config_dict_async(client): + with pytest_helper.exception_if_vertex(client, ValueError): + file = await client.aio.files.upload( + file='tests/data/google.png', + config={ + 'display_name': 'test_image', + 'http_options': {'timeout': '8000'}, + }, + ) + assert file.name.startswith('files/') + + +@pytest.mark.asyncio +async def test_image_upload_with_bytesio_async(client): + with pytest_helper.exception_if_vertex(client, ValueError): + with open('tests/data/google.png', 'rb') as f: + buffer = io.BytesIO(f.read()) + file = await client.aio.files.upload( + file=buffer, + config=types.UploadFileConfig( + mime_type='image/png'), + ) + assert file.name.startswith('files/') + + +@pytest.mark.asyncio +async def test_unknown_path_upload_async(client): + with pytest_helper.exception_if_vertex(client, ValueError): + try: + await client.aio.files.upload(file='unknown_path') + except FileNotFoundError as e: + assert 'is not a valid file path' in str(e) + +@pytest.mark.asyncio +async def test_bad_mime_type_async(client): + with pytest_helper.exception_if_vertex(client, ValueError): + with pytest.raises(errors.APIError, match="Unsupported MIME"): + file = await client.aio.files.upload( + file=io.BytesIO(b'test'), + config={'mime_type': 'bad/mime_type'}, + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/imports/test_no_optional_imports.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/imports/test_no_optional_imports.py new file mode 100644 index 0000000000000000000000000000000000000000..a65a3d4a9025e6c87390aebc848aa0695c87ec7e --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/imports/test_no_optional_imports.py @@ -0,0 +1,28 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +import os +import pytest + +IS_NOT_GITHUB_ACTIONS = os.getenv('GITHUB_ACTIONS') != 'true' + + +@pytest.mark.skipif(IS_NOT_GITHUB_ACTIONS, + reason='This test is only run on GitHub Actions.') +def test_library_can_be_imported_without_optional_dependencies(): + """Tests that the library can be imported without optional dependencies. + """ + from google import genai + from google.genai import types diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/interactions/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/interactions/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/interactions/test_auth.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/interactions/test_auth.py new file mode 100644 index 0000000000000000000000000000000000000000..5c92a225e9c79510acf1442fa169174f6e4cd27d --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/interactions/test_auth.py @@ -0,0 +1,476 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for Interactions API.""" + +from ... import Client +from ... import _base_url +from unittest import mock +import pytest +from httpx import Request, Response +from ..._api_client import AsyncHttpxClient, BaseApiClient +from httpx import Client as HTTPClient +import os + +ENV_VARS = [ + "GOOGLE_CLOUD_PROJECT", + "GEMINI_API_KEY", + "GOOGLE_API_KEY", + "GOOGLE_CLOUD_LOCATION", +] + +@pytest.fixture(autouse=True) +def clear_env_vars(monkeypatch): + for var in ENV_VARS: + monkeypatch.delenv(var, raising=False) + +def test_interactions_gemini_url(monkeypatch): + monkeypatch.setenv('GOOGLE_API_KEY', 'test-api-key') + client = Client() + + + with mock.patch.object(HTTPClient, "send") as mock_send: + mock_send.return_value = Response(200, request=Request('POST', '')) + client.interactions.create( + model='gemini-1.5-flash', + input='Hello', + ) + mock_send.assert_called_once() + request = mock_send.call_args[0][0] + assert str(request.url).endswith('/v1beta/interactions') + assert request.headers['x-goog-api-key'] == 'test-api-key' + + +def test_interactions_gemini_no_vertex_auth(monkeypatch): + monkeypatch.setenv('GOOGLE_API_KEY', 'test-api-key') + client = Client() + + with ( + mock.patch.object(BaseApiClient, "_access_token") as mock_access_token, + mock.patch.object(HTTPClient, "send") as mock_send, + ): + mock_send.return_value = Response(200, request=Request('POST', '')) + client.interactions.create( + model='gemini-1.5-flash', + input='Hello', + ) + mock_access_token.assert_not_called() + +def test_interactions_gemini_retry(monkeypatch): + monkeypatch.setenv('GOOGLE_API_KEY', 'test-api-key') + client = Client() + client._api_client.max_retries = 2 + + with mock.patch.object(HTTPClient, "send") as mock_send: + mock_send.side_effect = [ + Response(500, request=Request('POST', ''), headers={"retry-after-ms": "1"}), + Response(500, request=Request('POST', ''), headers={"retry-after-ms": "1"}), + Response(200, request=Request('POST', '')), + ] + client.interactions.create(model='gemini-1.5-flash', input='Hello') + assert mock_send.call_count == 3 + +def test_interactions_gemini_extra_headers(monkeypatch): + monkeypatch.setenv('GOOGLE_API_KEY', 'test-api-key') + client = Client() + + with mock.patch.object(HTTPClient, "send") as mock_send: + mock_send.return_value = Response(200, request=Request('POST', '')) + client.interactions.create( + model='gemini-1.5-flash', + input='Hello', + extra_headers={'X-Custom-Header': 'TestValue'} + ) + mock_send.assert_called_once() + request = mock_send.call_args[0][0] + assert request.headers['x-custom-header'] == 'TestValue' + assert request.headers['x-goog-api-key'] == 'test-api-key' + + +def test_interactions_vertex_auth_header(): + from ..._api_client import BaseApiClient + from ..._interactions._base_client import SyncAPIClient + from httpx import Client as HTTPClient + + creds = mock.Mock() + creds.quota_project_id = "test-quota-project" + client = Client(vertexai=True, project='test-project', location='us-central1', credentials=creds) + + with ( + mock.patch.object( + BaseApiClient, "_access_token", return_value='fake-vertex-token' + ) as mock_access_token, + mock.patch.object( + HTTPClient, "send", + return_value=mock.Mock(), + ) as mock_send, + ): + + response = client.interactions.create( + model='gemini-2.5-flash', + input='What is the largest planet in our solar system?', + ) + + mock_send.assert_called_once() + mock_access_token.assert_called_once() + args, kwargs = mock_send.call_args + headers = args[0].headers + assert any( + key == "authorization" and value == 'Bearer fake-vertex-token' + for key, value in headers.items()) + assert any( + key == "x-goog-user-project" and value == 'test-quota-project' + for key, value in headers.items()) + +def test_interactions_vertex_key_no_auth_header(): + from ..._api_client import BaseApiClient + from httpx import Client as HTTPClient + + creds = mock.Mock() + client = Client(vertexai=True, api_key='test-api-key') + + with ( + mock.patch.object( + BaseApiClient, "_access_token", return_value='fake-vertex-token' + ) as mock_access_token, + mock.patch.object( + HTTPClient, "send", + return_value=mock.Mock(), + ) as mock_send, + ): + + response = client.interactions.create( + model='gemini-2.5-flash', + input='What is the largest planet in our solar system?', + ) + + mock_send.assert_called_once() + mock_access_token.assert_not_called() + args, kwargs = mock_send.call_args + headers = args[0].headers + assert any( + key == "x-goog-api-key" and value == 'test-api-key' + for key, value in headers.items()) + +def test_interactions_vertex_url(): + creds = mock.Mock() + creds.quota_project_id = "test-quota-project" + client = Client(vertexai=True, project='test-project', location='us-central1', credentials=creds) + + with mock.patch("httpx.Client.send") as mock_send: + mock_send.return_value = Response(200, request=Request('POST', '')) + client.interactions.create( + model='gemini-1.5-flash', + input='Hello', + ) + mock_send.assert_called_once() + request = mock_send.call_args[0][0] + assert str(request.url) == 'https://us-central1-aiplatform.googleapis.com/v1beta1/projects/test-project/locations/us-central1/interactions' + +def test_interactions_vertex_auth_refresh_on_retry(): + from ..._api_client import BaseApiClient + from httpx import Client as HTTPClient + + creds = mock.Mock() + creds.quota_project_id = "test-quota-project" + client = Client(vertexai=True, project='test-project', location='us-central1', credentials=creds) + client._api_client.max_retries = 2 + + token_values = ['token1', 'token2', 'token3'] + token_iter = iter(token_values) + + def get_token(): + return next(token_iter) + + with ( + mock.patch.object(BaseApiClient, "_access_token", side_effect=get_token) as mock_access_token, + mock.patch.object(HTTPClient, "send") as mock_send, + ): + mock_send.side_effect = [ + Response(500, request=Request('POST', ''), headers={"retry-after-ms": "1"}), + Response(500, request=Request('POST', ''), headers={"retry-after-ms": "1"}), + Response(200, request=Request('POST', '')), + ] + + client.interactions.create(model='gemini-1.5-flash', input='Hello') + + assert mock_access_token.call_count == 3 + assert mock_send.call_count == 3 + # Check headers of each call + for i in range(3): + headers = mock_send.call_args_list[i][0][0].headers + assert headers['authorization'] == f'Bearer {token_values[i]}' + + +def test_interactions_vertex_extra_headers_override(): + from ..._api_client import BaseApiClient + from httpx import Client as HTTPClient + + creds = mock.Mock() + creds.quota_project_id = "test-quota-project" + client = Client(vertexai=True, project='test-project', location='us-central1', credentials=creds) + + with ( + mock.patch.object(BaseApiClient, "_access_token", return_value='default-token') as mock_access_token, + mock.patch.object(HTTPClient, "send") as mock_send, + ): + mock_send.return_value = Response(200, request=Request('POST', '')) + + # Override Authorization + client.interactions.create( + model='gemini-1.5-flash', + input='Hello', + extra_headers={'Authorization': 'Bearer manual-token'} + ) + mock_send.assert_called_once() + headers = mock_send.call_args[0][0].headers + assert headers['authorization'] == 'Bearer manual-token' + mock_access_token.assert_not_called() # Should not fetch default token + + mock_send.reset_mock() + mock_access_token.reset_mock() + + # Provide API Key + client.interactions.create( + model='gemini-1.5-flash', + input='Hello', + extra_headers={'x-goog-api-key': 'manual-key'} + ) + mock_send.assert_called_once() + headers = mock_send.call_args[0][0].headers + assert headers['x-goog-api-key'] == 'manual-key' + assert 'authorization' not in headers + mock_access_token.assert_not_called() + +@pytest.mark.asyncio +async def test_async_interactions_gemini_url(monkeypatch): + monkeypatch.setenv('GOOGLE_API_KEY', 'test-api-key') + client = Client() + + with mock.patch.object(AsyncHttpxClient, "send") as mock_send: + mock_send.return_value = Response(200, request=Request('POST', '')) + await client.aio.interactions.create( + model='gemini-1.5-flash', + input='Hello', + ) + mock_send.assert_called_once() + request = mock_send.call_args[0][0] + assert str(request.url).endswith('/v1beta/interactions') + assert request.headers['x-goog-api-key'] == 'test-api-key' + +@pytest.mark.asyncio +async def test_async_interactions_gemini_no_vertex_auth(monkeypatch): + monkeypatch.setenv('GOOGLE_API_KEY', 'test-api-key') + client = Client() + + with ( + mock.patch.object(BaseApiClient, "_async_access_token") as mock_access_token, + mock.patch.object(AsyncHttpxClient, "send") as mock_send, + ): + mock_send.return_value = Response(200, request=Request('POST', '')) + await client.aio.interactions.create( + model='gemini-1.5-flash', + input='Hello', + ) + mock_access_token.assert_not_called() + +@pytest.mark.asyncio +async def test_async_interactions_gemini_retry(monkeypatch): + monkeypatch.setenv('GOOGLE_API_KEY', 'test-api-key') + client = Client() + client.aio._api_client.max_retries = 2 + + with mock.patch.object(AsyncHttpxClient, "send") as mock_send: + mock_send.side_effect = [ + Response(500, request=Request('POST', ''), headers={"retry-after-ms": "1"}), + Response(500, request=Request('POST', ''), headers={"retry-after-ms": "1"}), + Response(200, request=Request('POST', '')), + ] + await client.aio.interactions.create(model='gemini-1.5-flash', input='Hello') + assert mock_send.call_count == 3 + +@pytest.mark.asyncio +async def test_async_interactions_gemini_extra_headers(monkeypatch): + monkeypatch.setenv('GOOGLE_API_KEY', 'test-api-key') + client = Client() + + with mock.patch.object(AsyncHttpxClient, "send") as mock_send: + mock_send.return_value = Response(200, request=Request('POST', '')) + await client.aio.interactions.create( + model='gemini-1.5-flash', + input='Hello', + extra_headers={'X-Custom-Header': 'TestValue'} + ) + mock_send.assert_called_once() + request = mock_send.call_args[0][0] + assert request.headers['x-custom-header'] == 'TestValue' + assert request.headers['x-goog-api-key'] == 'test-api-key' + +@pytest.mark.asyncio +async def test_async_interactions_vertex_auth_header(): + from ..._api_client import BaseApiClient + from ..._interactions._base_client import SyncAPIClient + from ..._api_client import AsyncHttpxClient + + creds = mock.Mock() + creds.quota_project_id = "test-quota-project" + client = Client(vertexai=True, project='test-project', location='us-central1', credentials=creds) + + with ( + mock.patch.object( + BaseApiClient, "_async_access_token", return_value='fake-vertex-token' + ) as mock_access_token, + mock.patch.object( + AsyncHttpxClient, "send", + return_value=mock.Mock(), + ) as mock_send, + ): + + response = await client.aio.interactions.create( + model='gemini-2.5-flash', + input='What is the largest planet in our solar system?', + ) + + mock_send.assert_called_once() + mock_access_token.assert_called_once() + args, kwargs = mock_send.call_args + headers = args[0].headers + assert any( + key == "authorization" and value == 'Bearer fake-vertex-token' + for key, value in headers.items()) + assert any( + key == "x-goog-user-project" and value == 'test-quota-project' + for key, value in headers.items()) + +@pytest.mark.asyncio +async def test_async_interactions_vertex_key_no_auth_header(): + from ..._api_client import BaseApiClient + client = Client(vertexai=True, api_key='test-api-key') + + with ( + mock.patch.object( + BaseApiClient, "_async_access_token", return_value='fake-vertex-token' + ) as mock_access_token, + mock.patch.object( + AsyncHttpxClient, "send", + return_value=mock.Mock(), + ) as mock_send, + ): + + response = await client.aio.interactions.create( + model='gemini-2.5-flash', + input='What is the largest planet in our solar system?', + ) + + mock_send.assert_called_once() + mock_access_token.assert_not_called() + args, kwargs = mock_send.call_args + headers = args[0].headers + assert any( + key == "x-goog-api-key" and value == 'test-api-key' + for key, value in headers.items()) + +@pytest.mark.asyncio +async def test_async_interactions_vertex_url(): + from ..._api_client import AsyncHttpxClient + creds = mock.Mock() + creds.quota_project_id = "test-quota-project" + client = Client(vertexai=True, project='test-project', location='us-central1', credentials=creds) + + with mock.patch.object(AsyncHttpxClient, "send") as mock_send: + mock_send.return_value = Response(200, request=Request('POST', '')) + await client.aio.interactions.create( + model='gemini-1.5-flash', + input='Hello', + ) + mock_send.assert_called_once() + request = mock_send.call_args[0][0] + assert str(request.url) == 'https://us-central1-aiplatform.googleapis.com/v1beta1/projects/test-project/locations/us-central1/interactions' + +@pytest.mark.asyncio +async def test_async_interactions_vertex_auth_refresh_on_retry(): + from ..._api_client import BaseApiClient + from ..._api_client import AsyncHttpxClient + + creds = mock.Mock() + creds.quota_project_id = "test-quota-project" + client = Client(vertexai=True, project='test-project', location='us-central1', credentials=creds) + client.aio._api_client.max_retries = 2 + + token_values = ['token1', 'token2', 'token3'] + token_iter = iter(token_values) + + async def get_token(): + return next(token_iter) + + with ( + mock.patch.object(BaseApiClient, "_async_access_token", side_effect=get_token) as mock_access_token, + mock.patch.object(AsyncHttpxClient, "send") as mock_send, + ): + mock_send.side_effect = [ + Response(500, request=Request('POST', ''), headers={"retry-after-ms": "1"}), + Response(500, request=Request('POST', ''), headers={"retry-after-ms": "1"}), + Response(200, request=Request('POST', '')), + ] + + await client.aio.interactions.create(model='gemini-1.5-flash', input='Hello') + + assert mock_access_token.call_count == 3 + assert mock_send.call_count == 3 + for i in range(3): + headers = mock_send.call_args_list[i][0][0].headers + assert headers['authorization'] == f'Bearer {token_values[i]}' + +@pytest.mark.asyncio +async def test_async_interactions_vertex_extra_headers_override(): + from ..._api_client import BaseApiClient + from ..._api_client import AsyncHttpxClient + + creds = mock.Mock() + creds.quota_project_id = "test-quota-project" + client = Client(vertexai=True, project='test-project', location='us-central1', credentials=creds) + + with ( + mock.patch.object(BaseApiClient, "_async_access_token", return_value='default-token') as mock_access_token, + mock.patch.object(AsyncHttpxClient, "send") as mock_send, + ): + mock_send.return_value = Response(200, request=Request('POST', '')) + + # Override Authorization + await client.aio.interactions.create( + model='gemini-1.5-flash', + input='Hello', + extra_headers={'Authorization': 'Bearer manual-token'} + ) + mock_send.assert_called_once() + headers = mock_send.call_args[0][0].headers + assert headers['authorization'] == 'Bearer manual-token' + mock_access_token.assert_not_called() + + mock_send.reset_mock() + mock_access_token.reset_mock() + + # Provide API Key + await client.aio.interactions.create( + model='gemini-1.5-flash', + input='Hello', + extra_headers={'x-goog-api-key': 'manual-key'} + ) + mock_send.assert_called_once() + headers = mock_send.call_args[0][0].headers + assert headers['x-goog-api-key'] == 'manual-key' + assert 'authorization' not in headers + mock_access_token.assert_not_called() diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/interactions/test_integration.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/interactions/test_integration.py new file mode 100644 index 0000000000000000000000000000000000000000..13b76f5c0681d4326d17f70c55fef88055660fab --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/interactions/test_integration.py @@ -0,0 +1,84 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. + +from unittest import mock +import pytest +from ... import client as client_lib + +pytest_plugins = ("pytest_asyncio",) + + +def test_client_future_warning(): + with mock.patch.object( + client_lib, "_interactions_experimental_warned", new=False + ): + client = client_lib.Client( + api_key="placeholder", + http_options={ + "api_version": "v1alpha", + } + ) + with pytest.warns( + UserWarning, match="Interactions.*experimental" + ): + _ = client.interactions + + +def test_client_timeout(): + with mock.patch.object( + client_lib, "GeminiNextGenAPIClient", spec_set=True + ) as mock_nextgen_client: + + client = client_lib.Client( + api_key="placeholder", + http_options={"api_version": "v1alpha", "timeout": 5000}, + ) + + _ = client.interactions + + mock_nextgen_client.assert_called_once_with( + base_url=mock.ANY, + api_key="placeholder", + api_version="v1alpha", + default_headers=mock.ANY, + http_client=mock.ANY, + timeout=5.0, + max_retries=mock.ANY, + client_adapter=mock.ANY, + ) + + +@pytest.mark.asyncio +async def test_async_client_timeout(): + with mock.patch.object( + client_lib, "AsyncGeminiNextGenAPIClient", spec_set=True + ) as mock_nextgen_client: + + client = client_lib.Client( + api_key="placeholder", + http_options={"api_version": "v1alpha", "timeout": 5000}, + ) + + _ = client.aio.interactions + + mock_nextgen_client.assert_called_once_with( + base_url=mock.ANY, + api_key="placeholder", + api_version="v1alpha", + default_headers=mock.ANY, + http_client=mock.ANY, + timeout=5.0, + max_retries=mock.ANY, + client_adapter=mock.ANY, + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/interactions/test_paths.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/interactions/test_paths.py new file mode 100644 index 0000000000000000000000000000000000000000..1e8f77000b3be683d675c2350222c960e96181cf --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/interactions/test_paths.py @@ -0,0 +1,105 @@ + +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for Interactions API URL paths.""" + +from unittest import mock +import pytest +from httpx import Request, Response +from ..._api_client import AsyncHttpxClient +from httpx import Client as HTTPClient +from .. import pytest_helper +import google.auth + +@mock.patch.object(google.auth, "default", autospec=True) +def test_interactions_paths(mock_auth_default, client): + interaction_id = "test-interaction-id" + + mock_creds = mock.Mock() + mock_creds.token = "test-token" + mock_creds.expired = False + mock_creds.quota_project_id = "test-quota-project" + mock_auth_default.return_value = (mock_creds, "test-project") + + if client._api_client.vertexai: + expected_base_url = f'https://{client._api_client.location}-aiplatform.googleapis.com/v1beta1/projects/{client._api_client.project}/locations/{client._api_client.location}' + else: + expected_base_url = "https://generativelanguage.googleapis.com/v1beta" + + with mock.patch.object(HTTPClient, "send") as mock_send: + mock_send.return_value = Response(200, request=Request('GET', '')) + client.interactions.get(id=interaction_id) + mock_send.assert_called_once() + request = mock_send.call_args[0][0] + assert str(request.url) == f'{expected_base_url}/interactions/{interaction_id}' + + mock_send.reset_mock() + mock_send.return_value = Response(200, request=Request('POST', '')) + client.interactions.cancel(id=interaction_id) + mock_send.assert_called_once() + request = mock_send.call_args[0][0] + assert str(request.url) == f'{expected_base_url}/interactions/{interaction_id}/cancel' + + mock_send.reset_mock() + mock_send.return_value = Response(200, request=Request('DELETE', '')) + client.interactions.delete(id=interaction_id) + mock_send.assert_called_once() + request = mock_send.call_args[0][0] + assert str(request.url) == f'{expected_base_url}/interactions/{interaction_id}' + +@pytest.mark.asyncio +@mock.patch.object(google.auth, "default", autospec=True) +async def test_async_interactions_paths(mock_auth_default, client): + interaction_id = "test-interaction-id" + + mock_creds = mock.Mock() + mock_creds.token = "test-token" + mock_creds.expired = False + mock_creds.quota_project_id = "test-quota-project" + mock_auth_default.return_value = (mock_creds, "test-project") + + if client._api_client.vertexai: + expected_base_url = f'https://{client._api_client.location}-aiplatform.googleapis.com/v1beta1/projects/{client._api_client.project}/locations/{client._api_client.location}' + else: + expected_base_url = "https://generativelanguage.googleapis.com/v1beta" + + with mock.patch.object(AsyncHttpxClient, "send") as mock_send: + mock_send.return_value = Response(200, request=Request('GET', '')) + await client.aio.interactions.get(id=interaction_id) + mock_send.assert_called_once() + request = mock_send.call_args[0][0] + assert str(request.url) == f'{expected_base_url}/interactions/{interaction_id}' + + mock_send.reset_mock() + mock_send.return_value = Response(200, request=Request('POST', '')) + await client.aio.interactions.cancel(id=interaction_id) + mock_send.assert_called_once() + request = mock_send.call_args[0][0] + assert str(request.url) == f'{expected_base_url}/interactions/{interaction_id}/cancel' + + mock_send.reset_mock() + mock_send.return_value = Response(200, request=Request('DELETE', '')) + await client.aio.interactions.delete(id=interaction_id) + mock_send.assert_called_once() + request = mock_send.call_args[0][0] + assert str(request.url) == f'{expected_base_url}/interactions/{interaction_id}' + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_table=[], +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/live/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/live/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..66e21cef88ff3772d37f5b8d6eac646a5963c406 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/live/__init__.py @@ -0,0 +1,16 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/live/test_live.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/live/test_live.py new file mode 100644 index 0000000000000000000000000000000000000000..513a90a3fae6721512e5c56008b217278c4c41a3 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/live/test_live.py @@ -0,0 +1,2259 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for live.py.""" + +import contextlib +import json +import os +import ssl +import typing +from typing import Any, AsyncIterator +from unittest import mock +from unittest.mock import AsyncMock +from unittest.mock import Mock +from unittest.mock import patch +import warnings + +import certifi +from google.oauth2.credentials import Credentials +import pytest +from websockets import client + +from .. import pytest_helper +from ... import _api_client as api_client +from ... import _common +from ... import Client +from ... import client as gl_client +from ... import live +from ... import types +try: + import aiohttp + AIOHTTP_NOT_INSTALLED = False +except ImportError: + AIOHTTP_NOT_INSTALLED = True + aiohttp = mock.MagicMock() + + +if typing.TYPE_CHECKING: + from mcp import types as mcp_types + from mcp import ClientSession as McpClientSession +else: + mcp_types: typing.Type = Any + McpClientSession: typing.Type = Any + try: + from mcp import types as mcp_types + from mcp import ClientSession as McpClientSession + except ImportError: + mcp_types = None + McpClientSession = None + + +requires_aiohttp = pytest.mark.skipif( + AIOHTTP_NOT_INSTALLED, reason="aiohttp is not installed, skipping test." +) + +function_declarations = [{ + 'name': 'get_current_weather', + 'description': 'Get the current weather in a city', + 'parameters': { + 'type': 'OBJECT', + 'properties': { + 'location': { + 'type': 'STRING', + 'description': 'The location to get the weather for', + }, + 'unit': { + 'type': 'STRING', + 'enum': ['C', 'F'], + }, + }, + }, +}] + + +def get_current_weather(location: str, unit: str): + """Get the current weather in a city.""" + return 15 if unit == 'C' else 59 + + +def mock_api_client(vertexai=False, credentials=None, http_options=None): + api_client = mock.MagicMock(spec=gl_client.BaseApiClient) + if not vertexai: + api_client.api_key = 'TEST_API_KEY' + api_client.location = None + api_client.project = None + api_client.custom_base_url = None + else: + api_client.api_key = None + if http_options: + http_options = ( + types.HttpOptions(**http_options) + if isinstance(http_options, dict) + else http_options + ) + api_client.custom_base_url = http_options.base_url + api_client.location = None + api_client.project = None + else: + api_client.location = 'us-central1' + api_client.project = 'test_project' + api_client.custom_base_url = None + + api_client._host = lambda: 'test_host' + api_client._credentials = credentials + api_client._http_options = types.HttpOptions.model_validate( + {'headers': {}} + ) # Ensure headers exist + api_client.vertexai = vertexai + api_client._api_client = api_client + ctx = ssl.create_default_context( + cafile=os.environ.get("SSL_CERT_FILE", certifi.where()), + capath=os.environ.get("SSL_CERT_DIR"), + ) + api_client._websocket_ssl_ctx = {'ssl': ctx} + return api_client + + +@pytest.fixture +def mock_websocket(): + websocket = AsyncMock(spec=client.ClientConnection) + websocket.send = AsyncMock() + websocket.recv = AsyncMock( + return_value='{"serverContent": {"turnComplete": true}}' + ) # Default response + websocket.close = AsyncMock() + return websocket + + +async def get_connect_message(api_client, model, config=None): + if config is None: + config = {} + mock_ws = AsyncMock() + mock_ws.send = AsyncMock() + mock_ws.recv = AsyncMock( + return_value=( + b'{\n "setupComplete": {"sessionId": "test_session_id"}\n}\n' + ) + ) + + mock_google_auth_default = Mock(return_value=(None, None)) + mock_creds = Mock(token='test_token') + mock_google_auth_default.return_value = (mock_creds, None) + + @contextlib.asynccontextmanager + async def mock_connect(uri, additional_headers=None, **kwargs): + yield mock_ws + + @patch('google.auth.default', new=mock_google_auth_default) + @patch.object(live, 'ws_connect', new=mock_connect) + async def _test_connect(): + live_module = live.AsyncLive(api_client) + async with live_module.connect( + model=model, + config=config, + ): + pass + + mock_ws.send.assert_called_once() + return json.loads(mock_ws.send.call_args[0][0]) + + return await _test_connect() + + +async def _async_iterator_to_list(async_iter): + return [value async for value in async_iter] + + +def test_mldev_from_env(monkeypatch): + api_key = 'google_api_key' + monkeypatch.setenv('GOOGLE_API_KEY', api_key) + + client = Client() + + assert not client.aio.live._api_client.vertexai + assert client.aio.live._api_client.api_key == api_key + assert isinstance(client.aio.live._api_client, api_client.BaseApiClient) + assert client.aio.live._api_client._http_options.headers['x-goog-api-key'] == api_key + + +@requires_aiohttp +def test_vertex_from_env(monkeypatch): + project_id = 'fake_project_id' + location = 'fake-location' + monkeypatch.setenv('GOOGLE_GENAI_USE_VERTEXAI', 'true') + monkeypatch.setenv('GOOGLE_CLOUD_PROJECT', project_id) + monkeypatch.setenv('GOOGLE_CLOUD_LOCATION', location) + + client = Client() + + assert client.aio.live._api_client.custom_base_url is None + assert client.aio.live._api_client.vertexai + assert client.aio.live._api_client.project == project_id + assert isinstance(client.aio.live._api_client, api_client.BaseApiClient) + assert 'x-goog-api-key' not in client.aio.live._api_client._http_options.headers + + +def test_vertex_api_key_from_env(monkeypatch): + api_key = 'google_api_key' + monkeypatch.setenv('GOOGLE_GENAI_USE_VERTEXAI', 'true') + monkeypatch.setenv('GOOGLE_API_KEY', api_key) + + # Due to proj/location taking precedence, need to clear proj/location env + # variables. Tests in client/test_client_initialization.py provide + # comprehensive coverage for proj/location and api key precedence. + monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", "") + monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "") + + client = Client() + + assert client.aio.live._api_client.vertexai + assert client.aio.live._api_client.api_key == api_key + assert isinstance(client.aio.live._api_client, api_client.BaseApiClient) + assert client.aio.live._api_client._http_options.headers['x-goog-api-key'] == api_key + + +def test_websocket_base_url(): + base_url = 'https://test.com' + api_client = gl_client.BaseApiClient( + api_key='google_api_key', + http_options={'base_url': base_url}, + ) + assert api_client._websocket_base_url() == 'wss://test.com' + + +def test_websocket_base_url_no_auth_with_custom_base_url(): + base_url = 'https://test-api-gateway-proxy.com' + api_client = gl_client.BaseApiClient( + vertexai=True, + http_options={ + 'base_url': base_url, + 'headers': {'Authorization': 'Bearer test_token'}, + }, + ) + # Note that our test environment does have project/location set. So we + # need to explicitly set them to None here. + api_client.project = None + api_client.location = None + + # Fully pass the custom base url if no API key or project/location. + assert api_client._websocket_base_url() == base_url + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_async_session_send_text(mock_websocket, vertexai): + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + await session.send(input='test') + mock_websocket.send.assert_called_once() + sent_data = json.loads(mock_websocket.send.call_args[0][0]) + assert 'client_content' in sent_data + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_async_session_send_content_dict( + mock_websocket, vertexai +): + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + client_content = { + 'content': [{'parts': [{'text': 'test'}]}], + 'turn_complete': True, + } + await session.send(input=client_content) + mock_websocket.send.assert_called_once() + sent_data = json.loads(mock_websocket.send.call_args[0][0]) + assert 'client_content' in sent_data + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_async_session_send_content( + mock_websocket, vertexai +): + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + client_content = types.LiveClientContent( + turns=[types.Content(parts=[types.Part(text='test')])], turn_complete=True + ) + await session.send(input=client_content) + mock_websocket.send.assert_called_once() + sent_data = json.loads(mock_websocket.send.call_args[0][0]) + assert 'client_content' in sent_data + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_async_session_send_bytes( + mock_websocket, vertexai +): + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + realtime_input = {'data': b'000000', 'mime_type': 'audio/pcm'} + + await session.send(input=realtime_input) + mock_websocket.send.assert_called_once() + sent_data = json.loads(mock_websocket.send.call_args[0][0]) + assert 'realtime_input' in sent_data + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_async_session_send_blob( + mock_websocket, vertexai +): + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + realtime_input = types.Blob(data=b'000000', mime_type='audio/pcm') + + await session.send(input=realtime_input) + mock_websocket.send.assert_called_once() + sent_data = json.loads(mock_websocket.send.call_args[0][0]) + assert 'realtime_input' in sent_data + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_async_session_send_realtime_input( + mock_websocket, vertexai +): + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + realtime_input = types.LiveClientRealtimeInput( + media_chunks=[types.Blob(data='MDAwMDAw', mime_type='audio/pcm')] + ) + await session.send(input=realtime_input) + mock_websocket.send.assert_called_once() + sent_data = json.loads(mock_websocket.send.call_args[0][0]) + assert 'realtime_input' in sent_data + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_async_session_send_tool_response( + mock_websocket, vertexai +): + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + + if vertexai: + tool_response = types.LiveClientToolResponse( + function_responses=[ + types.FunctionResponse( + name='get_current_weather', + response={'temperature': 14.5, 'unit': 'C'}, + ) + ] + ) + else: + tool_response = types.LiveClientToolResponse( + function_responses=[ + types.FunctionResponse( + name='get_current_weather', + response={'temperature': 14.5, 'unit': 'C'}, + id='some-id', + ) + ] + ) + await session.send(input=tool_response) + mock_websocket.send.assert_called_once() + sent_data = json.loads(mock_websocket.send.call_args[0][0]) + assert 'tool_response' in sent_data + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_async_session_send_input_none( + mock_websocket, vertexai +): + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + await session.send(input=None) + mock_websocket.send.assert_called_once() + sent_data = json.loads(mock_websocket.send.call_args[0][0]) + assert 'client_content' in sent_data + assert sent_data['client_content']['turn_complete'] + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_async_session_send_error( + mock_websocket, vertexai +): + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + with pytest.raises(ValueError): + await session.send(input=[{'invalid_key': 'invalid_value'}]) + + with pytest.raises(ValueError): + await session.send(input={'invalid_key': 'invalid_value'}) + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_async_session_receive( mock_websocket, vertexai): + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + responses = session.receive() + responses = await _async_iterator_to_list(responses) + assert isinstance(responses[0], types.LiveServerMessage) + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_async_session_receive_error( + mock_websocket, vertexai +): + mock_websocket.recv = AsyncMock(return_value='invalid json') + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + with pytest.raises(ValueError): + await session.receive().__anext__() + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_async_session_receive_text( + mock_websocket, vertexai +): + mock_websocket.recv = AsyncMock( + side_effect=[ + '{"serverContent": {"modelTurn": {"parts":[{"text": "test"}]}}}', + '{"serverContent": {"turnComplete": true}}', + ] + ) + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + messages = session.receive() + messages = await _async_iterator_to_list(messages) + assert isinstance(messages[0], types.LiveServerMessage) + assert messages[0].server_content.model_turn.parts[0].text == 'test' + assert messages[1].server_content.turn_complete == True + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_async_session_receive_audio( + mock_websocket, vertexai +): + mock_websocket.recv = AsyncMock( + side_effect=[ + ( + '{"serverContent": {"modelTurn": {"parts":[{"inlineData":' + ' {"data": "MDAwMDAw", "mimeType": "audio/pcm" }}]}}}' + ), + '{"serverContent": {"turnComplete": true}}', + ] + ) + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + messages = session.receive() + messages = await _async_iterator_to_list(messages) + assert isinstance(messages[0], types.LiveServerMessage) + assert ( + messages[0].server_content.model_turn.parts[0].inline_data.mime_type + == 'audio/pcm' + ) + assert ( + messages[0].server_content.model_turn.parts[0].inline_data.data + == b'000000' + ) + + with pytest.raises(RuntimeError): + await _async_iterator_to_list(session.receive()) + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_async_session_receive_tool_call( + mock_websocket, vertexai +): + mock_websocket.recv = AsyncMock( + side_effect=[ + ( + '{"toolCall": {"functionCalls": [{"name":' + ' "get_current_weather", "args": {"location": "San Francisco",' + ' "unit": "C"}}]}}' + ), + '{"serverContent": {"turnComplete": true}}', + ] + ) + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + messages = session.receive() + messages = await _async_iterator_to_list(messages) + assert isinstance(messages[0], types.LiveServerMessage) + assert messages[0].tool_call.function_calls[0].name == 'get_current_weather' + assert ( + messages[0].tool_call.function_calls[0].args['location'] + == 'San Francisco' + ) + assert messages[0].tool_call.function_calls[0].args['unit'] == 'C' + + with pytest.raises(RuntimeError): + await _async_iterator_to_list(session.receive()) + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_async_session_receive_transcription( + mock_websocket, vertexai +): + mock_websocket.recv = AsyncMock( + side_effect=[ + '{"serverContent": {"inputTranscription": {"text": "test_input", "finished": true}}}', + '{"serverContent": {"outputTranscription": {"text": "test_output", "finished": false}}}', + '{"serverContent": {"turnComplete": true}}', + ] + ) + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + messages = session.receive() + messages = await _async_iterator_to_list(messages) + assert isinstance(messages[0], types.LiveServerMessage) + assert messages[0].server_content.input_transcription.text == 'test_input' + assert messages[0].server_content.input_transcription.finished == True + + assert isinstance(messages[1], types.LiveServerMessage) + assert messages[1].server_content.output_transcription.text == 'test_output' + assert messages[1].server_content.output_transcription.finished == False + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_async_go_away( + mock_websocket, vertexai +): + mock_websocket.recv = AsyncMock( + side_effect=[ + '{"goAway": {"timeLeft": "10s"}}', + '{"serverContent": {"turnComplete": true}}', + ] + ) + expected_result = types.LiveServerMessage( + go_away=types.LiveServerGoAway(time_left='10s'), + ) + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + messages = session.receive() + messages = await _async_iterator_to_list(messages) + message = messages[0] + + assert isinstance(message, types.LiveServerMessage) + assert message == expected_result + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_async_session_resumption_update( + mock_websocket, vertexai +): + mock_websocket.recv = AsyncMock( + side_effect=[ + """{ + "sessionResumptionUpdate": { + "newHandle": "test_handle", + "resumable": "true", + "lastConsumedClientMessageIndex": "123456789" + } + }""", + '{"serverContent": {"turnComplete": true}}', + ] + ) + + expected_result = types.LiveServerMessage( + session_resumption_update=types.LiveServerSessionResumptionUpdate( + new_handle='test_handle', + resumable=True, + last_consumed_client_message_index=123456789 + ), + ) + + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + messages = session.receive() + messages = await _async_iterator_to_list(messages) + message = messages[0] + + assert isinstance(message, types.LiveServerMessage) + assert message == expected_result + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_async_session_start_stream( + mock_websocket, vertexai +): + + session = live.AsyncSession( + mock_api_client(vertexai=vertexai), mock_websocket + ) + + async def mock_stream(): + yield b'data1' + yield b'data2' + + async for message in session.start_stream( + stream=mock_stream(), mime_type='audio/pcm' + ): + assert isinstance(message, types.LiveServerMessage) + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_async_session_receive_vad_signal(mock_websocket, vertexai): + # Simulate the server sending a VAD signal message + mock_websocket.recv = mock.AsyncMock( + side_effect=[ + '{"voiceActivityDetectionSignal": {"vadSignalType": "VAD_SIGNAL_TYPE_SOS"}}', + '{"serverContent": {"turnComplete": true}}', # To close the receiver loop + ] + ) + + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + + messages = await _async_iterator_to_list(session.receive()) + + # Check if the first message contains the VAD signal + assert len(messages) > 0 + vad_message = messages[0] + assert isinstance(vad_message, types.LiveServerMessage) + assert vad_message.voice_activity_detection_signal is not None + assert ( + vad_message.voice_activity_detection_signal.vad_signal_type + == types.VadSignalType.VAD_SIGNAL_TYPE_SOS + ) + + # Check that the session can close cleanly + assert messages[-1].server_content.turn_complete is True + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_async_session_close( mock_websocket, vertexai): + session = live.AsyncSession( + mock_api_client(vertexai=vertexai), mock_websocket + ) + await session.close() + mock_websocket.close.assert_called_once() + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_bidi_setup_to_api_no_config(vertexai): + with warnings.catch_warnings(): + # Make sure there are no warnings cause by default values. + warnings.simplefilter('error') + result = await get_connect_message( + mock_api_client(vertexai=vertexai), + model='test_model' + ) + expected_result = {'setup': {}} + if vertexai: + expected_result['setup']['model'] = 'projects/test_project/locations/us-central1/publishers/google/models/test_model' + expected_result['setup']['generationConfig'] = {} + expected_result['setup']['generationConfig']['responseModalities'] = ["AUDIO"] + else: + expected_result['setup']['model'] = 'models/test_model' + assert result == expected_result + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_bidi_setup_to_api_speech_config(vertexai): + + expected_result = { + 'setup': { + 'model': 'models/test_model', + 'generationConfig': { + 'speechConfig': { + 'voice_config': { + 'prebuilt_voice_config': {'voice_name': 'en-default'} + }, + 'language_code': 'en-US', + }, + 'enableAffectiveDialog': True, + 'temperature': 0.7, + 'topP': 0.8, + 'topK': 9.0, + 'maxOutputTokens': 10, + 'mediaResolution': 'MEDIA_RESOLUTION_MEDIUM', + 'seed': 13, + }, + 'proactivity': {'proactive_audio': True}, + 'systemInstruction': { + 'parts': [ + { + 'text': 'test instruction', + }, + ], + 'role': 'user', + }, + } + } + if vertexai: + expected_result['setup']['model'] = ( + 'projects/test_project/locations/us-central1/' + 'publishers/google/models/test_model' + ) + expected_result['setup']['generationConfig']['responseModalities'] = [ + 'AUDIO' + ] + expected_result['setup']['generationConfig']['speechConfig'] = { + 'voiceConfig': { + 'prebuilt_voice_config': {'voice_name': 'en-default'} + }, + 'languageCode': 'en-US', + } + else: + expected_result['setup']['model'] = 'models/test_model' + + # Config is a dict + config_dict = { + 'speech_config': { + 'voice_config': { + 'prebuilt_voice_config': {'voice_name': 'en-default'} + }, + 'language_code': 'en-US', + }, + 'enable_affective_dialog': True, + 'proactivity': {'proactive_audio': True}, + 'temperature': 0.7, + 'top_p': 0.8, + 'top_k': 9, + 'max_output_tokens': 10, + 'seed': 13, + 'system_instruction': 'test instruction', + 'media_resolution': 'MEDIA_RESOLUTION_MEDIUM', + } + result = await get_connect_message( + mock_api_client(vertexai=vertexai), model='test_model', config=config_dict + ) + assert types.LiveClientMessage._from_response( + response=result, kwargs=None + ) == types.LiveClientMessage._from_response( + response=expected_result, kwargs=None + ) + # Config is a LiveConnectConfig + config = types.LiveConnectConfig( + speech_config=types.SpeechConfig( + voice_config=types.VoiceConfig( + prebuilt_voice_config=types.PrebuiltVoiceConfig( + voice_name='en-default' + ) + ), + language_code='en-US', + ), + enable_affective_dialog=True, + proactivity=types.ProactivityConfig(proactive_audio=True), + temperature=0.7, + top_p=0.8, + top_k=9, + max_output_tokens=10, + media_resolution=types.MediaResolution.MEDIA_RESOLUTION_MEDIUM, + seed=13, + system_instruction='test instruction', + ) + result = await get_connect_message( + mock_api_client(vertexai=vertexai), + model='test_model', config=config + ) + assert types.LiveClientMessage._from_response( + response=result, kwargs=None + ) == types.LiveClientMessage._from_response( + response=expected_result, kwargs=None + ) + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_bidi_setup_error_if_multispeaker_voice_config(vertexai): + + # Config is a dict + config_dict = { + 'speech_config': { + 'multi_speaker_voice_config': { + 'speaker_voice_configs': [ + { + 'speaker': 'Alice', + 'voice_config': { + 'prebuilt_voice_config': {'voice_name': 'leda'} + }, + }, + { + 'speaker': 'Bob', + 'voice_config': { + 'prebuilt_voice_config': {'voice_name': 'kore'} + }, + }, + ], + }, + }, + 'temperature': 0.7, + 'top_p': 0.8, + 'top_k': 9, + 'max_output_tokens': 10, + 'seed': 13, + 'system_instruction': 'test instruction', + 'media_resolution': 'MEDIA_RESOLUTION_MEDIUM', + } + with pytest.raises(ValueError, match='.*multi_speaker_voice_config.*'): + result = await get_connect_message( + mock_api_client(vertexai=vertexai), + model='test_model', + config=config_dict, + ) + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_explicit_vad(vertexai): + # Config is a dict + config_dict = {'explicit_vad_signal': True} + with pytest_helper.exception_if_mldev( + mock_api_client(vertexai=vertexai), ValueError + ): + result = await get_connect_message( + mock_api_client(vertexai=vertexai), model='test_model', config=config_dict + ) + if not vertexai: + return + assert result['setup']['explicitVadSignal'] == True + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_explicit_vad_config(vertexai): + api_client = mock_api_client(vertexai=vertexai) + + # Config is a dict + config_dict = {'explicit_vad_signal': True} + with pytest_helper.exception_if_mldev(api_client, ValueError): + result = await get_connect_message( + mock_api_client(vertexai=vertexai), + model='test_model', + config=config_dict, + ) + if not vertexai: + return + assert result['setup']['explicitVadSignal'] == True + + +@pytest.mark.asyncio +async def test_history_config(): + config_dict = { + 'history_config': {'initial_history_in_client_content': True}, + } + result = await get_connect_message( + mock_api_client(vertexai=False), model='test_model', config=config_dict + ) + assert result['setup']['historyConfig'] == { + 'initial_history_in_client_content': True, + } + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_bidi_setup_to_api_with_system_instruction_as_content_type( + vertexai, +): + config_dict = { + 'system_instruction': { + 'parts': [{'text': 'test instruction'}], + 'role': 'user', + }, + } + config = types.LiveConnectConfig(**config_dict) + expected_result = { + 'setup': { + 'model': 'test_model', + 'systemInstruction': { + 'parts': [{'text': 'test instruction'}], + 'role': 'user', + }, + } + } + if vertexai: + expected_result['setup'][ + 'model' + ] = 'projects/test_project/locations/us-central1/publishers/google/models/test_model' + expected_result['setup']['generationConfig'] = {} + expected_result['setup']['generationConfig']['responseModalities'] = [ + 'AUDIO' + ] + else: + expected_result['setup']['model'] = 'models/test_model' + + result = await get_connect_message( + mock_api_client(vertexai=vertexai), + model='test_model', config=config + ) + assert result == expected_result + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_bidi_setup_to_api_with_config_tools_google_search(vertexai): + config_dict = { + 'response_modalities': ['TEXT'], + 'system_instruction': 'test instruction', + 'generation_config': {'temperature': 0.7}, + 'tools': [{'google_search': {}}], + } + + config = types.LiveConnectConfig(**config_dict) + expected_result = { + 'setup': { + 'generationConfig': { + 'temperature': 0.7, + 'responseModalities': ['TEXT'], + }, + 'systemInstruction': { + 'parts': [{'text': 'test instruction'}], + 'role': 'user', + }, + 'tools': [{'googleSearch': {}}], + } + } + if vertexai: + expected_result['setup']['model'] = 'projects/test_project/locations/us-central1/publishers/google/models/test_model' + else: + expected_result['setup']['model'] = 'models/test_model' + + result = await get_connect_message( + mock_api_client(vertexai=vertexai), + model='test_model', config=config_dict + ) + + assert result == expected_result + + # Test config is a LiveConnectConfig + result = await get_connect_message( + mock_api_client(vertexai=vertexai), + model='test_model', config=config + ) + + assert result == expected_result + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_bidi_setup_to_api_with_config_tools_with_no_mcp(vertexai): + config_dict = { + 'response_modalities': ['TEXT'], + 'system_instruction': 'test instruction', + 'generation_config': {'temperature': 0.7}, + 'tools': [{'google_search': {}}], + } + + config = types.LiveConnectConfig(**config_dict) + expected_result = { + 'setup': { + 'generationConfig': { + 'temperature': 0.7, + 'responseModalities': ['TEXT'], + }, + 'systemInstruction': { + 'parts': [{'text': 'test instruction'}], + 'role': 'user', + }, + 'tools': [{'googleSearch': {}}], + } + } + if vertexai: + expected_result['setup']['model'] = 'projects/test_project/locations/us-central1/publishers/google/models/test_model' + else: + expected_result['setup']['model'] = 'models/test_model' + + @patch.object(live, "McpClientSession", new=None) + @patch.object(live, "McpTool", new=None) + async def get_connect_message_no_mcp(config): + return await get_connect_message( + mock_api_client(vertexai=vertexai), + model='test_model', config=config + ) + + result = await get_connect_message_no_mcp(config_dict) + assert result == expected_result + + result = await get_connect_message_no_mcp(config_dict) + assert result == expected_result + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_bidi_setup_to_api_with_context_window_compression( + vertexai +): + config = types.LiveConnectConfig( + generation_config=types.GenerationConfig(temperature=0.7), + response_modalities=['TEXT'], + system_instruction=types.Content( + parts=[types.Part(text='test instruction')], role='user' + ), + context_window_compression=types.ContextWindowCompressionConfig( + trigger_tokens=1000, + sliding_window=types.SlidingWindow(target_tokens=10), + ), + ) + expected_result = { + 'setup': { + 'generationConfig': { + 'temperature': 0.7, + 'responseModalities': ['TEXT'], + }, + 'systemInstruction': { + 'parts': [{'text': 'test instruction'}], + 'role': 'user', + }, + 'contextWindowCompression': { + 'trigger_tokens': 1000, + 'sliding_window': {'target_tokens': 10}, + } + } + } + if vertexai: + expected_result['setup']['model'] = 'projects/test_project/locations/us-central1/publishers/google/models/test_model' + else: + expected_result['setup']['model'] = 'models/test_model' + + result = await get_connect_message( + mock_api_client(vertexai=vertexai), + model='test_model', config=config + ) + assert result == expected_result + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_bidi_setup_to_api_with_config_tools_function_declaration( + vertexai +): + config_dict = { + 'generation_config': {'temperature': 0.7}, + 'tools': [{'function_declarations': function_declarations}], + } + config = types.LiveConnectConfig(**config_dict) + expected_result = { + 'setup': { + 'model': 'test_model', + 'tools': [{ + 'functionDeclarations': [{ + 'parameters': { + 'type': 'OBJECT', + 'properties': { + 'location': { + 'type': 'STRING', + 'description': ( + 'The location to get the weather for' + ), + }, + 'unit': {'type': 'STRING', 'enum': ['C', 'F']}, + }, + }, + 'name': 'get_current_weather', + 'description': 'Get the current weather in a city', + }], + }], + } + } + result = await get_connect_message( + mock_api_client(vertexai=vertexai), + model='test_model', config=config + ) + + assert result['setup']['tools'][0]['functionDeclarations'][0][ + 'description' + ] == ( + expected_result['setup']['tools'][0]['functionDeclarations'][0][ + 'description' + ] + ) + + result = await get_connect_message( + mock_api_client(vertexai=vertexai), + model='test_model', config=config + ) + + assert result['setup']['tools'][0]['functionDeclarations'][0][ + 'description' + ] == ( + expected_result['setup']['tools'][0]['functionDeclarations'][0][ + 'description' + ] + ) + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_bidi_setup_to_api_with_config_tools_function_directly( + vertexai +): + config_dict = { + 'generation_config': {'temperature': 0.7}, + 'tools': [get_current_weather], + } + config = types.LiveConnectConfig(**config_dict) + expected_result = { + 'setup': { + 'model': 'test_model', + 'tools': [{ + 'functionDeclarations': [{ + 'parameters': { + 'type': 'OBJECT', + 'properties': { + 'location': { + 'type': 'STRING', + 'description': ( + 'The location to get the weather for' + ), + }, + 'unit': {'type': 'STRING', 'enum': ['C', 'F']}, + }, + }, + 'name': 'get_current_weather', + 'description': 'Get the current weather in a city.', + }], + }], + } + } + result = await get_connect_message( + mock_api_client(vertexai=vertexai), + model='test_model', config=config + ) + + assert result['setup']['tools'][0]['functionDeclarations'][0][ + 'description' + ] == ( + expected_result['setup']['tools'][0]['functionDeclarations'][0][ + 'description' + ] + ) + + result = await get_connect_message( + mock_api_client(vertexai=vertexai), + model='test_model', config=config + ) + + assert result['setup']['tools'][0]['functionDeclarations'][0][ + 'description' + ] == ( + expected_result['setup']['tools'][0]['functionDeclarations'][0][ + 'description' + ] + ) + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_bidi_setup_to_api_with_tools_function_behavior(vertexai): + api_client = mock_api_client(vertexai=vertexai) + + declaration = types.FunctionDeclaration.from_callable( + client=api_client, callable=get_current_weather + ) + declaration.behavior = types.Behavior.NON_BLOCKING + config_dict = { + 'generation_config': {'temperature': 0.7}, + 'tools': [{'function_declarations': [declaration]}], + } + config = types.LiveConnectConfig(**config_dict) + + with pytest_helper.exception_if_vertex(api_client, ValueError): + result = await get_connect_message( + mock_api_client(vertexai=vertexai), model='test_model', config=config + ) + if vertexai: + return + + assert ( + result['setup']['tools'][0]['functionDeclarations'][0]['behavior'] + == 'NON_BLOCKING' + ) + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_bidi_setup_to_api_with_config_mcp_tools( + vertexai, +): + if mcp_types is None: + return + + expected_result_googleai = { + 'setup': { + 'model': 'models/test_model', + 'tools': [{ + 'functionDeclarations': [{ + 'parameters': { + 'type': 'OBJECT', + 'properties': { + 'location': { + 'type': 'STRING', + }, + }, + }, + 'name': 'get_weather', + 'description': 'Get the weather in a city.', + }], + }], + } + } + expected_result_vertexai = { + 'setup': { + 'generationConfig': { + 'responseModalities': [ + 'AUDIO', + ], + }, + 'model': ( + 'projects/test_project/locations/us-central1/publishers/google/models/test_model' + ), + 'tools': [{ + 'functionDeclarations': [{ + 'parameters': { + 'type': 'OBJECT', + 'properties': { + 'location': { + 'type': 'STRING', + }, + }, + }, + 'name': 'get_weather', + 'description': 'Get the weather in a city.', + }], + }], + } + } + result = await get_connect_message( + mock_api_client(vertexai=vertexai), + model='test_model', + config={ + 'tools': [ + mcp_types.Tool( + name='get_weather', + description='Get the weather in a city.', + inputSchema={ + 'type': 'object', + 'properties': {'location': {'type': 'string'}}, + }, + ) + ], + }, + ) + + assert ( + result == expected_result_vertexai + if vertexai + else expected_result_googleai + ) + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_bidi_setup_to_api_with_config_mcp_session( + vertexai, +): + if mcp_types is None: + return + + class MockMcpClientSession(McpClientSession): + + def __init__(self): + self._read_stream = None + self._write_stream = None + + async def list_tools(self): + return mcp_types.ListToolsResult( + tools=[ + mcp_types.Tool( + name='get_weather', + description='Get the weather in a city.', + inputSchema={ + 'type': 'object', + 'properties': {'location': {'type': 'string'}}, + }, + ), + ] + ) + + expected_result_googleai = { + 'setup': { + 'model': 'models/test_model', + 'tools': [{ + 'functionDeclarations': [{ + 'parameters': { + 'type': 'OBJECT', + 'properties': { + 'location': { + 'type': 'STRING', + }, + }, + }, + 'name': 'get_weather', + 'description': 'Get the weather in a city.', + }], + }], + } + } + expected_result_vertexai = { + 'setup': { + 'generationConfig': { + 'responseModalities': [ + 'AUDIO', + ], + }, + 'model': ( + 'projects/test_project/locations/us-central1/publishers/google/models/test_model' + ), + 'tools': [{ + 'functionDeclarations': [{ + 'parameters': { + 'type': 'OBJECT', + 'properties': { + 'location': { + 'type': 'STRING', + }, + }, + }, + 'name': 'get_weather', + 'description': 'Get the weather in a city.', + }], + }], + } + } + result = await get_connect_message( + mock_api_client(vertexai=vertexai), + model='test_model', + config={ + 'tools': [MockMcpClientSession()], + }, + ) + + assert ( + result == expected_result_vertexai + if vertexai + else expected_result_googleai + ) + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_bidi_setup_to_api_with_config_tools_code_execution( + vertexai +): + config_dict = { + 'tools': [{'code_execution': {}}], + } + config = types.LiveConnectConfig(**config_dict) + expected_result = { + 'setup': { + 'model': 'test_model', + 'tools': [{ + 'codeExecution': {}, + }], + } + } + result = await get_connect_message( + mock_api_client(vertexai=vertexai), + model='test_model', config=config + ) + + assert result['setup']['tools'][0] == expected_result['setup']['tools'][0] + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_bidi_setup_to_api_with_realtime_input_config(vertexai): + config_dict = { + 'realtime_input_config': { + 'automatic_activity_detection': { + 'disabled': True, + 'start_of_speech_sensitivity': 'START_SENSITIVITY_HIGH', + 'end_of_speech_sensitivity': 'END_SENSITIVITY_HIGH', + 'prefix_padding_ms': 20, + 'silence_duration_ms': 100, + }, + 'activity_handling': 'NO_INTERRUPTION', + 'turn_coverage': 'TURN_INCLUDES_ALL_INPUT', + } + } + + config = types.LiveConnectConfig(**config_dict) + expected_result = { + 'setup': { + 'model': 'test_model', + 'realtimeInputConfig': config_dict['realtime_input_config'], + } + } + + result = await get_connect_message( + mock_api_client(vertexai=vertexai), + model='test_model', config=config + ) + + assert ( + result['setup']['realtimeInputConfig'] + == expected_result['setup']['realtimeInputConfig'] + ) + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_bidi_setup_to_api_with_input_transcription(vertexai): + config_dict = { + 'input_audio_transcription': {}, + } + config = types.LiveConnectConfig(**config_dict) + expected_result = { + 'setup': { + 'model': 'test_model', + 'inputAudioTranscription': {}, + } + } + + result = await get_connect_message( + mock_api_client(vertexai=vertexai), model='test_model', config=config + ) + + assert ( + result['setup']['inputAudioTranscription'] + == expected_result['setup']['inputAudioTranscription'] + ) + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_bidi_setup_to_api_with_output_transcription(vertexai): + config_dict = { + 'output_audio_transcription': {}, + } + config = types.LiveConnectConfig(**config_dict) + expected_result = { + 'setup': { + 'model': 'test_model', + 'outputAudioTranscription': {}, + } + } + + result = await get_connect_message( + mock_api_client(vertexai=vertexai), + model='test_model', config=config + ) + + assert ( + result['setup']['outputAudioTranscription'] + == expected_result['setup']['outputAudioTranscription'] + ) + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_bidi_setup_to_api_with_media_resolution(vertexai): + config_dict = { + 'media_resolution': 'MEDIA_RESOLUTION_LOW', + } + config = types.LiveConnectConfig(**config_dict) + expected_result = { + 'setup': { + 'model': 'test_model', + 'generationConfig': {'mediaResolution':'MEDIA_RESOLUTION_LOW'}, + } + } + + result = await get_connect_message( + mock_api_client(vertexai=vertexai), + model='test_model', config=config + ) + + assert ( + result['setup']['generationConfig']['mediaResolution'] + == expected_result['setup']['generationConfig']['mediaResolution'] + ) + + +@pytest.mark.parametrize('vertexai', [True]) +@pytest.mark.asyncio +async def test_bidi_setup_publishers( + vertexai +): + expected_result = { + 'setup': { + 'generationConfig': { + 'responseModalities': [ + 'AUDIO', + ], + }, + 'model': 'projects/test_project/locations/us-central1/publishers/google/models/test_model', + } + } + result = await get_connect_message( + mock_api_client(vertexai=vertexai), + model='publishers/google/models/test_model') + + assert result == expected_result + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_bidi_setup_generation_config_warning( + vertexai +): + with pytest.warns( + DeprecationWarning, + match='Setting `LiveConnectConfig.generation_config` is deprecated' + ): + result = await get_connect_message( + mock_api_client(vertexai=vertexai), + model='models/test_model', + config={'generation_config': {'temperature': 0.7}}) + + assert result['setup']['generationConfig']['temperature'] == 0.7 + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_bidi_setup_to_api_with_session_resumption(vertexai): + config_dict = { + 'session_resumption': {'handle': 'test_handle'}, + } + config = types.LiveConnectConfig(**config_dict) + + result = await get_connect_message( + mock_api_client(vertexai=vertexai), + model='test_model', + config=config + ) + expected_result = { + 'setup': { + 'sessionResumption': { + 'handle': 'test_handle', + }, + } + } + if vertexai: + expected_result['setup']['generationConfig'] = { + 'responseModalities': [ + 'AUDIO', + ], + } + expected_result['setup']['model'] = 'projects/test_project/locations/us-central1/publishers/google/models/test_model' + else: + expected_result['setup']['model'] = 'models/test_model' + assert result == expected_result + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_bidi_setup_to_api_with_transparent_session_resumption(vertexai): + api_client = mock_api_client(vertexai=vertexai) + config_dict = { + 'session_resumption': {'handle': 'test_handle', 'transparent': True}, + } + config = types.LiveConnectConfig(**config_dict) + + with pytest_helper.exception_if_mldev(api_client, ValueError): + result = await get_connect_message( + mock_api_client(vertexai=vertexai), + model='test_model', + config=config + ) + + expected_result = { + 'setup': { + 'sessionResumption': { + 'handle': 'test_handle', + 'transparent': True, + }, + } + } + if vertexai: + expected_result['setup']['generationConfig'] = { + 'responseModalities': [ + 'AUDIO', + ], + } + expected_result['setup']['model'] = 'projects/test_project/locations/us-central1/publishers/google/models/test_model' + else: + return + + assert result == expected_result + + +@pytest.mark.parametrize('vertexai', [True, False]) +def test_parse_client_message_str( mock_websocket, vertexai): + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + result = session._parse_client_message('test') + assert 'client_content' in result + assert result == { + 'client_content': { + 'turn_complete': False, + 'turns': [{'role': 'user', 'parts': [{'text': 'test'}]}], + } + } + # _parse_client_message returns a TypedDict, so we should be able to + # construct a LiveClientMessage from it + assert types.LiveClientMessage(**result) + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_bidi_setup_to_api_with_thinking_config(vertexai): + config_dict = { + 'thinking_config': { + 'include_thoughts': True, + 'thinking_budget': 1024, + } + } + + expected_gen_config = { + 'thinkingConfig': { + 'include_thoughts': True, + 'thinking_budget': 1024, + } + } + + if vertexai: + expected_gen_config['responseModalities'] = ['AUDIO'] + + expected_result = { + 'setup': { + 'generationConfig': expected_gen_config, + } + } + + if vertexai: + expected_result['setup'][ + 'model' + ] = 'projects/test_project/locations/us-central1/publishers/google/models/test_model' + else: + expected_result['setup']['model'] = 'models/test_model' + + result = await get_connect_message( + mock_api_client(vertexai=vertexai), model='test_model', config=config_dict + ) + result = pytest_helper.camel_to_snake_all_keys(result) + expected_result = pytest_helper.camel_to_snake_all_keys(expected_result) + assert result == expected_result + + +@pytest.mark.parametrize('vertexai', [True, False]) +def test_parse_client_message_blob( mock_websocket, vertexai): + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + result = session._parse_client_message( + types.Blob(data=bytes([0, 0, 0]), mime_type='text/plain') + ) + assert 'realtime_input' in result + assert result == { + 'realtime_input': { + 'media_chunks': [{'mime_type': 'text/plain', 'data': 'AAAA'}], + } + } + + +@pytest.mark.parametrize('vertexai', [True, False]) +def test_parse_client_message_blob_dict( + mock_websocket, vertexai +): + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + + blob = types.Blob(data=bytes([0, 0, 0]), mime_type='text/plain') + blob_dict = blob.model_dump() + result = session._parse_client_message(blob_dict) + assert 'realtime_input' in result + assert result == { + 'realtime_input': { + 'media_chunks': [{'mime_type': 'text/plain', 'data': 'AAAA'}], + } + } + + +@pytest.mark.parametrize('vertexai', [True, False]) +def test_parse_client_message_client_content( + mock_websocket, vertexai +): + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + result = session._parse_client_message( + types.LiveClientContent( + turn_complete=False, + turns=[types.Content(parts=[types.Part(text='test')], role='user')], + ) + ) + assert 'client_content' in result + assert result == { + 'client_content': { + 'turn_complete': False, + 'turns': [{'role': 'user', 'parts': [{'text': 'test'}]}], + } + } + + +@pytest.mark.parametrize('vertexai', [True, False]) +def test_parse_client_message_client_content_blob( + mock_websocket, vertexai +): + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + client_content = types.LiveClientContent( + turn_complete=False, + turns=[ + types.Content( + parts=[ + types.Part( + inline_data=types.Blob( + data=bytes([0, 0, 0]), mime_type='text/plain' + ) + ) + ], + role='user', + ) + ], + ) + result = session._parse_client_message(client_content) + assert 'client_content' in result + assert ( + type( + result['client_content']['turns'][0]['parts'][0]['inline_data'][ + 'data' + ] + ) + == str + ) + assert result == { + 'client_content': { + 'turn_complete': False, + 'turns': [{ + 'role': 'user', + 'parts': [ + {'inline_data': {'mime_type': 'text/plain', 'data': 'AAAA'}} + ], + }], + } + } + + +@pytest.mark.parametrize('vertexai', [True, False]) +def test_parse_client_message_client_content_dict( + mock_websocket, vertexai +): + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + client_content = types.LiveClientContent( + turn_complete=False, + turns=[ + types.Content( + parts=[ + types.Part( + inline_data=types.Blob( + data=bytes([0, 0, 0]), mime_type='text/plain' + ) + ) + ], + role='user', + ) + ], + ) + result = session._parse_client_message( + client_content.model_dump(mode='json', exclude_none=True) + ) + assert 'client_content' in result + assert ( + type( + result['client_content']['turns'][0]['parts'][0]['inline_data'][ + 'data' + ] + ) + == str + ) + assert result == { + 'client_content': { + 'turn_complete': False, + 'turns': [{ + 'role': 'user', + 'parts': [ + {'inline_data': {'mime_type': 'text/plain', 'data': 'AAAA'}} + ], + }], + } + } + + +@pytest.mark.parametrize('vertexai', [True, False]) +def test_parse_client_message_realtime_input( + mock_websocket, vertexai +): + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + input = types.LiveClientRealtimeInput( + media_chunks=[types.Blob(data=bytes([0, 0, 0]), mime_type='text/plain')] + ) + result = session._parse_client_message(input) + assert 'realtime_input' in result + assert result == { + 'realtime_input': { + 'media_chunks': [{'mime_type': 'text/plain', 'data': 'AAAA'}], + } + } + + +@pytest.mark.parametrize('vertexai', [True, False]) +def test_parse_client_message_realtime_input_dict( + mock_websocket, vertexai +): + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + input = types.LiveClientRealtimeInput( + media_chunks=[types.Blob(data=bytes([0, 0, 0]), mime_type='text/plain')] + ) + result = session._parse_client_message( + input.model_dump(mode='json', exclude_none=True) + ) + assert 'realtime_input' in result + assert result == { + 'realtime_input': { + 'media_chunks': [{'mime_type': 'text/plain', 'data': 'AAAA'}], + } + } + + +@pytest.mark.parametrize('vertexai', [True, False]) +def test_parse_client_message_tool_response( + mock_websocket, vertexai +): + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + input = types.LiveClientToolResponse( + function_responses=[ + types.FunctionResponse( + id='test_id', + name='test_name', + response={'result': 'test_response'}, + ) + ] + ) + result = session._parse_client_message(input) + assert 'tool_response' in result + assert result == { + 'tool_response': { + 'function_responses': [ + { + 'id': 'test_id', + 'name': 'test_name', + 'response': { + 'result': 'test_response', + }, + }, + ], + } + } + + +@pytest.mark.parametrize('vertexai', [True, False]) +def test_parse_client_message_function_response( + mock_websocket, vertexai +): + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + input = types.FunctionResponse( + id='test_id', + name='test_name', + response={ + 'result': 'test_response', + 'user_name': 'test_user_name', + 'userEmail': 'test_user_email', + }, + ) + result = session._parse_client_message(input) + assert 'tool_response' in result + assert result == { + 'tool_response': { + 'function_responses': [ + { + 'id': 'test_id', + 'name': 'test_name', + 'response': { + 'result': 'test_response', + 'user_name': 'test_user_name', + 'userEmail': 'test_user_email', + }, + }, + ], + } + } + + +@pytest.mark.parametrize('vertexai', [True, False]) +def test_parse_client_message_tool_response_dict_with_only_response( + mock_websocket, vertexai +): + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + input = { + 'id': 'test_id', + 'name': 'test_name', + 'response': { + 'result': 'test_response', + } + } + result = session._parse_client_message(input) + assert 'tool_response' in result + assert result == { + 'tool_response': { + 'function_responses': [ + { + 'id': 'test_id', + 'name': 'test_name', + 'response': { + 'result': 'test_response', + }, + }, + ], + } + } + + +@pytest.mark.parametrize('vertexai', [True, False]) +def test_parse_client_message_realtime_tool_response( + mock_websocket, vertexai +): + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + input = types.LiveClientToolResponse( + function_responses=[ + types.FunctionResponse( + id='test_id', + name='test_name', + response={'result': 'test_response'}, + ) + ] + ) + + result = session._parse_client_message( + input.model_dump(mode='json', exclude_none=True) + ) + assert 'tool_response' in result + assert result == { + 'tool_response': { + 'function_responses': [ + { + 'id': 'test_id', + 'name': 'test_name', + 'response': { + 'result': 'test_response', + }, + }, + ], + } + } + + +@pytest.mark.asyncio +async def test_connect_with_provided_credentials(mock_websocket): + # custom oauth2 credentials + credentials = Credentials(token='provided_fake_token') + # mock api client + client = mock_api_client(vertexai=True, credentials=credentials) + capture = {} + + @contextlib.asynccontextmanager + async def mock_connect(uri, additional_headers=None, **kwargs): + capture['headers'] = additional_headers + yield mock_websocket + + @patch.object(live, 'ws_connect', new=mock_connect) + async def _test_connect(): + live_module = live.AsyncLive(client) + async with live_module.connect(model='test-model'): + pass + + assert 'Authorization' in capture['headers'] + assert capture['headers']['Authorization'] == 'Bearer provided_fake_token' + + await _test_connect() + + +@pytest.mark.asyncio +async def test_connect_with_default_credentials(mock_websocket): + # mock api client + client = mock_api_client(vertexai=True, credentials=None) + # mock google auth cred + mock_google_auth_default = Mock(return_value=(None, None)) + mock_creds = Mock(token='default_test_token') + mock_google_auth_default.return_value = (mock_creds, None) + capture = {} + + @contextlib.asynccontextmanager + async def mock_connect(uri, additional_headers=None, **kwargs): + capture['headers'] = additional_headers + yield mock_websocket + + @patch('google.auth.default', new=mock_google_auth_default) + @patch.object(live, 'ws_connect', new=mock_connect) + async def _test_connect(): + live_module = live.AsyncLive(client) + async with live_module.connect(model='test-model'): + pass + + assert 'Authorization' in capture['headers'] + assert capture['headers']['Authorization'] == 'Bearer default_test_token' + + await _test_connect() + + +@pytest.mark.asyncio +async def test_connect_with_custom_base_url(mock_websocket): + # mock api client + client = gl_client.BaseApiClient( + vertexai=True, + http_options={ + 'base_url': 'https://custom-base-url.com', + 'headers': {'Authorization': 'Bearer custom_test_token'}, + } + ) + # No ADC credentials. + capture = {} + + @contextlib.asynccontextmanager + async def mock_connect(uri, additional_headers=None, **kwargs): + capture['uri'] = uri + capture['headers'] = additional_headers + yield mock_websocket + + @patch.object(live, 'ws_connect', new=mock_connect) + async def _test_connect(): + live_module = live.AsyncLive(client) + async with live_module.connect(model='test-model'): + pass + + assert 'Authorization' in capture['headers'] + assert capture['headers']['Authorization'] == 'Bearer custom_test_token' + assert capture['uri'] == 'https://custom-base-url.com' + + await _test_connect() + + +@pytest.mark.parametrize('vertexai', [False]) +@pytest.mark.asyncio +async def test_bidi_setup_to_api_with_auth_tokens(mock_websocket, vertexai): + api_client_mock = mock_api_client(vertexai=vertexai) + api_client_mock.api_key = 'auth_tokens/TEST_AUTH_TOKEN' + result = await get_connect_message(api_client_mock, model='test_model') + + mock_ws = AsyncMock() + mock_ws.send = AsyncMock() + mock_ws.recv = AsyncMock( + return_value=( + b'{\n "setupComplete": {"sessionId": "test_session_id"}\n}\n' + ) + ) + capture = {} + + @contextlib.asynccontextmanager + async def mock_connect(uri, additional_headers=None, **kwargs): + capture['uri'] = uri + capture['headers'] = additional_headers + yield mock_ws + + with patch.object(live, 'ws_connect', new=mock_connect): + live_module = live.AsyncLive(api_client_mock) + async with live_module.connect( + model='test_model', + ): + pass + + assert ( + 'Authorization' in capture['headers'] + ), 'Authorization key is missing from headers' + assert ( + capture['headers']['Authorization'] == 'Token auth_tokens/TEST_AUTH_TOKEN' + ) + assert 'BidiGenerateContentConstrained' in capture['uri'] + + +@pytest.mark.parametrize('vertexai', [False]) +@pytest.mark.asyncio +async def test_bidi_setup_to_api_with_api_key(mock_websocket, vertexai): + api_client_mock = mock_api_client(vertexai=vertexai) + api_client_mock._http_options = types.HttpOptions.model_validate( + {'headers': {'x-goog-api-key': 'TEST_API_KEY'}} + ) + result = await get_connect_message(api_client_mock, model='test_model') + + mock_ws = AsyncMock() + mock_ws.send = AsyncMock() + mock_ws.recv = AsyncMock( + return_value=( + b'{\n "setupComplete": {"sessionId": "test_session_id"}\n}\n' + ) + ) + capture = {} + + @contextlib.asynccontextmanager + async def mock_connect(uri, additional_headers=None, **kwargs): + capture['uri'] = uri + capture['headers'] = additional_headers + yield mock_ws + + with patch.object(live, 'ws_connect', new=mock_connect): + live_module = live.AsyncLive(api_client_mock) + async with live_module.connect( + model='test_model', + ): + pass + + assert 'x-goog-api-key' in capture['headers'], "x-goog-api-key is missing from headers" + assert capture['headers']['x-goog-api-key'] == 'TEST_API_KEY' + assert 'BidiGenerateContent' in capture['uri'] + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_async_session_setup_complete_with_voice_consent_signature( + vertexai, +): + mock_ws = AsyncMock() + mock_ws.send = AsyncMock() + mock_ws.recv = AsyncMock( + return_value=( + b'{"setupComplete": {"sessionId": "test_session_id",' + b' "voiceConsentSignature": {"signature": "test_sig_abc123"}}}' + ) + ) + mock_ws.close = AsyncMock() + + mock_google_auth_default = Mock(return_value=(None, None)) + mock_creds = Mock(token='test_token') + mock_google_auth_default.return_value = (mock_creds, None) + + @contextlib.asynccontextmanager + async def mock_connect(uri, additional_headers=None, **kwargs): + yield mock_ws + + @patch('google.auth.default', new=mock_google_auth_default) + @patch.object(live, 'ws_connect', new=mock_connect) + async def _test_connect(): + live_module = live.AsyncLive(mock_api_client(vertexai=vertexai)) + async with live_module.connect(model='test_model') as session: + assert session.setup_complete is not None + assert session.setup_complete.session_id == 'test_session_id' + assert session.setup_complete.voice_consent_signature is not None + assert ( + session.setup_complete.voice_consent_signature.signature + == 'test_sig_abc123' + ) + + await _test_connect() + + +@pytest.mark.parametrize('vertexai', [False]) +@pytest.mark.asyncio +async def test_bidi_setup_replicated_voice_config_with_consent(vertexai): + config = types.LiveConnectConfig( + response_modalities=['AUDIO'], + speech_config=types.SpeechConfig( + voice_config=types.VoiceConfig( + replicated_voice_config=types.ReplicatedVoiceConfig( + mime_type='audio/wav', + voice_sample_audio=b'fake_audio_data', + consent_audio=b'fake_consent_data', + ) + ) + ), + ) + result = await get_connect_message( + mock_api_client(vertexai=vertexai), model='test_model', config=config + ) + + setup = result.get('setup', {}) + gen_config = setup.get('generationConfig', {}) + speech_config = gen_config.get('speechConfig', {}) + voice_config = speech_config.get('voice_config', {}) + replicated = voice_config.get('replicated_voice_config', {}) + + assert replicated.get('mime_type') == 'audio/wav' + assert replicated.get('voice_sample_audio') is not None + assert replicated.get('consent_audio') is not None + + config_with_sig = types.LiveConnectConfig( + response_modalities=['AUDIO'], + speech_config=types.SpeechConfig( + voice_config=types.VoiceConfig( + replicated_voice_config=types.ReplicatedVoiceConfig( + mime_type='audio/wav', + voice_sample_audio=b'fake_audio_data', + voice_consent_signature=types.VoiceConsentSignature( + signature='test_sig_abc123' + ), + ) + ) + ), + ) + result_with_sig = await get_connect_message( + mock_api_client(vertexai=vertexai), + model='test_model', + config=config_with_sig, + ) + + setup_sig = result_with_sig.get('setup', {}) + gen_config_sig = setup_sig.get('generationConfig', {}) + speech_config_sig = gen_config_sig.get('speechConfig', {}) + voice_config_sig = speech_config_sig.get('voice_config', {}) + replicated_sig = voice_config_sig.get('replicated_voice_config', {}) + + assert replicated_sig.get('mime_type') == 'audio/wav' + assert replicated_sig.get('voice_sample_audio') is not None + assert replicated_sig.get('voice_consent_signature') is not None + assert ( + replicated_sig['voice_consent_signature'].get('signature') + == 'test_sig_abc123' + ) + diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/live/test_live_music.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/live/test_live_music.py new file mode 100644 index 0000000000000000000000000000000000000000..f51f8248d6f88f856b636930957e7b96b5456153 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/live/test_live_music.py @@ -0,0 +1,362 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for live_music.py.""" +import contextlib +import json +from typing import AsyncIterator +from unittest import mock +from unittest.mock import AsyncMock +from unittest.mock import Mock +from unittest.mock import patch +import warnings + +from google.oauth2.credentials import Credentials +import pytest +from websockets import client + +from ... import _api_client as api_client +from ... import _common +from ... import Client +from ... import client as gl_client +from ... import live +from ... import live_music +from ... import types +from .. import pytest_helper +try: + import aiohttp + AIOHTTP_NOT_INSTALLED = False +except ImportError: + AIOHTTP_NOT_INSTALLED = True + aiohttp = mock.MagicMock() + + +requires_aiohttp = pytest.mark.skipif( + AIOHTTP_NOT_INSTALLED, reason="aiohttp is not installed, skipping test." +) + + +def mock_api_client(vertexai=False, credentials=None): + api_client = mock.MagicMock(spec=gl_client.BaseApiClient) + if not vertexai: + api_client.api_key = 'TEST_API_KEY' + api_client.location = None + api_client.project = None + else: + api_client.api_key = None + api_client.location = 'us-central1' + api_client.project = 'test_project' + + api_client._host = lambda: 'test_host' + api_client._credentials = credentials + api_client._http_options = types.HttpOptions.model_validate( + {'headers': {}} + ) # Ensure headers exist + api_client.vertexai = vertexai + api_client._api_client = api_client + return api_client + + +@pytest.fixture +def mock_websocket(): + websocket = AsyncMock(spec=client.ClientConnection) + websocket.send = AsyncMock() + websocket.recv = AsyncMock( + return_value=b"""{ + "serverContent": { + "audioChunks": [ + { + "data": "Z2VsYmFuYW5h", + "mimeType": "audio/l16;rate=48000;channels=2", + "sourceMetadata": { + "clientContent": { + "weightedPrompts": [ + { + "text": "Jazz", + "weight": 1 + } + ] + }, + "musicGenerationConfig": { + "seed": -957124937, + "bpm": 140, + "scale": "A_FLAT_MAJOR_F_MINOR" + } + } + } + ] + } +}""" + ) # Default response + websocket.close = AsyncMock() + return websocket + + +async def get_connect_message(api_client, model): + mock_ws = AsyncMock() + mock_ws.send = AsyncMock() + mock_ws.recv = AsyncMock(return_value=b'some response') + + mock_google_auth_default = Mock(return_value=(None, None)) + mock_creds = Mock(token='test_token') + mock_google_auth_default.return_value = (mock_creds, None) + + @contextlib.asynccontextmanager + async def mock_connect(uri, additional_headers=None): + yield mock_ws + + @patch('google.auth.default', new=mock_google_auth_default) + @patch.object(live_music, 'connect', new=mock_connect) + async def _test_connect(): + live_module = live.AsyncLive(api_client) + async with live_module.music.connect( + model=model, + ): + pass + + mock_ws.send.assert_called_once() + return json.loads(mock_ws.send.call_args[0][0]) + + return await _test_connect() + + +def test_mldev_from_env(monkeypatch): + api_key = 'google_api_key' + monkeypatch.setenv('GOOGLE_API_KEY', api_key) + + client = Client() + + assert not client.aio.live.music._api_client.vertexai + assert client.aio.live.music._api_client.api_key == api_key + assert isinstance(client.aio.live._api_client, api_client.BaseApiClient) + + +@requires_aiohttp +def test_vertex_from_env(monkeypatch): + project_id = 'fake_project_id' + location = 'fake-location' + monkeypatch.setenv('GOOGLE_GENAI_USE_VERTEXAI', 'true') + monkeypatch.setenv('GOOGLE_CLOUD_PROJECT', project_id) + monkeypatch.setenv('GOOGLE_CLOUD_LOCATION', location) + + client = Client() + + assert client.aio.live.music._api_client.vertexai + assert client.aio.live.music._api_client.project == project_id + assert isinstance(client.aio.live._api_client, api_client.BaseApiClient) + + +def test_websocket_base_url(): + base_url = 'https://test.com' + api_client = gl_client.BaseApiClient( + api_key='google_api_key', + http_options={'base_url': base_url}, + ) + assert api_client._websocket_base_url() == 'wss://test.com' + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_async_session_send_weighted_prompts( + mock_websocket, vertexai +): + session = live_music.AsyncMusicSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + if vertexai: + with pytest.raises(NotImplementedError): + await session.set_weighted_prompts(prompts=[types.WeightedPrompt(text='Jazz', weight=1)]) + return + await session.set_weighted_prompts(prompts=[types.WeightedPrompt(text='Jazz', weight=1)]) + mock_websocket.send.assert_called_once() + sent_data = json.loads(mock_websocket.send.call_args[0][0]) + assert 'clientContent' in sent_data + assert sent_data['clientContent']['weightedPrompts'][0]['text'] == 'Jazz' + assert sent_data['clientContent']['weightedPrompts'][0]['weight'] == 1 + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_async_session_send_config( + mock_websocket, vertexai +): + session = live_music.AsyncMusicSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + if vertexai: + with pytest.raises(NotImplementedError): + await session.set_music_generation_config( + config=types.LiveMusicGenerationConfig( + bpm=140, + music_generation_mode=types.MusicGenerationMode.VOCALIZATION, + ) + ) + return + await session.set_music_generation_config( + config=types.LiveMusicGenerationConfig( + bpm=140, + music_generation_mode=types.MusicGenerationMode.VOCALIZATION, + ) + ) + mock_websocket.send.assert_called_once() + sent_data = json.loads(mock_websocket.send.call_args[0][0]) + assert 'musicGenerationConfig' in sent_data + assert sent_data['musicGenerationConfig']['bpm'] == 140 + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_async_session_control_signal_play( + mock_websocket, vertexai +): + session = live_music.AsyncMusicSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + if vertexai: + with pytest.raises(NotImplementedError): + await session.play() + return + await session.play() + mock_websocket.send.assert_called_once() + sent_data = json.loads(mock_websocket.send.call_args[0][0]) + assert 'playbackControl' in sent_data + assert 'PLAY' in sent_data['playbackControl'] + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_async_session_control_signal_pause( + mock_websocket, vertexai +): + session = live_music.AsyncMusicSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + if vertexai: + with pytest.raises(NotImplementedError): + await session.pause() + return + await session.pause() + mock_websocket.send.assert_called_once() + sent_data = json.loads(mock_websocket.send.call_args[0][0]) + assert 'playbackControl' in sent_data + assert 'PAUSE' in sent_data['playbackControl'] + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_async_session_control_signal_stop( + mock_websocket, vertexai +): + session = live_music.AsyncMusicSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + if vertexai: + with pytest.raises(NotImplementedError): + await session.stop() + return + await session.stop() + mock_websocket.send.assert_called_once() + sent_data = json.loads(mock_websocket.send.call_args[0][0]) + assert 'playbackControl' in sent_data + assert 'STOP' in sent_data['playbackControl'] + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_async_session_control_signal_reset_context( + mock_websocket, vertexai +): + session = live_music.AsyncMusicSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + if vertexai: + with pytest.raises(NotImplementedError): + await session.reset_context() + return + await session.reset_context() + mock_websocket.send.assert_called_once() + sent_data = json.loads(mock_websocket.send.call_args[0][0]) + assert 'playbackControl' in sent_data + assert 'RESET_CONTEXT' in sent_data['playbackControl'] + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_async_session_receive( mock_websocket, vertexai): + session = live_music.AsyncMusicSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + if vertexai: + with pytest.raises(NotImplementedError): + async for _ in session.receive(): + pass + return + async for response in session.receive(): + assert isinstance(response, types.LiveMusicServerMessage) + audio_chunk = response.server_content.audio_chunks[0] + # Data contains decoded b64 audio + assert audio_chunk.data == b'gelbanana' + assert audio_chunk.mime_type == 'audio/l16;rate=48000;channels=2' + assert audio_chunk.source_metadata.client_content.weighted_prompts[0].text == 'Jazz' + assert audio_chunk.source_metadata.client_content.weighted_prompts[0].weight == 1 + assert audio_chunk.source_metadata.music_generation_config.bpm == 140 + break + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_async_session_receive_error( + mock_websocket, vertexai +): + mock_websocket.recv = AsyncMock(return_value='invalid json') + session = live_music.AsyncMusicSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + with pytest.raises(ValueError): + await session.receive().__anext__() + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_async_session_close( mock_websocket, vertexai): + session = live_music.AsyncMusicSession( + mock_api_client(vertexai=vertexai), mock_websocket + ) + await session.close() + mock_websocket.close.assert_called_once() + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_setup_to_api(vertexai): + if vertexai: + with pytest.raises(NotImplementedError): + await get_connect_message( + mock_api_client(vertexai=vertexai), + model='test_model' + ) + return + result = await get_connect_message( + mock_api_client(vertexai=vertexai), + model='test_model' + ) + expected_result = {'setup': {}} + if vertexai: + # Vertex is not supported yet + assert False + else: + expected_result['setup']['model'] = 'models/test_model' + assert result == expected_result diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/live/test_live_response.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/live/test_live_response.py new file mode 100644 index 0000000000000000000000000000000000000000..ab93b24c61c3ae580a7ffdab946fcb1b4dea5d02 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/live/test_live_response.py @@ -0,0 +1,163 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +"""Tests for live response handling.""" +import json +from typing import cast +from unittest import mock +from unittest.mock import AsyncMock + +import pytest + +from ... import _api_client as api_client +from ... import _common +from ... import Client +from ... import client as gl_client +from ... import live +from ... import types + + +def mock_api_client(vertexai=False): + """Creates a mock BaseApiClient.""" + mock_client = mock.MagicMock(spec=gl_client.BaseApiClient) + if not vertexai: + mock_client.api_key = 'TEST_API_KEY' + mock_client.location = None + mock_client.project = None + else: + mock_client.api_key = None + mock_client.location = 'us-central1' + mock_client.project = 'test_project' + + mock_client._host = lambda: 'test_host' + mock_client._http_options = types.HttpOptions.model_validate( + {'headers': {}} + ) + mock_client.vertexai = vertexai + return mock_client + + +@pytest.fixture +def mock_websocket(): + """Provides a mock websocket connection.""" + # Use live.ClientConnection if that's the specific type hint in AsyncSession + websocket = AsyncMock(spec=live.ClientConnection) + websocket.send = AsyncMock() + # Set default recv value, will be overridden in the test + websocket.recv = AsyncMock(return_value='{}') + websocket.close = AsyncMock() + return websocket + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_receive_server_content(mock_websocket, vertexai): + + raw_response_json = json.dumps({ + "usageMetadata": { + "promptTokenCount": 15, + "responseTokenCount": 25, + "candidatesTokenCount": 50, + "totalTokenCount": 200, + "responseTokensDetails": [ + { + "tokenCount": 20, + "modality": "TEXT", + } + ], + "candidatesTokensDetails": [ + { + "tokenCount": 10, + "modality": "TEXT", + } + ], + }, + "serverContent": { + "modelTurn": { + "parts": [{"text": "This is a simple response."}] + }, + "turnComplete": True, + "groundingMetadata": { + "web_search_queries": ["test query"], + "groundingChunks": [{ + "web": { + "domain": "google.com", + "title": "Search results", + } + }] + } + } + }) + mock_websocket.recv.return_value = raw_response_json + + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + result = await session._receive() + + # Assert the results + assert isinstance(result, types.LiveServerMessage) + + assert ( + result.server_content.model_turn.parts[0].text + == "This is a simple response." + ) + assert result.server_content.turn_complete + assert result.server_content.grounding_metadata.web_search_queries == ["test query"] + assert result.server_content.grounding_metadata.grounding_chunks[0].web.domain == "google.com" + assert result.server_content.grounding_metadata.grounding_chunks[0].web.title == "Search results" + # Verify usageMetadata was parsed + assert isinstance(result.usage_metadata, types.UsageMetadata) + assert result.usage_metadata.prompt_token_count == 15 + assert result.usage_metadata.total_token_count == 200 + if not vertexai: + assert result.usage_metadata.response_token_count == 25 + assert result.usage_metadata.response_tokens_details[0].token_count == 20 + else: + # VertexAI maps candidatesTokenCount to responseTokenCount and maps + # candidatesTokensDetails to responseTokensDetails. + assert result.usage_metadata.response_token_count == 50 + assert result.usage_metadata.response_tokens_details[0].token_count == 10 + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_receive_server_content_with_turn_reason(mock_websocket, vertexai): + """Tests parsing of LiveServerContent with turn_complete_reason and waiting_for_input.""" + + raw_response_json = json.dumps({ + "serverContent": { + "modelTurn": { + "parts": [{"text": "Please provide more details."}] + }, + "turnComplete": True, + "turnCompleteReason": "NEED_MORE_INPUT", + "waitingForInput": True + } + }) + mock_websocket.recv.return_value = raw_response_json + + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + result = await session._receive() + + # Assert the results + assert isinstance(result, types.LiveServerMessage) + assert result.server_content is not None + + assert result.server_content.model_turn.parts[0].text == "Please provide more details." + assert result.server_content.turn_complete is True + assert result.server_content.turn_complete_reason == types.TurnCompleteReason.NEED_MORE_INPUT + assert result.server_content.waiting_for_input is True diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/live/test_send_client_content.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/live/test_send_client_content.py new file mode 100644 index 0000000000000000000000000000000000000000..770e1c46d57bc76dad82fb8c486796c81a3887da --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/live/test_send_client_content.py @@ -0,0 +1,147 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for live.py.""" +import base64 +import json +from unittest import mock + +import pytest +from websockets import client + +from .. import pytest_helper +from ... import client as gl_client +from ... import live +from ... import types + + +def mock_api_client(vertexai=False): + api_client = mock.MagicMock(spec=gl_client.BaseApiClient) + api_client.api_key = 'TEST_API_KEY' + api_client._host = lambda: 'test_host' + api_client._http_options = {'headers': {}} # Ensure headers exist + api_client.vertexai = vertexai + return api_client + + +@pytest.fixture +def mock_websocket(): + websocket = mock.AsyncMock(spec=client.ClientConnection) + websocket.send = mock.AsyncMock() + websocket.recv = mock.AsyncMock( + return_value='{"serverContent": {"turnComplete": true}}' + ) # Default response + websocket.close = mock.AsyncMock() + return websocket + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_send_content_dict(mock_websocket, vertexai): + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + content = [{'parts': [{'text': 'test'}]}] + + await session.send_client_content(turns=content) + mock_websocket.send.assert_called_once() + sent_data = json.loads(mock_websocket.send.call_args[0][0]) + assert 'client_content' in sent_data + + assert sent_data['client_content']['turns'][0]['parts'][0]['text'] == 'test' + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_send_content_dict_list(mock_websocket, vertexai): + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + content = [{'parts': [{'text': 'test'}]}] + + await session.send_client_content(turns=content) + mock_websocket.send.assert_called_once() + sent_data = json.loads(mock_websocket.send.call_args[0][0]) + assert 'client_content' in sent_data + + assert sent_data['client_content']['turns'][0]['parts'][0]['text'] == 'test' + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_send_content_content(mock_websocket, vertexai): + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + content = types.Content.model_validate({'parts': [{'text': 'test'}]}) + + await session.send_client_content(turns=content) + mock_websocket.send.assert_called_once() + sent_data = json.loads(mock_websocket.send.call_args[0][0]) + assert 'client_content' in sent_data + + assert sent_data['client_content']['turns'][0]['parts'][0]['text'] == 'test' + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_send_content_with_blob(mock_websocket, vertexai): + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + content = types.Content.model_validate( + {'parts': [{'inline_data': {'data': b'test'}}]} + ) + + await session.send_client_content(turns=content) + mock_websocket.send.assert_called_once() + sent_data = json.loads(mock_websocket.send.call_args[0][0]) + assert 'client_content' in sent_data + + assert pytest_helper.get_value_ignore_key_case( + sent_data['client_content']['turns'][0]['parts'][0], 'inline_data') == { + 'data': base64.b64encode(b'test').decode() + } + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_send_client_content_turn_complete_false( + mock_websocket, vertexai +): + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + + await session.send_client_content(turn_complete=False) + mock_websocket.send.assert_called_once() + sent_data = json.loads(mock_websocket.send.call_args[0][0]) + assert 'client_content' in sent_data + assert sent_data['client_content']['turnComplete'] == False + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_send_client_content_empty( + mock_websocket, vertexai +): + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + + await session.send_client_content() + mock_websocket.send.assert_called_once() + sent_data = json.loads(mock_websocket.send.call_args[0][0]) + assert 'client_content' in sent_data + assert sent_data['client_content']['turnComplete'] == True diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/live/test_send_realtime_input.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/live/test_send_realtime_input.py new file mode 100644 index 0000000000000000000000000000000000000000..59cd3f5030cfbb2c5a33ae49e230f51fe5b291a1 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/live/test_send_realtime_input.py @@ -0,0 +1,268 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for live.py.""" +import json +import os +from unittest import mock + +import pytest +from websockets import client + +from ... import client as gl_client +from ... import live +from ... import types +from .. import pytest_helper + + +IMAGE_FILE_PATH = os.path.abspath( + os.path.join(os.path.dirname(__file__), '../data/google.jpg') +) + + +def mock_api_client(vertexai=False): + api_client = mock.MagicMock(spec=gl_client.BaseApiClient) + api_client.api_key = 'TEST_API_KEY' + api_client._host = lambda: 'test_host' + api_client._http_options = {'headers': {}} # Ensure headers exist + api_client.vertexai = vertexai + api_client._api_client = api_client + return api_client + + +@pytest.fixture +def mock_websocket(): + websocket = mock.AsyncMock(spec=client.ClientConnection) + websocket.send = mock.AsyncMock() + websocket.recv = mock.AsyncMock( + return_value='{"serverContent": {"turnComplete": true}}' + ) # Default response + websocket.close = mock.AsyncMock() + return websocket + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_send_media_blob_dict(mock_websocket, vertexai): + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + content = {'data': bytes([0, 0, 0, 0, 0, 0]), 'mime_type': 'audio/pcm'} + + await session.send_realtime_input(media=content) + mock_websocket.send.assert_called_once() + sent_data = json.loads(mock_websocket.send.call_args[0][0]) + assert 'realtime_input' in sent_data + + assert sent_data['realtime_input']['mediaChunks'][0]['data'] == 'AAAAAAAA' + assert pytest_helper.get_value_ignore_key_case( + sent_data['realtime_input']['mediaChunks'][0], 'mime_type' + ) == 'audio/pcm' + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_send_media_blob(mock_websocket, vertexai): + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + content = types.Blob(data=bytes([0, 0, 0, 0, 0, 0]), mime_type='audio/pcm') + + await session.send_realtime_input(media=content) + mock_websocket.send.assert_called_once() + sent_data = json.loads(mock_websocket.send.call_args[0][0]) + assert 'realtime_input' in sent_data + + assert sent_data['realtime_input']['mediaChunks'][0]['data'] == 'AAAAAAAA' + assert pytest_helper.get_value_ignore_key_case( + sent_data['realtime_input']['mediaChunks'][0], 'mime_type' + ) == 'audio/pcm' + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_send_media_image(mock_websocket, vertexai, image_jpeg): + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + + await session.send_realtime_input(media=image_jpeg) + mock_websocket.send.assert_called_once() + sent_data = json.loads(mock_websocket.send.call_args[0][0]) + assert 'realtime_input' in sent_data + + assert pytest_helper.get_value_ignore_key_case( + sent_data['realtime_input']['mediaChunks'][0], 'mime_type' + ) == 'image/jpeg' + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.parametrize( + 'content', + [ + {'data': bytes([0, 0, 0, 0, 0, 0]), 'mime_type': 'audio/pcm'}, + types.Blob(data=bytes([0, 0, 0, 0, 0, 0]), mime_type='audio/pcm'), + ], +) +@pytest.mark.asyncio +async def test_send_audio(mock_websocket, vertexai, content): + api_client = mock_api_client(vertexai=vertexai) + session = live.AsyncSession(api_client=api_client, websocket=mock_websocket) + + await session.send_realtime_input(audio=content) + mock_websocket.send.assert_called_once() + sent_data = json.loads(mock_websocket.send.call_args[0][0]) + assert 'realtime_input' in sent_data + + assert sent_data['realtime_input']['audio']['data'] == 'AAAAAAAA' + assert pytest_helper.get_value_ignore_key_case( + sent_data['realtime_input']['audio'], 'mime_type' + ) == 'audio/pcm' + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_send_bad_audio_blob(mock_websocket, vertexai): + api_client = mock_api_client(vertexai=vertexai) + session = live.AsyncSession(api_client=api_client, websocket=mock_websocket) + content = types.Blob(data=bytes([0, 0, 0, 0, 0, 0]), mime_type='image/png') + + with pytest.raises(ValueError, match='.*Unsupported mime type.*'): + await session.send_realtime_input(audio=content) + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_send_bad_video_blob(mock_websocket, vertexai): + api_client = mock_api_client(vertexai=vertexai) + session = live.AsyncSession(api_client=api_client, websocket=mock_websocket) + content = types.Blob(data=bytes([0, 0, 0, 0, 0, 0]), mime_type='audio/pcm') + + with pytest.raises(ValueError, match='.*Unsupported mime type.*'): + await session.send_realtime_input(video=content) + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_send_audio_stream_end(mock_websocket, vertexai): + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + + await session.send_realtime_input(audio_stream_end=True) + mock_websocket.send.assert_called_once() + sent_data = json.loads(mock_websocket.send.call_args[0][0]) + assert 'realtime_input' in sent_data + + assert sent_data['realtime_input']['audioStreamEnd'] == True + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.parametrize( + 'content', + [ + {'data': bytes([0, 0, 0, 0, 0, 0]), 'mime_type': 'image/png'}, + types.Blob(data=bytes([0, 0, 0, 0, 0, 0]), mime_type='image/png'), + ], +) +@pytest.mark.asyncio +async def test_send_video(mock_websocket, vertexai, content): + api_client = mock_api_client(vertexai=vertexai) + session = live.AsyncSession(api_client=api_client, websocket=mock_websocket) + + await session.send_realtime_input(video=content) + mock_websocket.send.assert_called_once() + sent_data = json.loads(mock_websocket.send.call_args[0][0]) + assert 'realtime_input' in sent_data + + assert sent_data['realtime_input']['video']['data'] == 'AAAAAAAA' + assert pytest_helper.get_value_ignore_key_case( + sent_data['realtime_input']['video'], 'mime_type' + ) == 'image/png' + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_send_video_image(mock_websocket, vertexai, image_jpeg): + api_client = mock_api_client(vertexai=vertexai) + session = live.AsyncSession(api_client=api_client, websocket=mock_websocket) + + await session.send_realtime_input(video=image_jpeg) + mock_websocket.send.assert_called_once() + sent_data = json.loads(mock_websocket.send.call_args[0][0]) + assert 'realtime_input' in sent_data + + assert pytest_helper.get_value_ignore_key_case( + sent_data['realtime_input']['video'], 'mime_type' + ) == 'image/jpeg' + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_send_text(mock_websocket, vertexai): + api_client = mock_api_client(vertexai=vertexai) + session = live.AsyncSession(api_client=api_client, websocket=mock_websocket) + + await session.send_realtime_input(text='Hello?') + mock_websocket.send.assert_called_once() + sent_data = json.loads(mock_websocket.send.call_args[0][0]) + assert 'realtime_input' in sent_data + + assert sent_data['realtime_input']['text'] == 'Hello?' + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.parametrize('activity', [{}, types.ActivityStart()]) +@pytest.mark.asyncio +async def test_send_activity_start(mock_websocket, vertexai, activity): + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + + await session.send_realtime_input(activity_start=activity) + mock_websocket.send.assert_called_once() + sent_data = json.loads(mock_websocket.send.call_args[0][0]) + assert 'realtime_input' in sent_data + + assert sent_data['realtime_input']['activityStart'] == {} + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.parametrize('activity', [{}, types.ActivityEnd()]) +@pytest.mark.asyncio +async def test_send_activity_end(mock_websocket, vertexai, activity): + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + + await session.send_realtime_input(activity_end=activity) + mock_websocket.send.assert_called_once() + sent_data = json.loads(mock_websocket.send.call_args[0][0]) + assert 'realtime_input' in sent_data + + assert sent_data['realtime_input']['activityEnd'] == {} + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_send_multiple_args(mock_websocket, vertexai): + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + with pytest.raises(ValueError, match='.*one argument.*'): + await session.send_realtime_input( + text='Hello?', activity_start=types.ActivityStart() + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/live/test_send_tool_response.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/live/test_send_tool_response.py new file mode 100644 index 0000000000000000000000000000000000000000..cc1d78d36bfe5f9e96c4fad76416f22f087c95ec --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/live/test_send_tool_response.py @@ -0,0 +1,222 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for live.py.""" + +import contextlib +import json +from unittest import mock + +import pytest +from websockets import client + +from .. import pytest_helper +from ... import client as gl_client +from ... import live +from ... import types + + +def exception_if_mldev(vertexai, exception_type: type[Exception]): + if vertexai: + return contextlib.nullcontext() + else: + return pytest.raises(exception_type) + + +def mock_api_client(vertexai=False): + api_client = mock.MagicMock(spec=gl_client.BaseApiClient) + api_client.api_key = 'TEST_API_KEY' + api_client._host = lambda: 'test_host' + api_client._http_options = {'headers': {}} # Ensure headers exist + api_client.vertexai = vertexai + api_client._api_client = api_client + return api_client + + +@pytest.fixture +def mock_websocket(): + websocket = mock.AsyncMock(spec=client.ClientConnection) + websocket.send = mock.AsyncMock() + websocket.recv = mock.AsyncMock( + return_value='{"serverContent": {"turnComplete": true}}' + ) # Default response + websocket.close = mock.AsyncMock() + return websocket + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_function_response_dict(mock_websocket, vertexai): + api_client = mock_api_client(vertexai=vertexai) + session = live.AsyncSession( + api_client=api_client, websocket=mock_websocket + ) + + input = { + 'name': 'get_current_weather', + 'response': {'temperature': 14.5, 'unit': 'C'}, + } + + if not vertexai: + input['id'] = 'some-id' + + await session.send_tool_response(function_responses=input) + + mock_websocket.send.assert_called_once() + sent_data = json.loads(mock_websocket.send.call_args[0][0]) + assert 'tool_response' in sent_data + + assert ( + sent_data['tool_response']['functionResponses'][0]['name'] + == 'get_current_weather' + ) + assert ( + sent_data['tool_response']['functionResponses'][0]['response'][ + 'temperature' + ] + == 14.5 + ) + assert ( + sent_data['tool_response']['functionResponses'][0]['response']['unit'] + == 'C' + ) + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_function_response(mock_websocket, vertexai): + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + + input = types.FunctionResponse( + name='get_current_weather', + response={ + 'temperature': 14.5, + 'unit': 'C', + 'user_name': 'test_user_name', + 'userEmail': 'test_user_email', + }, + ) + if not vertexai: + input.id = 'some-id' + + await session.send_tool_response(function_responses=input) + mock_websocket.send.assert_called_once() + sent_data = json.loads(mock_websocket.send.call_args[0][0]) + assert 'tool_response' in sent_data + + assert ( + sent_data['tool_response']['functionResponses'][0]['name'] + == 'get_current_weather' + ) + assert ( + sent_data['tool_response']['functionResponses'][0]['response'] + == input.response + ) + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_function_response_scheduling(mock_websocket, vertexai): + api_client = mock_api_client(vertexai=vertexai) + session = live.AsyncSession(api_client=api_client, websocket=mock_websocket) + + input = types.FunctionResponse( + name='get_current_weather', + response={'temperature': 14.5, 'unit': 'C'}, + will_continue=True, + scheduling=types.FunctionResponseScheduling.SILENT, + ) + if not vertexai: + input.id = 'some-id' + + await session.send_tool_response(function_responses=input) + + mock_websocket.send.assert_called_once() + sent_data = json.loads(mock_websocket.send.call_args[0][0]) + assert 'tool_response' in sent_data + + assert pytest_helper.get_value_ignore_key_case( + sent_data['tool_response']['functionResponses'][0], 'will_continue' + ) + assert ( + sent_data['tool_response']['functionResponses'][0]['scheduling'] + == 'SILENT' + ) + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_function_response_list(mock_websocket, vertexai): + session = live.AsyncSession( + api_client=mock_api_client(vertexai=vertexai), websocket=mock_websocket + ) + + input1 = { + 'name': 'get_current_weather', + 'response': {'temperature': 14.5, 'unit': 'C'}, + } + input2 = { + 'name': 'get_current_weather', + 'response': {'temperature': 99.9, 'unit': 'C'}, + } + + if not vertexai: + input1['id'] = '1' + input2['id'] = '2' + + await session.send_tool_response(function_responses=[input1, input2]) + mock_websocket.send.assert_called_once() + sent_data = json.loads(mock_websocket.send.call_args[0][0]) + assert 'tool_response' in sent_data + + assert len(sent_data['tool_response']['functionResponses']) == 2 + assert ( + sent_data['tool_response']['functionResponses'][0]['response'][ + 'temperature' + ] + == 14.5 + ) + assert ( + sent_data['tool_response']['functionResponses'][1]['response'][ + 'temperature' + ] + == 99.9 + ) + + +@pytest.mark.parametrize('vertexai', [True, False]) +@pytest.mark.asyncio +async def test_missing_id(mock_websocket, vertexai): + api_client = mock_api_client(vertexai=vertexai) + session = live.AsyncSession( + api_client=api_client, websocket=mock_websocket + ) + + input1 = { + 'name': 'get_current_weather', + 'response': {'temperature': 14.5, 'unit': 'C'}, + 'id': '1', + } + input2 = { + 'name': 'get_current_weather', + 'response': {'temperature': 99.9, 'unit': 'C'}, + } + + if not vertexai: + with pytest.raises(ValueError, match=".*must have.*"): + await session.send_tool_response(function_responses=[input1, input2]) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/local_tokenizer/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/local_tokenizer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8bd99f047360605cfcf4eb00626c7ebf204a4da2 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/local_tokenizer/__init__.py @@ -0,0 +1,17 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for the Google GenAI SDK's local_tokenizer module.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/local_tokenizer/test_local_tokenizer.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/local_tokenizer/test_local_tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..ca337b5e8ea959a94fcb7228d9af6352c04b1d2e --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/local_tokenizer/test_local_tokenizer.py @@ -0,0 +1,343 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +import unittest +from unittest.mock import MagicMock, patch + +from sentencepiece import sentencepiece_model_pb2 + +from ... import local_tokenizer +from ... import types + + +class TestLocalTokenizer(unittest.TestCase): + + def setUp(self): + # This setup will be used by all tests + self.mock_load_model_proto = patch( + 'genai._local_tokenizer_loader.load_model_proto' + ).start() + self.mock_get_sentencepiece = patch( + 'genai._local_tokenizer_loader.get_sentencepiece' + ).start() + + self.mock_load_model_proto.return_value = MagicMock() + self.mock_tokenizer = MagicMock() + self.mock_get_sentencepiece.return_value = self.mock_tokenizer + + self.tokenizer = local_tokenizer.LocalTokenizer(model_name='gemini-3-pro-preview') + + def tearDown(self): + patch.stopall() + + def test_count_tokens_simple_string(self): + self.mock_tokenizer.encode.return_value = [[1, 2, 3]] + result = self.tokenizer.count_tokens('Hello world') + self.assertEqual(result.total_tokens, 3) + self.mock_tokenizer.encode.assert_called_once_with(['Hello world']) + + def test_count_tokens_list_of_strings(self): + self.mock_tokenizer.encode.return_value = [[1, 2], [3]] + result = self.tokenizer.count_tokens(['Hello', 'world']) + self.assertEqual(result.total_tokens, 3) + self.mock_tokenizer.encode.assert_called_once_with(['Hello', 'world']) + + def test_count_tokens_with_content_object(self): + self.mock_tokenizer.encode.return_value = [[1, 2, 3]] + content = types.Content(parts=[types.Part(text='Hello world')]) + result = self.tokenizer.count_tokens(content) + self.assertEqual(result.total_tokens, 3) + self.mock_tokenizer.encode.assert_called_once_with(['Hello world']) + + def test_count_tokens_with_chat_history(self): + self.mock_tokenizer.encode.return_value = [[1, 2], [3, 4, 5]] + history = [ + types.Content(role='user', parts=[types.Part(text='Hello')]), + types.Content(role='model', parts=[types.Part(text='Hi there!')]), + ] + result = self.tokenizer.count_tokens(history) + self.assertEqual(result.total_tokens, 5) + self.mock_tokenizer.encode.assert_called_once_with(['Hello', 'Hi there!']) + + def test_count_tokens_with_tools(self): + self.mock_tokenizer.encode.return_value = [ + [1], + [1, 2], + [1, 2, 3], + [1, 2, 3, 4], + [1, 2, 3, 4, 5], + [1, 2, 3, 4, 5, 6], + ] + tool = types.Tool( + function_declarations=[ + types.FunctionDeclaration( + name='get_weather', + description='Get the weather for a location', + parameters=types.Schema( + type=types.Type.OBJECT, + properties={ + 'location': types.Schema( + type=types.Type.STRING, description='The location' + ) + }, + required=['location'], + ), + ) + ] + ) + config = types.CountTokensConfig(tools=[tool]) + result = self.tokenizer.count_tokens( + 'What is the weather in Boston?', config=config + ) + self.assertEqual(result.total_tokens, 21) + self.mock_tokenizer.encode.assert_called_once_with([ + 'What is the weather in Boston?', + 'get_weather', + 'Get the weather for a location', + 'location', + 'location', + 'The location', + ]) + + def test_count_tokens_with_function_call(self): + self.mock_tokenizer.encode.return_value = [[1, 2], [3], [4, 5]] + content = types.Content( + role='model', + parts=[ + types.Part( + function_call=types.FunctionCall( + name='get_weather', args={'location': 'Boston'} + ) + ) + ], + ) + result = self.tokenizer.count_tokens(content) + self.assertEqual(result.total_tokens, 5) + self.mock_tokenizer.encode.assert_called_once_with( + ['get_weather', 'location', 'Boston'] + ) + + def test_count_tokens_with_function_response(self): + self.mock_tokenizer.encode.return_value = [[1, 2], [3], [4, 5]] + content = types.Content( + role='user', + parts=[ + types.Part( + function_response=types.FunctionResponse( + name='get_weather', response={'weather': 'sunny'} + ) + ) + ], + ) + result = self.tokenizer.count_tokens(content) + self.assertEqual(result.total_tokens, 5) + self.mock_tokenizer.encode.assert_called_once_with( + ['get_weather', 'weather', 'sunny'] + ) + + def test_count_tokens_with_unsupported_content(self): + with self.assertRaises(ValueError): + self.tokenizer.count_tokens( + [ + types.Content( + parts=[ + types.Part( + inline_data=types.Blob( + data=b'test', mime_type='image/png' + ) + ) + ] + ) + ] + ) + + def test_count_tokens_with_system_instruction(self): + self.mock_tokenizer.encode.return_value = [[1, 2, 3], [4, 5]] + config = types.CountTokensConfig( + system_instruction=types.Content( + parts=[types.Part(text='You are a helpful assistant.')] + ) + ) + result = self.tokenizer.count_tokens('Hello', config=config) + self.assertEqual(result.total_tokens, 5) + self.mock_tokenizer.encode.assert_called_once_with( + ['Hello', 'You are a helpful assistant.'] + ) + + def test_count_tokens_with_response_schema(self): + self.mock_tokenizer.encode.return_value = [ + [1], + [1, 2], + [1, 2, 3], + [1, 2, 3, 4], + [1, 2, 3, 4, 5], + ] + schema = types.Schema( + type=types.Type.OBJECT, + format='schema_format', + description='Recipe schema', + enum=['schema_enum1', 'schema_enum2'], + properties={ + 'recipe_name': types.Schema( + type=types.Type.STRING, + description='Name of the recipe', + ) + }, + items=types.Schema( + type=types.Type.STRING, + description='Item in the recipe', + ), + example={ + 'recipe_example': types.Schema( + type=types.Type.STRING, + description='example in the recipe', + ) + }, + required=['recipe_name'], + ) + config = types.CountTokensConfig( + generation_config=types.GenerationConfig(response_schema=schema) + ) + result = self.tokenizer.count_tokens( + 'Generate a recipe for chocolate chip cookies.', config=config + ) + self.assertEqual(result.total_tokens, 15) + self.mock_tokenizer.encode.assert_called_once_with([ + 'Generate a recipe for chocolate chip cookies.', + 'schema_format', + 'Recipe schema', + 'schema_enum1', + 'schema_enum2', + 'recipe_name', + 'Item in the recipe', + 'recipe_name', + 'Name of the recipe', + 'recipe_example', + ]) + + def test_count_tokens_with_unsupported_fields_logs_warning(self): + self.mock_tokenizer.encode.return_value = [[1, 2, 3]] + content_with_unsupported = types.Content( + role='user', + parts=[ + types.Part(text='hello'), + # executable_code is not supported by _TextsAccumulator + types.Part( + executable_code=types.ExecutableCode( + language='PYTHON', code='print(1)' + ) + ), + ], + ) + with self.assertLogs('google_genai.local_tokenizer', level='WARNING') as cm: + self.tokenizer.count_tokens(content_with_unsupported) + self.assertIn( + 'Content contains unsupported types for token counting', cm.output[0] + ) + + def test_compute_tokens_simple_string(self): + mock_spt = MagicMock() + mock_spt.pieces = [ + MagicMock(id=1, piece='He'), + MagicMock(id=2, piece='llo'), + MagicMock(id=3, piece=' world'), + ] + self.mock_tokenizer.EncodeAsImmutableProto.return_value = [mock_spt] + result = self.tokenizer.compute_tokens('Hello world') + self.assertEqual(len(result.tokens_info), 1) + self.assertEqual(result.tokens_info[0].token_ids, [1, 2, 3]) + self.assertEqual(result.tokens_info[0].tokens, [b'He', b'llo', b' world']) + self.assertEqual(result.tokens_info[0].role, 'user') + self.mock_tokenizer.EncodeAsImmutableProto.assert_called_once_with( + ['Hello world'] + ) + + def test_compute_tokens_with_chat_history(self): + mock_spt1 = MagicMock() + mock_spt1.pieces = [MagicMock(id=1, piece='Hello')] + mock_spt2 = MagicMock() + mock_spt2.pieces = [ + MagicMock(id=2, piece='Hi'), + MagicMock(id=3, piece=' there!'), + ] + self.mock_tokenizer.EncodeAsImmutableProto.return_value = [ + mock_spt1, + mock_spt2, + ] + history = [ + types.Content(role='user', parts=[types.Part(text='Hello')]), + types.Content(role='model', parts=[types.Part(text='Hi there!')]), + ] + result = self.tokenizer.compute_tokens(history) + self.assertEqual(len(result.tokens_info), 2) + self.assertEqual(result.tokens_info[0].token_ids, [1]) + self.assertEqual(result.tokens_info[0].tokens, [b'Hello']) + self.assertEqual(result.tokens_info[0].role, 'user') + self.assertEqual(result.tokens_info[1].token_ids, [2, 3]) + self.assertEqual(result.tokens_info[1].tokens, [b'Hi', b' there!']) + self.assertEqual(result.tokens_info[1].role, 'model') + self.mock_tokenizer.EncodeAsImmutableProto.assert_called_once_with( + ['Hello', 'Hi there!'] + ) + + def test_compute_tokens_with_byte_tokens(self): + mock_spt = MagicMock() + mock_spt.pieces = [ + MagicMock(id=1, piece='<0x48>'), + MagicMock(id=2, piece='ello'), + ] + self.mock_tokenizer.EncodeAsImmutableProto.return_value = [mock_spt] + self.tokenizer._model_proto = sentencepiece_model_pb2.ModelProto( + pieces=[ + sentencepiece_model_pb2.ModelProto.SentencePiece(), + sentencepiece_model_pb2.ModelProto.SentencePiece( + type=sentencepiece_model_pb2.ModelProto.SentencePiece.Type.BYTE + ), + sentencepiece_model_pb2.ModelProto.SentencePiece( + type=sentencepiece_model_pb2.ModelProto.SentencePiece.Type.NORMAL + ), + ] + ) + result = self.tokenizer.compute_tokens('Hello') + self.assertEqual(len(result.tokens_info), 1) + self.assertEqual(result.tokens_info[0].token_ids, [1, 2]) + self.assertEqual(result.tokens_info[0].tokens, [b'H', b'ello']) + self.mock_tokenizer.EncodeAsImmutableProto.assert_called_once_with( + ['Hello'] + ) + + +class TestParseHexByte(unittest.TestCase): + + def test_valid_hex(self): + self.assertEqual(local_tokenizer._parse_hex_byte('<0x41>'), 65) + self.assertEqual(local_tokenizer._parse_hex_byte('<0xFF>'), 255) + self.assertEqual(local_tokenizer._parse_hex_byte('<0x00>'), 0) + + def test_invalid_length(self): + with self.assertRaisesRegex(ValueError, 'Invalid byte length'): + local_tokenizer._parse_hex_byte('<0x41') + with self.assertRaisesRegex(ValueError, 'Invalid byte length'): + local_tokenizer._parse_hex_byte('<0x411>') + + def test_invalid_format(self): + with self.assertRaisesRegex(ValueError, 'Invalid byte format'): + local_tokenizer._parse_hex_byte(' 0x41>') + with self.assertRaisesRegex(ValueError, 'Invalid byte format'): + local_tokenizer._parse_hex_byte('<0x41 ') + + def test_invalid_hex_value(self): + with self.assertRaisesRegex(ValueError, 'Invalid hex value'): + local_tokenizer._parse_hex_byte('<0xFG>') diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/local_tokenizer/test_local_tokenizer_loader.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/local_tokenizer/test_local_tokenizer_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..09cd63f425a4c2eaf94a3c53d2af74dc75f10e4b --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/local_tokenizer/test_local_tokenizer_loader.py @@ -0,0 +1,235 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +import unittest +from unittest.mock import MagicMock, mock_open, patch + +import sentencepiece as spm +from sentencepiece import sentencepiece_model_pb2 + +from ... import _local_tokenizer_loader as loader + +# A minimal valid sentencepiece model proto +FAKE_MODEL_CONTENT = sentencepiece_model_pb2.ModelProto( + pieces=[ + sentencepiece_model_pb2.ModelProto.SentencePiece( + piece="", + score=0, + type=sentencepiece_model_pb2.ModelProto.SentencePiece.Type.UNKNOWN, + ), + sentencepiece_model_pb2.ModelProto.SentencePiece( + piece="", + score=0, + type=sentencepiece_model_pb2.ModelProto.SentencePiece.Type.CONTROL, + ), + sentencepiece_model_pb2.ModelProto.SentencePiece( + piece="", + score=0, + type=sentencepiece_model_pb2.ModelProto.SentencePiece.Type.CONTROL, + ), + sentencepiece_model_pb2.ModelProto.SentencePiece( + piece="a", + score=0, + type=sentencepiece_model_pb2.ModelProto.SentencePiece.Type.NORMAL, + ), + ] +).SerializeToString() + +GEMMA2_HASH = "61a7b147390c64585d6c3543dd6fc636906c9af3865a5548f27f31aee1d4c8e2" + + +class TestGetTokenizerName(unittest.TestCase): + + def test_get_tokenizer_name_success(self): + self.assertEqual(loader.get_tokenizer_name("gemini-2.5-pro"), "gemma3") + self.assertEqual( + loader.get_tokenizer_name("gemini-2.5-pro-preview-06-05"), "gemma3" + ) + + def test_get_tokenizer_name_unsupported(self): + with self.assertRaisesRegex( + ValueError, "Model unsupported-model is not supported" + ): + loader.get_tokenizer_name("unsupported-model") + + +@patch("genai._local_tokenizer_loader.os.rename") +@patch("genai._local_tokenizer_loader.os.makedirs") +@patch("genai._local_tokenizer_loader.os.remove") +@patch("genai._local_tokenizer_loader.open", new_callable=mock_open) +@patch("genai._local_tokenizer_loader.os.path.exists") +@patch("genai._local_tokenizer_loader.requests.get") +@patch("genai._local_tokenizer_loader.hashlib.sha256") +class TestLoaderFunctions(unittest.TestCase): + + def setUp(self): + # Clear caches before each test + loader.load_model_proto.cache_clear() + loader.get_sentencepiece.cache_clear() + # Patch tempfile.gettempdir to control cache location + self.tempdir_patcher = patch( + "tempfile.gettempdir", return_value="/tmp/fake_temp_dir" + ) + self.mock_tempdir = self.tempdir_patcher.start() + + def tearDown(self): + self.tempdir_patcher.stop() + + def _setup_get_mock(self, mock_get): + mock_response = MagicMock() + mock_response.content = FAKE_MODEL_CONTENT + mock_response.raise_for_status.return_value = None + mock_get.return_value = mock_response + + def test_load_model_proto_from_url( + self, + mock_sha256, + mock_get, + mock_exists, + mock_open_func, + mock_remove, + mock_makedirs, + mock_rename, + ): + mock_exists.return_value = False # Don't use cache + self._setup_get_mock(mock_get) + mock_sha256.return_value.hexdigest.return_value = GEMMA2_HASH + + proto = loader.load_model_proto("gemma2") + + self.assertIsInstance(proto, sentencepiece_model_pb2.ModelProto) + self.assertEqual(len(proto.pieces), 4) + mock_get.assert_called_once() + mock_makedirs.assert_called_once() + mock_open_func.assert_called() + mock_rename.assert_called_once() + + def test_load_model_proto_from_cache( + self, + mock_sha256, + mock_get, + mock_exists, + mock_open_func, + mock_remove, + mock_makedirs, + mock_rename, + ): + mock_exists.return_value = True # Use cache + mock_open_func.return_value.read.return_value = FAKE_MODEL_CONTENT + mock_sha256.return_value.hexdigest.return_value = GEMMA2_HASH + + proto = loader.load_model_proto("gemma2") + + self.assertIsInstance(proto, sentencepiece_model_pb2.ModelProto) + mock_get.assert_not_called() + + def test_load_model_proto_corrupted_cache( + self, + mock_sha256, + mock_get, + mock_exists, + mock_open_func, + mock_remove, + mock_makedirs, + mock_rename, + ): + mock_exists.return_value = True # Use cache initially + self._setup_get_mock(mock_get) + mock_open_func.return_value.__enter__.return_value.read.return_value = ( + b"corrupted" + ) + + # First hash for corrupted cache, second for good download + mock_sha256.side_effect = [ + MagicMock(hexdigest=MagicMock(return_value="wrong_hash")), + MagicMock(hexdigest=MagicMock(return_value=GEMMA2_HASH)), + ] + + proto = loader.load_model_proto("gemma2") + + self.assertIsInstance(proto, sentencepiece_model_pb2.ModelProto) + mock_remove.assert_called_once() + mock_get.assert_called_once() + + def test_load_model_proto_bad_hash_from_url( + self, + mock_sha256, + mock_get, + mock_exists, + mock_open_func, + mock_remove, + mock_makedirs, + mock_rename, + ): + mock_exists.return_value = False + self._setup_get_mock(mock_get) + mock_sha256.return_value.hexdigest.return_value = "wrong_hash" + + with self.assertRaisesRegex( + ValueError, "Downloaded model file is corrupted" + ): + loader.load_model_proto("gemma2") + + def test_load_model_proto_unsupported(self, *args): + with self.assertRaisesRegex( + ValueError, "Tokenizer unsupported is not supported" + ): + loader.load_model_proto("unsupported") + + def test_get_sentencepiece_success( + self, + mock_sha256, + mock_get, + mock_exists, + mock_open_func, + mock_remove, + mock_makedirs, + mock_rename, + ): + mock_exists.return_value = False + self._setup_get_mock(mock_get) + mock_sha256.return_value.hexdigest.return_value = GEMMA2_HASH + + processor = loader.get_sentencepiece("gemma2") + + self.assertIsInstance(processor, spm.SentencePieceProcessor) + mock_get.assert_called_once() + + def test_get_sentencepiece_unsupported(self, *args): + with self.assertRaisesRegex( + ValueError, "Tokenizer unsupported is not supported" + ): + loader.get_sentencepiece("unsupported") + + def test_get_sentencepiece_caching( + self, + mock_sha256, + mock_get, + mock_exists, + mock_open_func, + mock_remove, + mock_makedirs, + mock_rename, + ): + mock_exists.return_value = False + self._setup_get_mock(mock_get) + mock_sha256.return_value.hexdigest.return_value = GEMMA2_HASH + + # Call twice + loader.get_sentencepiece("gemma2") + loader.get_sentencepiece("gemma2") + + # Should only be loaded once due to lru_cache + mock_get.assert_called_once() diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/mcp/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/mcp/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..17da203ae500f4c08f30ce70512dda4129a3f488 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/mcp/__init__.py @@ -0,0 +1,17 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for the Google GenAI SDK's _mcp_utils module.""" \ No newline at end of file diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/mcp/test_has_mcp_tool_usage.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/mcp/test_has_mcp_tool_usage.py new file mode 100644 index 0000000000000000000000000000000000000000..12d8c903a9c4e69678868c178c85095b4d5b0659 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/mcp/test_has_mcp_tool_usage.py @@ -0,0 +1,89 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +import typing +from typing import Any + +from ... import _mcp_utils +from ... import types + +if typing.TYPE_CHECKING: + from mcp.types import Tool as McpTool + from mcp import ClientSession as McpClientSession +else: + McpTool: typing.Type = Any + McpClientSession: typing.Type = Any + try: + from mcp.types import Tool as McpTool + from mcp import ClientSession as McpClientSession + except ImportError: + McpTool = None + McpClientSession = None + + +def test_mcp_tools(): + """Test whether the list of tools contains any MCP tools.""" + if McpTool is None: + return + mcp_tools = [ + McpTool( + name='tool', + description='tool-description', + inputSchema={ + 'type': 'OBJECT', + 'properties': { + 'key1': {'type': 'STRING'}, + 'key2': {'type': 'NUMBER'}, + }, + }, + ), + ] + assert _mcp_utils.has_mcp_tool_usage(mcp_tools) + + +def test_mcp_client_session(): + """Test whether the list of tools contains any MCP tools.""" + + class MockMcpClientSession(McpClientSession): + + def __init__(self): + self._read_stream = None + self._write_stream = None + + mcp_tools = [ + MockMcpClientSession(), + ] + assert _mcp_utils.has_mcp_tool_usage(mcp_tools) + + +def test_no_mcp_tools(): + if McpClientSession is None: + return + """Test whether the list of tools contains any MCP tools.""" + gemini_tools = [ + types.Tool( + function_declarations=[ + types.FunctionDeclaration( + name='tool', + description='tool-description', + parameters=types.Schema( + type='OBJECT', + properties={}, + ), + ), + ], + ), + ] + assert not _mcp_utils.has_mcp_tool_usage(gemini_tools) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/mcp/test_mcp_to_gemini_tools.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/mcp/test_mcp_to_gemini_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..62db7d89a0128dc51c080211a9f58ba855dc1c76 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/mcp/test_mcp_to_gemini_tools.py @@ -0,0 +1,191 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +from ... import _mcp_utils +from ... import types + +try: + from mcp import types as mcp_types +except ImportError as e: + import sys + + if sys.version_info < (3, 10): + raise ImportError( + 'MCP Tool requires Python 3.10 or above. Please upgrade your Python' + ' version.' + ) from e + else: + raise e + + +def test_empty_mcp_tools_list(): + """Test conversion of empty MCP tools list to Gemini tools list.""" + result = _mcp_utils.mcp_to_gemini_tools([]) + + assert result == [] + + +def test_unknown_field_conversion(): + """Test conversion of MCP tools with unknown fields to Gemini tools.""" + mcp_tools = [ + mcp_types.Tool( + name='tool', + description='tool-description', + inputSchema={ + 'type': 'object', + 'properties': {}, + 'unknown_field': 'unknownField', + 'unknown_object': {}, + }, + ), + ] + result = _mcp_utils.mcp_to_gemini_tools(mcp_tools) + assert result == [ + types.Tool( + function_declarations=[ + types.FunctionDeclaration( + name='tool', + description='tool-description', + parameters=types.Schema( + type='OBJECT', + properties={}, + ), + ), + ], + ), + ] + + +def test_items_conversion(): + """Test conversion of MCP tools with items to Gemini tools.""" + mcp_tools = [ + mcp_types.Tool( + name='tool', + description='tool-description', + inputSchema={ + 'type': 'array', + 'items': { + 'type': 'object', + 'properties': { + 'key1': { + 'type': 'string', + }, + 'key2': { + 'type': 'number', + }, + }, + }, + }, + ), + ] + result = _mcp_utils.mcp_to_gemini_tools(mcp_tools) + assert result == [ + types.Tool( + function_declarations=[ + types.FunctionDeclaration( + name='tool', + description='tool-description', + parameters=types.Schema( + type='ARRAY', + items=types.Schema( + type='OBJECT', + properties={ + 'key1': types.Schema(type='STRING'), + 'key2': types.Schema(type='NUMBER'), + }, + ), + ), + ), + ], + ), + ] + + +def test_any_of_conversion(): + """Test conversion of MCP tools with any_of to Gemini tools.""" + mcp_tools = [ + mcp_types.Tool( + name='tool', + description='tool-description', + inputSchema={ + 'type': 'object', + 'any_of': [ + { + 'type': 'string', + }, + { + 'type': 'number', + }, + ], + }, + ), + ] + result = _mcp_utils.mcp_to_gemini_tools(mcp_tools) + assert result == [ + types.Tool( + function_declarations=[ + types.FunctionDeclaration( + name='tool', + description='tool-description', + parameters=types.Schema( + type='OBJECT', + any_of=[ + types.Schema(type='STRING'), + types.Schema(type='NUMBER'), + ], + ), + ), + ], + ), + ] + + +def test_properties_conversion(): + """Test conversion of MCP tools with properties to Gemini tools.""" + mcp_tools = [ + mcp_types.Tool( + name='tool', + description='tool-description', + inputSchema={ + 'type': 'object', + 'properties': { + 'key1': { + 'type': 'string', + }, + 'key2': { + 'type': 'number', + }, + }, + }, + ), + ] + result = _mcp_utils.mcp_to_gemini_tools(mcp_tools) + assert result == [ + types.Tool( + function_declarations=[ + types.FunctionDeclaration( + name='tool', + description='tool-description', + parameters=types.Schema( + type='OBJECT', + properties={ + 'key1': types.Schema(type='STRING'), + 'key2': types.Schema(type='NUMBER'), + }, + ), + ), + ], + ), + ] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/mcp/test_parse_config_for_mcp_sessions.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/mcp/test_parse_config_for_mcp_sessions.py new file mode 100644 index 0000000000000000000000000000000000000000..89693bcb8ea5db0d79ae80249aeffe1041ea95f6 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/mcp/test_parse_config_for_mcp_sessions.py @@ -0,0 +1,201 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +import _asyncio +import pytest +from ... import _extra_utils +from ... import types +from ..._adapters import McpToGenAiToolAdapter + +try: + from mcp import types as mcp_types + from mcp import ClientSession as McpClientSession +except ImportError as e: + import sys + + if sys.version_info < (3, 10): + raise ImportError( + 'MCP Tool requires Python 3.10 or above. Please upgrade your Python' + ' version.' + ) from e + else: + raise e + + +@pytest.mark.asyncio +async def test_parse_empty_config_dict(): + """Test conversion of empty GenerateContentConfigDict to parsed config.""" + config = {} + parsed_config, mcp_to_genai_tool_adapters = ( + await _extra_utils.parse_config_for_mcp_sessions(config) + ) + assert parsed_config == None + assert not mcp_to_genai_tool_adapters + + +@pytest.mark.asyncio +async def test_parse_empty_config_object(): + """Test conversion of empty GenerateContentConfig to parsed config.""" + config = types.GenerateContentConfig() + parsed_config, mcp_to_genai_tool_adapters = ( + await _extra_utils.parse_config_for_mcp_sessions(config) + ) + assert config is not parsed_config # config is not modified + assert not mcp_to_genai_tool_adapters + + +@pytest.mark.asyncio +async def test_parse_config_object_with_tools(): + """Test conversion of GenerateContentConfig with tools to parsed config.""" + + class MockMcpClientSession(McpClientSession): + + def __init__(self): + self._read_stream = None + self._write_stream = None + + async def list_tools(self): + return mcp_types.ListToolsResult( + tools=[ + mcp_types.Tool( + name='get_weather', + description='Get the weather in a city.', + inputSchema={ + 'type': 'object', + 'properties': {'location': {'type': 'string'}}, + }, + ), + mcp_types.Tool( + name='get_weather_2', + description='Different tool to get the weather.', + inputSchema={ + 'type': 'object', + 'properties': {'location': {'type': 'string'}}, + }, + ), + ] + ) + + mock_session_instance = MockMcpClientSession() + config = types.GenerateContentConfig(tools=[mock_session_instance]) + parsed_config, mcp_to_genai_tool_adapters = ( + await _extra_utils.parse_config_for_mcp_sessions(config) + ) + assert len(config.tools) == 1 + assert config.tools[0] is mock_session_instance + assert config is not parsed_config # config is not modified + assert len(mcp_to_genai_tool_adapters) == 2 + assert mcp_to_genai_tool_adapters.keys() == { + 'get_weather', + 'get_weather_2', + } + assert isinstance( + mcp_to_genai_tool_adapters['get_weather'], McpToGenAiToolAdapter + ) + assert isinstance( + mcp_to_genai_tool_adapters['get_weather_2'], McpToGenAiToolAdapter + ) + + +@pytest.mark.asyncio +async def test_parse_config_object_with_tools_complex_type(): + """Test conversion of GenerateContentConfig with tools to parsed config.""" + + class MockMcpClientSession(McpClientSession): + + def __init__(self): + self._read_stream = None + self._write_stream = None + self._future = _asyncio.Future() # This object cannot be pickled. + + async def list_tools(self): + return mcp_types.ListToolsResult( + tools=[ + mcp_types.Tool( + name='get_weather', + description='Get the weather in a city.', + inputSchema={ + 'type': 'object', + 'properties': {'location': {'type': 'string'}}, + }, + ), + mcp_types.Tool( + name='get_weather_2', + description='Different tool to get the weather.', + inputSchema={ + 'type': 'object', + 'properties': {'location': {'type': 'string'}}, + }, + ), + ] + ) + + mock_session_instance = MockMcpClientSession() + config = types.GenerateContentConfig(tools=[mock_session_instance]) + parsed_config, mcp_to_genai_tool_adapters = ( + await _extra_utils.parse_config_for_mcp_sessions(config) + ) + assert len(config.tools) == 1 + assert config.tools[0] is mock_session_instance + assert config is not parsed_config # config is not modified + assert len(mcp_to_genai_tool_adapters) == 2 + assert mcp_to_genai_tool_adapters.keys() == { + 'get_weather', + 'get_weather_2', + } + assert isinstance( + mcp_to_genai_tool_adapters['get_weather'], McpToGenAiToolAdapter + ) + assert isinstance( + mcp_to_genai_tool_adapters['get_weather_2'], McpToGenAiToolAdapter + ) + + +@pytest.mark.asyncio +async def test_parse_config_object_with_non_mcp_tools(): + """Test conversion of GenerateContentConfig with regular tools to parsed config.""" + + config = types.GenerateContentConfig( + tools=[ + types.Tool( + function_declarations=[ + {'name': 'tool-1', 'description': 'tool-1-description'} + ] + ), + types.Tool( + function_declarations=[ + {'name': 'tool-2', 'description': 'tool-2-description'} + ] + ), + ] + ) + parsed_config, mcp_to_genai_tool_adapters = ( + await _extra_utils.parse_config_for_mcp_sessions(config) + ) + assert len(config.tools) == 2 + assert config is not parsed_config # config is not modified + assert mcp_to_genai_tool_adapters == {} + assert parsed_config.tools == [ + types.Tool( + function_declarations=[ + {'name': 'tool-1', 'description': 'tool-1-description'} + ] + ), + types.Tool( + function_declarations=[ + {'name': 'tool-2', 'description': 'tool-2-description'} + ] + ), + ] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/mcp/test_parse_config_for_mcp_usage.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/mcp/test_parse_config_for_mcp_usage.py new file mode 100644 index 0000000000000000000000000000000000000000..6c1d690f185c857d036bd1304bc61608a24cd92e --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/mcp/test_parse_config_for_mcp_usage.py @@ -0,0 +1,130 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +import re +import pytest +from ... import _extra_utils +from ... import types +from ..._adapters import McpToGenAiToolAdapter + +try: + from mcp import types as mcp_types + from mcp import ClientSession as McpClientSession +except ImportError as e: + import sys + + if sys.version_info < (3, 10): + raise ImportError( + 'MCP Tool requires Python 3.10 or above. Please upgrade your Python' + ' version.' + ) from e + else: + raise e + + +def test_parse_empty_config_dict(): + """Test conversion of empty GenerateContentConfigDict to parsed config.""" + config = {} + parsed_config = _extra_utils.parse_config_for_mcp_usage(config) + assert parsed_config == None + + +def test_parse_empty_config_object(): + """Test conversion of empty GenerateContentConfig to parsed config.""" + config = types.GenerateContentConfig() + parsed_config = _extra_utils.parse_config_for_mcp_usage(config) + assert config is not parsed_config # config is not modified + + +def test_parse_config_object_with_tools(): + """Test conversion of GenerateContentConfig with tools to parsed config.""" + + class MockMcpClientSession(McpClientSession): + + def __init__(self): + self._read_stream = None + self._write_stream = None + + async def list_tools(self): + return mcp_types.ListToolsResult( + tools=[ + mcp_types.Tool( + name='get_weather', + description='Get the weather in a city.', + inputSchema={ + 'type': 'object', + 'properties': {'location': {'type': 'string'}}, + }, + ), + mcp_types.Tool( + name='get_weather_2', + description='Different tool to get the weather.', + inputSchema={ + 'type': 'object', + 'properties': {'location': {'type': 'string'}}, + }, + ), + ] + ) + + mock_session_instance = MockMcpClientSession() + config = types.GenerateContentConfig(tools=[mock_session_instance]) + parsed_config = _extra_utils.parse_config_for_mcp_usage(config) + assert config.http_options is None + assert config is not parsed_config # config is not modified + assert re.match( + r'mcp_used/\d+\.\d+\.\d+', + parsed_config.http_options.headers['x-goog-api-client'], + ) + + +def test_parse_config_object_with_tools_and_existing_headers(): + """Test conversion of GenerateContentConfig with tools and existing headers to parsed config.""" + + config = types.GenerateContentConfig( + tools=[ + mcp_types.Tool( + name='get_weather', + description='Get the weather in a city.', + inputSchema={ + 'type': 'object', + 'properties': {'location': {'type': 'string'}}, + }, + ), + mcp_types.Tool( + name='get_weather_2', + description='Different tool to get the weather.', + inputSchema={ + 'type': 'object', + 'properties': {'location': {'type': 'string'}}, + }, + ), + ], + http_options=types.HttpOptions( + headers={ + 'x-goog-api-client': 'google-genai-sdk/1.0.0 gl-python/1.0.0' + } + ), + ) + parsed_config = _extra_utils.parse_config_for_mcp_usage(config) + assert not re.match( + r'mcp_used/\d+\.\d+\.\d+', + config.http_options.headers['x-goog-api-client'], + ) + assert config is not parsed_config # config is not modified + assert re.match( + r'google-genai-sdk/1.0.0 gl-python/1.0.0 mcp_used/\d+\.\d+\.\d+', + parsed_config.http_options.headers['x-goog-api-client'], + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/mcp/test_set_mcp_usage_header.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/mcp/test_set_mcp_usage_header.py new file mode 100644 index 0000000000000000000000000000000000000000..5fa846ede0284b91032e78356ede547059af9c99 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/mcp/test_set_mcp_usage_header.py @@ -0,0 +1,72 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +from importlib.metadata import version +import re +import typing +from typing import Any + +from ... import _mcp_utils +from ... import types + +_is_mcp_imported = False +if typing.TYPE_CHECKING: + import mcp + + _is_mcp_imported = True +else: + try: + import mcp + + _is_mcp_imported = True + except ImportError: + _is_mcp_imported = False + + +def test_set_mcp_usage_header_from_empty_dict(): + if not _is_mcp_imported: + return + """Test whether the MCP usage header is set correctly from an empty dict.""" + headers = {} + _mcp_utils.set_mcp_usage_header(headers) + assert re.match(r'mcp_used/\d+\.\d+\.\d+', headers['x-goog-api-client']) + + +def test_set_mcp_usage_header_with_existing_header(): + if not _is_mcp_imported: + return + """Test whether the MCP usage header is set correctly from an existing header.""" + headers = {'x-goog-api-client': 'google-genai-sdk/1.0.0 gl-python/1.0.0'} + _mcp_utils.set_mcp_usage_header(headers) + assert re.match( + r'google-genai-sdk/1.0.0 gl-python/1.0.0 mcp_used/\d+\.\d+\.\d+', + headers['x-goog-api-client'], + ) + + +def test_set_mcp_usage_header_with_existing_mcp_header(): + if not _is_mcp_imported: + return + """Test whether the MCP usage header is set correctly from an existing MCP header.""" + headers = { + 'x-goog-api-client': ( + 'google-genai-sdk/1.0.0 gl-python/1.0.0 mcp_used/1.0.0' + ) + } + _mcp_utils.set_mcp_usage_header(headers) + assert re.match( + r'google-genai-sdk/1.0.0 gl-python/1.0.0 mcp_used/\d+\.\d+\.\d+', + headers['x-goog-api-client'], + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2da6c6d6a2c292cea762f172b5c913f157998b65 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/__init__.py @@ -0,0 +1,17 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for the Google GenAI SDK's models module.""" \ No newline at end of file diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/constants.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..d360291b6367c0e15811d8728f185b950de90984 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/constants.py @@ -0,0 +1,8 @@ +VERTEX_HTTP_OPTIONS = { + 'api_version': 'v1beta1', + 'base_url': 'https://us-central1-aiplatform.googleapis.com/', +} +MLDEV_HTTP_OPTIONS = { + 'api_version': 'v1beta', + 'base_url': 'https://generativelanguage.googleapis.com/', +} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_compute_tokens.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_compute_tokens.py new file mode 100644 index 0000000000000000000000000000000000000000..d507f42df30f997657fd1e5a3e12c0bc066ddb44 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_compute_tokens.py @@ -0,0 +1,120 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +import pytest +from ... import _transformers as t +from ... import types +from .. import pytest_helper +from . import constants + +_COMPUTE_TOKENS_PARAMS = types._ComputeTokensParameters( + model='gemini-2.5-flash', + contents=[t.t_content('Tell me a story in 300 words.')], +) +_COMPUTE_TOKENS_PARAMS_VERTEX_CUSTOM_URL = types._ComputeTokensParameters( + model='gemini-2.5-flash', + contents=[t.t_content('Tell me a story in 300 words.')], + config={'http_options': constants.VERTEX_HTTP_OPTIONS}, +) +_COMPUTE_TOKENS_PARAMS_MLDEV_CUSTOM_URL = types._ComputeTokensParameters( + model='gemini-2.5-flash', + contents=[t.t_content('Tell me a story in 300 words.')], + config={'http_options': constants.MLDEV_HTTP_OPTIONS}, +) +_UNICODE_STRING = '这是一条unicode测试🤪❤★' + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_compute_tokens', + exception_if_mldev='only supported in', + parameters=types._ComputeTokensParameters( + model='gemini-2.5-flash', + contents=[t.t_content('Tell me a story in 300 words.')], + ), + ), + pytest_helper.TestTableItem( + name='test_compute_tokens_vertex_custom_url', + parameters=_COMPUTE_TOKENS_PARAMS_VERTEX_CUSTOM_URL, + exception_if_mldev='only supported in', + ), + pytest_helper.TestTableItem( + name='test_compute_tokens_mldev_custom_url', + parameters=_COMPUTE_TOKENS_PARAMS_MLDEV_CUSTOM_URL, + exception_if_vertex='404', + exception_if_mldev='only supported in', + ), + pytest_helper.TestTableItem( + name='test_compute_tokens_unicode', + exception_if_mldev='only supported in', + parameters=types._ComputeTokensParameters( + model='gemini-2.5-flash', contents=[t.t_content(_UNICODE_STRING)] + ), + ), +] +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='models.compute_tokens', + test_table=test_table, +) + + +def test_token_bytes_deserialization(client): + if client._api_client.vertexai: + response = client.models.compute_tokens( + model=_COMPUTE_TOKENS_PARAMS.model, + contents=_UNICODE_STRING, + ) + decoded_tokens = b''.join(response.tokens_info[0].tokens) + assert ( + decoded_tokens + == b'\xe8\xbf\x99\xe6\x98\xaf\xe4\xb8\x80\xe6\x9d\xa1unicode\xe6\xb5\x8b\xe8\xaf\x95\xf0\x9f\xa4\xaa\xe2\x9d\xa4\xe2\x98\x85' + ) + assert decoded_tokens.decode('utf-8') == _UNICODE_STRING + + +@pytest.mark.asyncio +async def test_async(client): + if client._api_client.vertexai: + response = await client.aio.models.compute_tokens( + model=_COMPUTE_TOKENS_PARAMS.model, + contents=_COMPUTE_TOKENS_PARAMS.contents, + ) + assert response + else: + with pytest.raises(Exception): + await client.aio.models.compute_tokens( + model=_COMPUTE_TOKENS_PARAMS.model, + contents=_COMPUTE_TOKENS_PARAMS.contents, + ) + + +def test_different_model_names(client): + if client._api_client.vertexai: + response1 = client.models.compute_tokens( + model='gemini-2.5-flash', contents=_COMPUTE_TOKENS_PARAMS.contents + ) + assert response1 + response3 = client.models.compute_tokens( + model='publishers/google/models/gemini-2.5-flash', + contents=_COMPUTE_TOKENS_PARAMS.contents, + ) + assert response3 + response4 = client.models.compute_tokens( + model='projects/vertexsdk/locations/us-central1/publishers/google/models/gemini-2.5-flash', + contents=_COMPUTE_TOKENS_PARAMS.contents, + ) + assert response4 diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_count_tokens.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_count_tokens.py new file mode 100644 index 0000000000000000000000000000000000000000..6589bc470517a219f4ad659a8620eb6b96acacd7 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_count_tokens.py @@ -0,0 +1,159 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +import copy +import pytest +from ... import _transformers as t +from ... import errors +from ... import types +from .. import pytest_helper +from . import constants + +_COUNT_TOKENS_PARAMS = types._CountTokensParameters( + model='gemini-2.5-flash', + contents=[t.t_content('Tell me a story in 300 words.')], +) + +_COUNT_TOKENS_PARAMS_WITH_SYSTEM_INSTRUCTION = copy.deepcopy( + _COUNT_TOKENS_PARAMS +) +_COUNT_TOKENS_PARAMS_WITH_SYSTEM_INSTRUCTION.config = { + 'system_instruction': t.t_content('you are a chatbot.') +} + +_COUNT_TOKENS_PARAMS_WITH_TOOLS = copy.deepcopy(_COUNT_TOKENS_PARAMS) +_COUNT_TOKENS_PARAMS_WITH_TOOLS.config = { + 'tools': [{'google_search_retrieval': {}}] +} + +_COUNT_TOKENS_PARAMS_WITH_GENERATION_CONFIG = copy.deepcopy( + _COUNT_TOKENS_PARAMS +) +_COUNT_TOKENS_PARAMS_WITH_GENERATION_CONFIG.config = { + 'generation_config': {'max_output_tokens': 50} +} + +_COUNT_TOKENS_PARAMS_VERTEX_CUSTOM_URL = copy.deepcopy(_COUNT_TOKENS_PARAMS) +_COUNT_TOKENS_PARAMS_VERTEX_CUSTOM_URL.config = { + 'http_options': constants.VERTEX_HTTP_OPTIONS +} +_COUNT_TOKENS_PARAMS_MLDEV_CUSTOM_URL = copy.deepcopy(_COUNT_TOKENS_PARAMS) +_COUNT_TOKENS_PARAMS_MLDEV_CUSTOM_URL.config = { + 'http_options': constants.MLDEV_HTTP_OPTIONS +} + + +# TODO(b/378952792): MLDev count_tokens needs to merge contents and model +# param into generateContentRequest field. +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_count_tokens', + parameters=_COUNT_TOKENS_PARAMS, + ), + pytest_helper.TestTableItem( + name='test_count_tokens_vertex_custom_url', + parameters=_COUNT_TOKENS_PARAMS_VERTEX_CUSTOM_URL, + exception_if_mldev='404', + ), + pytest_helper.TestTableItem( + name='test_count_tokens_mldev_custom_url', + parameters=_COUNT_TOKENS_PARAMS_MLDEV_CUSTOM_URL, + exception_if_vertex='404', + ), + pytest_helper.TestTableItem( + name='test_count_tokens_with_system_instruction', + exception_if_mldev='not supported', + parameters=_COUNT_TOKENS_PARAMS_WITH_SYSTEM_INSTRUCTION, + ), + pytest_helper.TestTableItem( + name='test_count_tokens_with_tools', + exception_if_mldev='not supported', + parameters=_COUNT_TOKENS_PARAMS_WITH_TOOLS, + ), + pytest_helper.TestTableItem( + name='test_count_tokens_with_generation_config', + exception_if_mldev='not supported', + parameters=_COUNT_TOKENS_PARAMS_WITH_GENERATION_CONFIG, + ), +] +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='models.count_tokens', + test_table=test_table, +) + + +@pytest.mark.asyncio +async def test_async(client): + response = await client.aio.models.count_tokens( + model=_COUNT_TOKENS_PARAMS.model, contents=_COUNT_TOKENS_PARAMS.contents + ) + assert response + + +def test_different_model_names(client): + if client._api_client.vertexai: + response1 = client.models.count_tokens( + model='gemini-2.5-flash', contents=_COUNT_TOKENS_PARAMS.contents + ) + assert response1 + response3 = client.models.count_tokens( + model='publishers/google/models/gemini-2.5-flash', + contents=_COUNT_TOKENS_PARAMS.contents, + ) + assert response3 + response4 = client.models.count_tokens( + model='projects/vertexsdk/locations/us-central1/publishers/google/models/gemini-2.5-flash', + contents=_COUNT_TOKENS_PARAMS.contents, + ) + assert response4 + else: + response1 = client.models.count_tokens( + model='gemini-2.5-flash', contents=_COUNT_TOKENS_PARAMS.contents + ) + assert response1 + response2 = client.models.count_tokens( + model='models/gemini-2.5-flash', contents=_COUNT_TOKENS_PARAMS.contents + ) + assert response2 + + +def test_extra_body(client): + config = { + 'http_options': { + 'extra_body': { + 'systemInstruction': { + 'parts': [{'text': 'you are a chatbot.'}], + 'role': 'user', + } + } + } + } + if client._api_client.vertexai: + response = client.models.count_tokens( + model=_COUNT_TOKENS_PARAMS.model, + contents=_COUNT_TOKENS_PARAMS.contents, + config=config, + ) + assert response.total_tokens + else: + with pytest.raises(errors.ClientError): + client.models.count_tokens( + model=_COUNT_TOKENS_PARAMS.model, + contents=_COUNT_TOKENS_PARAMS.contents, + config=config, + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_delete.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_delete.py new file mode 100644 index 0000000000000000000000000000000000000000..b3d86ea73d32862c1c3ac9f68f2de9f06bcf1a27 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_delete.py @@ -0,0 +1,107 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for models.get.""" + +import pytest + +from ... import errors +from ... import types +from .. import pytest_helper + +TEST_API_VERSION = 'test_api_version' +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_delete_model', + parameters=types._DeleteModelParameters( + model='models/8533706666867163136' + ), + exception_if_mldev='404', + skip_in_api_mode='cannot be deleted for multiple times', + ), + pytest_helper.TestTableItem( + name='test_delete_model_with_http_options_in_method', + parameters=types._DeleteModelParameters( + model='tmodels/8533706666867163136', + config={ + 'http_options': { + 'api_version': TEST_API_VERSION, + 'headers': {'test': 'headers'}, + }, + }, + ), + exception_if_vertex=TEST_API_VERSION, + exception_if_mldev='404', + skip_in_api_mode='cannot be deleted for multiple times', + ), + pytest_helper.TestTableItem( + name='test_delete_tuned_model', + parameters=types._DeleteModelParameters( + model='tunedModels/generate-num-9598' + ), + exception_if_vertex='404', + skip_in_api_mode='cannot be deleted for multiple times', + ), +] +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='models.delete', + test_table=test_table, +) + + +@pytest.mark.asyncio +async def test_async_delete_model_with_http_options_in_method(client): + + with pytest.raises(errors.ClientError) as e: + await client.aio.models.delete( + model='tunedModels/generate-num-888', + config={ + 'http_options': { + 'api_version': TEST_API_VERSION, + 'headers': {'test': 'headers'}, + }, + }, + ) + if client._api_client.vertexai: + assert TEST_API_VERSION in e.value.args[0] + else: + assert '404' in str(e) + + +@pytest.mark.asyncio +async def test_async_delete_tuned_model(client): + if client._api_client.vertexai: + with pytest.raises(errors.ClientError) as e: + await client.aio.models.delete(model='tunedModels/generate-num-888') + assert '404' in str(e) + else: + response = await client.aio.models.delete( + model='tunedModels/generate-num-888' + ) + + +@pytest.mark.asyncio +async def test_async_delete_model(client): + if client._api_client.vertexai: + response = await client.aio.models.delete( + model='models/1071206899942162432' + ) + else: + with pytest.raises(errors.ClientError) as e: + await client.aio.models.delete(model='models/1071206899942162432') + assert '404' in str(e) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_edit_image.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_edit_image.py new file mode 100644 index 0000000000000000000000000000000000000000..1bcaf3298805ce431757ad3b1cd078a306cedca0 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_edit_image.py @@ -0,0 +1,264 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for edit_image.""" + +import os + +import pydantic +import pytest + +from ... import types +from .. import pytest_helper + +CAPABILITY_MODEL_NAME = 'imagen-3.0-capability-001' + +IMAGE_FILE_PATH = os.path.abspath( + os.path.join(os.path.dirname(__file__), '../data/google.png') +) + +MASK_FILE_PATH = os.path.abspath( + os.path.join(os.path.dirname(__file__), '../data/checkerboard.png') +) + +BRIDGE_IMAGE_FILE_PATH = os.path.abspath( + os.path.join(os.path.dirname(__file__), '../data/bridge1.png') +) + +raw_ref_image = types.RawReferenceImage( + reference_id=1, + reference_image=types.Image.from_file(location=IMAGE_FILE_PATH), +) + +mask_ref_image = types.MaskReferenceImage( + reference_id=2, + config=types.MaskReferenceConfig( + mask_mode='MASK_MODE_BACKGROUND', + mask_dilation=0.06, + ), +) + +mask_ref_image_user_provided = types.MaskReferenceImage( + reference_id=2, + reference_image=types.Image.from_file(location=MASK_FILE_PATH), + config=types.MaskReferenceConfig( + mask_mode='MASK_MODE_USER_PROVIDED', + mask_dilation=0.06, + ), +) + +control_ref_image = types.ControlReferenceImage( + reference_id=2, + reference_image=types.Image.from_file(location=MASK_FILE_PATH), + config=types.ControlReferenceConfig( + control_type='CONTROL_TYPE_SCRIBBLE', + # Backend creates the control image if this is set to True. + enable_control_image_computation=False, + ), +) + +style_ref_image_customization = types.StyleReferenceImage( + reference_id=1, + reference_image=types.Image.from_file(location=IMAGE_FILE_PATH), + config=types.StyleReferenceConfig( + style_description='glowing style', + ), +) + +subject_ref_image_customization = types.SubjectReferenceImage( + reference_id=1, + reference_image=types.Image.from_file(location=IMAGE_FILE_PATH), + config=types.SubjectReferenceConfig( + subject_type='SUBJECT_TYPE_PRODUCT', + subject_description='A product logo that is a multi-colored letter G', + ), +) + +dog_content_ref_image = types.ContentReferenceImage( + reference_id=1, + reference_image=types.Image( + gcs_uri='gs://genai-sdk-tests/inputs/images/dog.jpg' + ), +) + +cyberpunk_style_ref_image = types.StyleReferenceImage( + reference_id=2, + reference_image=types.Image( + gcs_uri='gs://genai-sdk-tests/inputs/images/cyberpunk.jpg' + ), + config=types.StyleReferenceConfig( + style_description='cyberpunk style', + ), +) + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_edit_mask_inpaint_insert', + exception_if_mldev='only supported in the Vertex AI client', + parameters=types._EditImageParameters( + model=CAPABILITY_MODEL_NAME, + prompt='Sunlight and clear weather', + reference_images=[raw_ref_image, mask_ref_image], + config=types.EditImageConfig( + edit_mode=types.EditMode.EDIT_MODE_INPAINT_INSERTION, + number_of_images=1, + # Test comprehensive configs + # aspect_ratio is not supported for mask editing + negative_prompt='human', + guidance_scale=15.0, + safety_filter_level=types.SafetyFilterLevel.BLOCK_MEDIUM_AND_ABOVE, + person_generation=types.PersonGeneration.DONT_ALLOW, + include_safety_attributes=False, + include_rai_reason=True, + output_mime_type='image/jpeg', + output_compression_quality=80, + base_steps=32, + add_watermark=False, + labels={'imagen_label_key': 'edit_image'} + ), + ), + ), + pytest_helper.TestTableItem( + name='test_edit_mask_inpaint_insert_user_provided', + exception_if_mldev='only supported in the Vertex AI client', + parameters=types._EditImageParameters( + model=CAPABILITY_MODEL_NAME, + prompt='Change the colors', + reference_images=[raw_ref_image, mask_ref_image_user_provided], + config=types.EditImageConfig( + edit_mode=types.EditMode.EDIT_MODE_INPAINT_INSERTION, + # aspect_ratio is not supported for mask editing + number_of_images=1, + include_rai_reason=True, + ), + ), + ), + pytest_helper.TestTableItem( + name='test_edit_control_user_provided', + exception_if_mldev='only supported in the Vertex AI client', + parameters=types._EditImageParameters( + model=CAPABILITY_MODEL_NAME, + prompt='Change the colors aligning with the scribble map [2]', + reference_images=[raw_ref_image, control_ref_image], + config=types.EditImageConfig( + number_of_images=1, + aspect_ratio='9:16', + include_rai_reason=True, + ), + ), + ), + pytest_helper.TestTableItem( + name='test_edit_style_reference_image_customization', + exception_if_mldev='only supported in the Vertex AI client', + parameters=types._EditImageParameters( + model=CAPABILITY_MODEL_NAME, + prompt=( + 'Generate an image in glowing style [1] based on the following' + ' caption: A church in the mountain.' + ), + reference_images=[style_ref_image_customization], + config=types.EditImageConfig( + number_of_images=1, + aspect_ratio='9:16', + include_rai_reason=True, + ), + ), + ), + pytest_helper.TestTableItem( + name='test_edit_subject_image_customization', + exception_if_mldev='only supported in the Vertex AI client', + parameters=types._EditImageParameters( + model=CAPABILITY_MODEL_NAME, + prompt=( + 'Generate an image containing a mug with the product logo [1]' + ' visible on the side of the mug.' + ), + reference_images=[subject_ref_image_customization], + config=types.EditImageConfig( + number_of_images=1, + aspect_ratio='9:16', + include_rai_reason=True, + ), + ), + ), + pytest_helper.TestTableItem( + name='test_edit_content_image_ingredients', + exception_if_mldev='only supported in the Vertex AI client', + parameters=types._EditImageParameters( + model='imagen-4.0-ingredients-preview', + prompt=( + 'Dog in [1] sleeping on the ground at the bottom of the image' + ' with the cyberpunk city landscape in [2] in the background.' + ), + reference_images=[dog_content_ref_image, cyberpunk_style_ref_image], + config=types.EditImageConfig( + number_of_images=1, + aspect_ratio='9:16', + include_rai_reason=True, + output_mime_type='image/jpeg', + ), + ), + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='models.edit_image', + test_table=test_table, +) + + +def test_setting_reference_type_raises(client): + with pytest.raises(pydantic.ValidationError): + types.SubjectReferenceImage( + reference_id=1, + # This test should fail because the user can't set reference_type. + reference_type='REFERENCE_TYPE_SUBJECT', + reference_image=types.Image.from_file(location=IMAGE_FILE_PATH), + config=types.SubjectReferenceConfig( + subject_type='SUBJECT_TYPE_PRODUCT', + subject_description=( + 'A product logo that is a multi-colored letter G' + ), + ), + ) + + +@pytest.mark.asyncio +async def test_edit_mask_inpaint_insert_async(client): + with pytest_helper.exception_if_mldev(client, ValueError): + response = await client.aio.models.edit_image( + model=CAPABILITY_MODEL_NAME, + prompt='Sunlight and clear weather', + reference_images=[raw_ref_image, mask_ref_image], + config=types.EditImageConfig( + edit_mode=types.EditMode.EDIT_MODE_INPAINT_INSERTION, + number_of_images=1, + # Test comprehensive configs + # aspect_ratio is not supported for mask editing + negative_prompt='human', + guidance_scale=15.0, + safety_filter_level=types.SafetyFilterLevel.BLOCK_MEDIUM_AND_ABOVE, + person_generation=types.PersonGeneration.DONT_ALLOW, + include_safety_attributes=False, + include_rai_reason=True, + output_mime_type='image/jpeg', + output_compression_quality=80, + add_watermark=False, + ), + ) + assert response.generated_images[0].image.image_bytes diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_embed_content.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_embed_content.py new file mode 100644 index 0000000000000000000000000000000000000000..3b18646006f963d32d3a100fd6e8fe3bf664687a --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_embed_content.py @@ -0,0 +1,269 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# +# pylint: disable=protected-access + + +"""Tests for models.embedContent().""" + +import os +import pytest + +from ... import _transformers as t +from ... import types +from .. import pytest_helper + + +def _get_bytes_from_file(relative_path: str) -> bytes: + abs_file_path = os.path.abspath( + os.path.join(os.path.dirname(__file__), relative_path) + ) + with open(abs_file_path, 'rb') as file: + return file.read() + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_multi_texts_with_config', + parameters=types.EmbedContentParameters( + model='gemini-embedding-001', + contents=[ + t.t_content('What is your name?'), + t.t_content('I am a model.'), + ], + config={ + 'output_dimensionality': 10, + 'title': 'test_title', + 'task_type': 'RETRIEVAL_DOCUMENT', + 'http_options': { + 'headers': {'test': 'headers'}, + }, + }, + ), + ), + pytest_helper.TestTableItem( + name='test_single_text_with_mime_type_not_supported_in_mldev', + parameters=types.EmbedContentParameters( + model='gemini-embedding-001', + contents=t.t_contents('What is your name?'), + config={ + 'output_dimensionality': 10, + 'mime_type': 'text/plain', + }, + ), + exception_if_mldev='parameter is not supported', + ), + pytest_helper.TestTableItem( + name='test_single_text_with_auto_truncate_not_supported_in_mldev', + parameters=types.EmbedContentParameters( + model='gemini-embedding-001', + contents=t.t_contents('What is your name?'), + config={ + 'output_dimensionality': 10, + 'auto_truncate': True, + }, + ), + exception_if_mldev='parameter is not supported', + ), + pytest_helper.TestTableItem( + name='test_vertex_new_api_text_only_with_config', + parameters=types.EmbedContentParameters( + model='gemini-embedding-2-preview', + contents=t.t_contents('What is your name?'), + config={ + 'output_dimensionality': 10, + 'title': 'test_title', + 'task_type': 'RETRIEVAL_DOCUMENT', + 'http_options': { + 'headers': {'test': 'headers'}, + }, + 'auto_truncate': True, + }, + ), + # auto_truncate not supported on MLDev. + exception_if_mldev='parameter is not supported', + ), + pytest_helper.TestTableItem( + name='test_new_api_text_only', + parameters=types.EmbedContentParameters( + model='gemini-embedding-2-preview', + contents=t.t_contents('What is your name?'), + config={ + 'output_dimensionality': 100, + }, + ), + ), + pytest_helper.TestTableItem( + name='test_vertex_new_api_maas', + parameters=types.EmbedContentParameters( + model=( + 'publishers/intfloat/models/multilingual-e5-large-instruct-maas' + ), + contents=t.t_contents('What is your name?'), + config={ + 'output_dimensionality': 100, + }, + ), + # Model not exposed on MLDev. + exception_if_mldev='404', + ), + pytest_helper.TestTableItem( + name='test_new_api_gcs_image_and_config', + parameters=types.EmbedContentParameters( + model='gemini-embedding-2-preview', + contents=[ + types.Content( + parts=[ + types.Part.from_text( + text='Similar things to the following image:' + ), + types.Part.from_uri( + file_uri='gs://cloud-samples-data/generative-ai/image/a-man-and-a-dog.png', + mime_type='image/png', + ), + ], + ) + ], + config={ + 'output_dimensionality': 10, + 'title': 'test_title', + 'task_type': 'RETRIEVAL_DOCUMENT', + 'http_options': { + 'headers': {'test': 'headers'}, + }, + }, + ), + ), + pytest_helper.TestTableItem( + name='test_new_api_inline_pdf', + parameters=types.EmbedContentParameters( + model='gemini-embedding-2-preview', + contents=[ + types.Content( + parts=[ + types.Part.from_bytes( + data=_get_bytes_from_file('../data/story.pdf'), + mime_type='application/pdf', + ), + ], + ) + ], + config={ + 'output_dimensionality': 100, + }, + ), + ), + pytest_helper.TestTableItem( + name='test_vertex_new_api_list_of_contents_error', + parameters=types.EmbedContentParameters( + model='gemini-embedding-2-exp-11-2025', + contents=[ + types.Content(parts=[types.Part.from_text(text='hello')]), + types.Content(parts=[types.Part.from_text(text='world')]), + ], + ), + exception_if_vertex='supports', + exception_if_mldev='404', + ), + pytest_helper.TestTableItem( + name='test_vertex_inline_pdf_document_ocr', + parameters=types.EmbedContentParameters( + model='gemini-embedding-2-preview', + contents=[ + types.Content( + parts=[ + types.Part.from_bytes( + data=_get_bytes_from_file('../data/story.pdf'), + mime_type='application/pdf', + ), + ], + ) + ], + config={ + 'output_dimensionality': 100, + 'document_ocr': True, + }, + ), + exception_if_mldev='not supported in Gemini API', + ), + pytest_helper.TestTableItem( + name='test_vertex_inline_video_audio_track_extraction', + parameters=types.EmbedContentParameters( + model='gemini-embedding-2-preview', + contents=[ + types.Content( + parts=[ + types.Part.from_bytes( + data=_get_bytes_from_file('../data/animal.mp4'), + mime_type='video/mp4', + ), + ], + ) + ], + config={ + 'output_dimensionality': 100, + 'audio_track_extraction': True, + }, + ), + exception_if_mldev='not supported in Gemini API', + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='models.embed_content', + test_table=test_table, +) + + +def test_gemini_embedding_2_content_combination(client): + response = client.models.embed_content( + model='gemini-embedding-2-preview', + contents=[ + 'The jetpack is cool', + types.Part.from_bytes( + data=_get_bytes_from_file('../data/checkerboard.png'), + mime_type='image/png', + ), + types.Part.from_uri( + file_uri='gs://generativeai-downloads/images/scones.jpg', + mime_type='image/jpeg', + ), + ], + config={'output_dimensionality': 100}, + ) + # assert has one total embedding + assert response.embeddings is not None + assert len(response.embeddings) == 1 + assert len(response.embeddings[0].values) == 100 + + +@pytest.mark.asyncio +async def test_async(client): + response = await client.aio.models.embed_content( + model='gemini-embedding-001', + contents='What is your name?', + config={'output_dimensionality': 10}, + ) + assert response + + +@pytest.mark.asyncio +async def test_async_new_api(client): + response = await client.aio.models.embed_content( + model='gemini-embedding-2-preview', + contents=t.t_contents('What is your name?'), + config={'output_dimensionality': 10}, + ) + assert response diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_function_call_streaming.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_function_call_streaming.py new file mode 100644 index 0000000000000000000000000000000000000000..7ac83bc24c0e57c04523097fd0092ac25362428d --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_function_call_streaming.py @@ -0,0 +1,442 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +"""Tests for models.generate_content_stream() with stream_function_call_arguments enabled.""" + +import pytest +from ... import types +from unittest import mock +from .. import pytest_helper +from . import test_generate_content_tools + +json_function_declarations = [{ + 'name': 'get_current_weather', + 'description': 'Get the current weather in a city', + 'parameters_json_schema': { + 'type': 'object', + 'properties': { + 'location': { + 'type': 'string', + 'description': 'The location to get the weather for', + }, + 'country': { + 'anyOf': [ + { + 'type': 'string', + 'description': 'The country to get the weather for', + }, + { + 'type': 'null', + }, + ], + 'description': 'The country to get the weather for', + }, + 'unit': { + 'type': 'string', + 'enum': ['C', 'F'], + }, + 'purpose': { + 'type': 'string', + 'description': 'Discribes the purpose of asking the weather', + } + }, + 'required': ['location', 'unit', 'country'], + }, +}] + +gemini_function_declarations = [{ + 'name': 'get_current_weather', + 'description': 'Get the current weather in a city', + 'parameters': { + 'type': 'OBJECT', + 'properties': { + 'location': { + 'type': 'STRING', + 'description': 'The location to get the weather for', + }, + 'country': { + 'type': 'STRING', + 'description': 'The country to get the weather for', + 'nullable': True, + }, + 'unit': { + 'type': 'STRING', + 'enum': ['C', 'F'], + 'description': 'The unit to return the weather in', + }, + 'purpose': { + 'type': 'STRING', + 'description': 'Discribes the purpose of asking the weather', + } + }, + 'required': ['location', 'unit', 'country'], + }, +}] + +generate_content_prompt = [ + types.Content( + role='user', + parts=[ + types.Part( + text=( + 'get the current weather in boston in celsius, the' + ' country should be US, the purpose is to know' + ' what to wear today?' + ) + ) + ], + ), +] +previous_generate_content_history = [ + types.Content( + role='user', + parts=[ + types.Part( + text=( + ' get the current weather in boston in celsius, the country' + ' is U.S., the purpose is to' + ' know what to wear today.' + ) + ) + ], + ), + types.Content( + role='model', + parts=[ + types.Part( + function_call=types.FunctionCall( + name='get_current_weather', + will_continue=True, + ) + ) + ], + ), + types.Content( + role='model', + parts=[ + types.Part( + function_call=types.FunctionCall( + name='get_current_weather', + partial_args=[ + types.PartialArg( + json_path='$.country', + null_value="NULL_VALUE", + ) + ], + will_continue=False, + ) + ) + ], + ) +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='models.generate_content_stream', +) + +def test_streaming_with_python_native_no_afc_config(client): + """Tests streaming function calls with native python AFC without disabling AFC.""" + if not client.vertexai: + return + with pytest.raises(ValueError) as e: + for chunk in client.models.generate_content_stream( + model='gemini-3-pro-preview', + contents=generate_content_prompt, + config=types.GenerateContentConfig( + tools=[ + test_generate_content_tools.get_weather, + test_generate_content_tools.get_stock_price, + ], + tool_config=types.ToolConfig( + function_calling_config={ + 'stream_function_call_arguments': True, + } + ), + ), + ): + pass + + assert 'not compatible with automatic function calling (AFC)' in str(e.value) + + +def test_streaming_with_python_afc_disabled_false(client): + """Tests streaming function calls with native python AFC without disabling AFC.""" + if not client.vertexai: + return + with pytest.raises(ValueError) as e: + for chunk in client.models.generate_content_stream( + model='gemini-3-pro-preview', + contents=( + 'What is the price of GOOG? And what is the weather in Boston?' + ), + config=types.GenerateContentConfig( + tools=[ + test_generate_content_tools.get_weather, + test_generate_content_tools.get_stock_price, + ], + automatic_function_calling=types.AutomaticFunctionCallingConfig( + disable=False, + ), + tool_config=types.ToolConfig( + function_calling_config={ + 'stream_function_call_arguments': True, + } + ), + ), + ): + pass + assert 'not compatible with automatic function calling (AFC)' in str(e.value) + + +def test_streaming_with_json_parameters_without_history(client): + """Tests streaming function calls with FunctionDeclaration withJSON parameters.""" + + with pytest_helper.exception_if_mldev(client, ValueError): + for chunk in client.models.generate_content_stream( + model='gemini-3-pro-preview', + contents=generate_content_prompt, + config=types.GenerateContentConfig( + tools=[{'function_declarations': json_function_declarations}], + tool_config=types.ToolConfig( + function_calling_config={ + 'stream_function_call_arguments': True, + } + ), + ), + ): + assert chunk is not None + assert chunk.candidates is not None + assert chunk.candidates[0].content is not None + assert chunk.candidates[0].content.parts is not None + + +@pytest.mark.asyncio +async def test_streaming_with_json_parameters_async(client): + """Tests streaming function calls with FunctionDeclaration withJSON parameters.""" + with pytest_helper.exception_if_mldev(client, ValueError): + async for chunk in await client.aio.models.generate_content_stream( + model='gemini-3-pro-preview', + contents=generate_content_prompt, + config=types.GenerateContentConfig( + tools=[{'function_declarations': json_function_declarations}], + tool_config=types.ToolConfig( + function_calling_config={ + 'stream_function_call_arguments': True, + } + ), + ), + ): + assert chunk is not None + assert chunk.candidates is not None + assert chunk.candidates[0].content is not None + assert chunk.candidates[0].content.parts is not None + + +def test_streaming_with_gemini_parameters_without_history(client): + """Tests streaming function calls with FunctionDeclaration withJSON parameters.""" + with pytest_helper.exception_if_mldev(client, ValueError): + for chunk in client.models.generate_content_stream( + model='gemini-3-pro-preview', + contents=generate_content_prompt, + config=types.GenerateContentConfig( + tools=[{ + 'function_declarations': gemini_function_declarations + }], + tool_config=types.ToolConfig( + function_calling_config={ + 'stream_function_call_arguments': True, + } + ), + ), + ): + assert chunk is not None + assert chunk.candidates is not None + assert chunk.candidates[0].content is not None + assert chunk.candidates[0].content.parts is not None + +def test_streaming_with_gemini_parameters_with_response(client): + """Tests streaming function calls with FunctionDeclaration withJSON parameters.""" + with pytest_helper.exception_if_mldev(client, ValueError): + streaming_function_call_content = [] + for chunk in client.models.generate_content_stream( + model='gemini-3-pro-preview', + contents=[ + types.Content( + role='user', + parts=[ + types.Part( + text=( + 'get the current weather in boston in celsius, the' + ' country should be US, the purpose is to know' + ' what to wear today?' + ) + ) + ], + ), + ], + config=types.GenerateContentConfig( + tools=[{ + 'function_declarations': gemini_function_declarations + }], + tool_config=types.ToolConfig( + function_calling_config={ + 'stream_function_call_arguments': True, + } + ), + ), + ): + streaming_function_call_content.append(chunk.candidates[0].content) + + streaming_function_call_content.append( + types.Content( + role='user', + parts=[ + types.Part.from_function_response( + name='get_current_weather', + response={ + 'temperature': 21, + 'unit': 'C', + }, + ) + ], + ), + ) + + for chunk in client.models.generate_content_stream( + model='gemini-3-pro-preview', + contents=streaming_function_call_content, + config=types.GenerateContentConfig( + tools=[{'function_declarations': json_function_declarations}], + tool_config=types.ToolConfig( + function_calling_config={ + 'stream_function_call_arguments': True, + } + ), + ), + ): + pass + +def test_chat_streaming_with_json_parameters_with_history(client): + """Tests streaming function calls with FunctionDeclaration withJSON parameters.""" + with pytest_helper.exception_if_mldev(client, ValueError): + test_parts = [ + types.Part( + text=( + 'get the current weather in boston in celsius, the' + ' country should be US, the purpose is to know' + ' what to wear today?' + ) + ), + types.Part.from_function_response( + name='get_current_weather', + response={ + 'temperature': 21, + 'unit': 'C', + }, + ), + types.Part( + text=( + 'get the current weather in new brunswick in celsius, the' + ' country should be US, the purpose is to know' + ' what to prepare an event today?' + ) + ), + types.Part.from_function_response( + name='get_current_weather', + response={ + 'temperature': 21, + 'unit': 'C', + }, + ), + ] + chat = client.chats.create( + model='gemini-3-pro-preview', + history=previous_generate_content_history, + config=types.GenerateContentConfig( + tools=[{ + 'function_declarations': gemini_function_declarations + }], + tool_config=types.ToolConfig( + function_calling_config={ + 'stream_function_call_arguments': True, + } + ), + ), + ) + for message in test_parts: + result = chat.send_message_stream(message) + for chunk in result: + assert chunk is not None + assert chunk.candidates is not None + assert chunk.candidates[0].content is not None + assert chunk.candidates[0].content.parts is not None + + assert chat.get_history() is not None + + +@pytest.mark.asyncio +async def test_chat_streaming_with_json_parameters_with_history_async(client): + """Tests streaming function calls with FunctionDeclaration withJSON parameters.""" + test_parts = [ + types.Part( + text=( + 'get the current weather in boston in celsius, the' + ' country should be US, the purpose is to know' + ' what to wear today?' + ) + ), + types.Part.from_function_response( + name='get_current_weather', + response={ + 'temperature': 21, + 'unit': 'C', + }, + ), + types.Part( + text=( + 'get the current weather in new brunswick in celsius, the' + ' country should be US, the purpose is to know' + ' what to prepare an event today?' + ) + ), + types.Part.from_function_response( + name='get_current_weather', + response={ + 'temperature': 21, + 'unit': 'C', + }, + ), + ] + with pytest_helper.exception_if_mldev(client, ValueError): + chat = client.aio.chats.create( + model='gemini-3-pro-preview', + history=previous_generate_content_history, + config=types.GenerateContentConfig( + tools=[{'function_declarations': gemini_function_declarations}], + tool_config=types.ToolConfig( + function_calling_config={ + 'stream_function_call_arguments': True, + } + ), + ), + ) + for message in test_parts: + async for chunk in await chat.send_message_stream(message): + assert chunk is not None + assert chunk.candidates is not None + assert chunk.candidates[0].content is not None + assert chunk.candidates[0].content.parts is not None diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_content.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_content.py new file mode 100644 index 0000000000000000000000000000000000000000..72759f960812514f23625cfa41233b049f822cbd --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_content.py @@ -0,0 +1,2535 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +import os +import pathlib + +from pydantic import BaseModel, ValidationError, Field, ConfigDict +from typing import Literal, List, Optional, Union, Set +from datetime import datetime +import pytest +import json +import logging +import sys +from ... import _transformers as t +from ... import errors +from ... import types +from .. import pytest_helper +from enum import Enum + +GEMINI_FLASH_LATEST = 'gemini-2.5-flash' +GEMINI_FLASH_2_0 = 'gemini-2.0-flash-001' +GEMINI_FLASH_IMAGE_LATEST = 'gemini-2.5-flash-image' + +IMAGE_PNG_FILE_PATH = pathlib.Path(__file__).parent / '../data/google.png' +image_bytes = IMAGE_PNG_FILE_PATH.read_bytes() + +AUDIO_WAV_FILE_PATH = pathlib.Path(__file__).parent / '../data/voice_sample.wav' +audio_bytes = AUDIO_WAV_FILE_PATH.read_bytes() + + +safety_settings_with_method = [ + { + 'category': 'HARM_CATEGORY_HATE_SPEECH', + 'threshold': 'BLOCK_ONLY_HIGH', + 'method': 'SEVERITY', + }, + { + 'category': 'HARM_CATEGORY_DANGEROUS_CONTENT', + 'threshold': 'BLOCK_LOW_AND_ABOVE', + 'method': 'PROBABILITY', + }, +] + +test_http_options = {'api_version': 'v1', 'headers': {'test': 'headers'}} + + +class InstrumentEnum(Enum): + PERCUSSION = 'Percussion' + STRING = 'String' + WOODWIND = 'Woodwind' + BRASS = 'Brass' + KEYBOARD = 'Keyboard' + + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_http_options_in_method', + parameters=types._GenerateContentParameters( + model=GEMINI_FLASH_LATEST, + contents=t.t_contents('What is your name?'), + config={ + 'http_options': test_http_options, + }, + ), + ), + pytest_helper.TestTableItem( + name='test_union_contents_is_string', + override_replay_id='test_sync', + parameters=types._GenerateContentParameters( + model=GEMINI_FLASH_LATEST, contents='Tell me a story in 300 words.' + ), + has_union=True, + ), + pytest_helper.TestTableItem( + name='test_union_contents_is_content', + override_replay_id='test_sync', + parameters=types._GenerateContentParameters( + model=GEMINI_FLASH_LATEST, + contents=types.Content( + role='user', + parts=[types.Part(text='Tell me a story in 300 words.')], + ), + ), + has_union=True, + ), + pytest_helper.TestTableItem( + name='test_union_contents_is_parts', + override_replay_id='test_sync', + parameters=types._GenerateContentParameters( + model=GEMINI_FLASH_LATEST, + contents=[types.Part(text='Tell me a story in 300 words.')], + ), + has_union=True, + ), + pytest_helper.TestTableItem( + name='test_union_contents_is_part', + override_replay_id='test_sync', + parameters=types._GenerateContentParameters( + model=GEMINI_FLASH_LATEST, + contents=types.Part(text='Tell me a story in 300 words.'), + ), + has_union=True, + ), + pytest_helper.TestTableItem( + name='test_sync_content_list', + override_replay_id='test_sync', + parameters=types._GenerateContentParameters( + model=GEMINI_FLASH_LATEST, + contents=[ + types.Content( + role='user', + parts=[types.Part(text='Tell me a story in 300 words.')], + ) + ], + ), + ), + # You need to enable llama API in Vertex AI Model Garden. + pytest_helper.TestTableItem( + name='test_llama', + parameters=types._GenerateContentParameters( + model='meta/llama-3.2-90b-vision-instruct-maas', + contents=t.t_contents('What is your name?'), + ), + exception_if_mldev='404', + skip_in_api_mode='it will encounter 403 for api mode', + ), + pytest_helper.TestTableItem( + name='test_system_instructions', + parameters=types._GenerateContentParameters( + model=GEMINI_FLASH_LATEST, + contents=t.t_contents('high'), + config={ + 'system_instruction': t.t_content('I say high, you say low') + }, + ), + ), + pytest_helper.TestTableItem( + name='test_labels', + exception_if_mldev='not supported', + parameters=types._GenerateContentParameters( + model=GEMINI_FLASH_LATEST, + contents=t.t_contents('What is your name?'), + config={ + 'labels': {'label1': 'value1', 'label2': 'value2'}, + }, + ), + ), + pytest_helper.TestTableItem( + name='test_simple_shared_generation_config', + parameters=types._GenerateContentParameters( + model=GEMINI_FLASH_LATEST, + contents=t.t_contents('What is your name?'), + config={ + 'max_output_tokens': 100, + 'top_k': 2, + 'temperature': 0.5, + 'top_p': 0.5, + 'response_mime_type': 'application/json', + 'stop_sequences': ['\n'], + 'candidate_count': 2, + 'seed': 42, + }, + ), + ), + pytest_helper.TestTableItem( + name='test_2_candidates_gemini_2_5_flash', + parameters=types._GenerateContentParameters( + model=GEMINI_FLASH_LATEST, + contents=t.t_contents('Tell me a story in 30 words.'), + config={ + 'candidate_count': 2, + }, + ), + ), + pytest_helper.TestTableItem( + name='test_safety_settings_on_difference', + parameters=types._GenerateContentParameters( + model=GEMINI_FLASH_LATEST, + contents=t.t_contents('What is your name?'), + config={ + 'safety_settings': safety_settings_with_method, + }, + ), + exception_if_mldev='method', + ), + pytest_helper.TestTableItem( + name='test_penalty', + parameters=types._GenerateContentParameters( + model=GEMINI_FLASH_2_0, + contents=t.t_contents('Tell me a story in 30 words.'), + config={ + 'presence_penalty': 0.5, + 'frequency_penalty': 0.5, + }, + ), + ), + pytest_helper.TestTableItem( + name='test_penalty_gemini_2_0_flash', + parameters=types._GenerateContentParameters( + model=GEMINI_FLASH_2_0, + contents=t.t_contents('Tell me a story in 30 words.'), + config={ + 'presence_penalty': 0.5, + 'frequency_penalty': 0.5, + }, + ), + ), + pytest_helper.TestTableItem( + name='test_google_search_tool', + parameters=types._GenerateContentParameters( + model=GEMINI_FLASH_LATEST, + contents=t.t_contents('Why is the sky blue?'), + config=types.GenerateContentConfig( + tools=[types.Tool(google_search=types.GoogleSearch())] + ), + ), + ), + pytest_helper.TestTableItem( + name='test_google_maps_tool', + parameters=types._GenerateContentParameters( + model=GEMINI_FLASH_LATEST, + contents=t.t_contents('Find restaurants near me.'), + config=types.GenerateContentConfig( + tools=[{'google_maps': {}}], + tool_config={ + 'retrieval_config': { + 'lat_lng': { + 'latitude': 37.421993, + 'longitude': -122.079725, + } + } + }, + ), + ), + ), + pytest_helper.TestTableItem( + name='test_google_search_tool_with_time_range_filter', + parameters=types._GenerateContentParameters( + model=GEMINI_FLASH_LATEST, + contents=t.t_contents('What is the QQQ stock price?'), + config=types.GenerateContentConfig( + tools=[ + types.Tool( + google_search=types.GoogleSearch( + time_range_filter=types.Interval( + start_time=datetime.fromisoformat( + '2025-05-01T00:00:00Z' + ), + end_time=datetime.fromisoformat( + '2025-05-03T00:00:00Z' + ), + ) + ) + ) + ] + ), + ), + ), + pytest_helper.TestTableItem( + name='test_google_search_tool_with_exclude_domains', + parameters=types._GenerateContentParameters( + model=GEMINI_FLASH_LATEST, + contents=t.t_contents('Why is the sky blue?'), + config=types.GenerateContentConfig( + tools=[ + types.Tool( + google_search=types.GoogleSearch( + exclude_domains=['amazon.com', 'facebook.com'] + ) + ) + ] + ), + ), + exception_if_mldev='not supported in', + ), + pytest_helper.TestTableItem( + name='test_google_search_tool_with_blocking_confidence', + parameters=types._GenerateContentParameters( + model=GEMINI_FLASH_LATEST, + contents=t.t_contents('Why is the sky blue?'), + config=types.GenerateContentConfig( + tools=[ + types.Tool( + google_search=types.GoogleSearch( + blocking_confidence=types.PhishBlockThreshold.BLOCK_LOW_AND_ABOVE, + ) + ) + ] + ), + ), + exception_if_mldev='not supported in', + ), + pytest_helper.TestTableItem( + name='test_enterprise_web_search_tool', + parameters=types._GenerateContentParameters( + model=GEMINI_FLASH_LATEST, + contents=t.t_contents('Why is the sky blue?'), + config=types.GenerateContentConfig( + tools=[ + types.Tool( + enterprise_web_search=types.EnterpriseWebSearch() + ) + ] + ), + ), + exception_if_mldev='not supported in', + ), + pytest_helper.TestTableItem( + name='test_enterprise_web_search_tool_with_exclude_domains', + parameters=types._GenerateContentParameters( + model=GEMINI_FLASH_LATEST, + contents=t.t_contents('Why is the sky blue?'), + config=types.GenerateContentConfig( + tools=[ + types.Tool( + enterprise_web_search=types.EnterpriseWebSearch( + exclude_domains=['amazon.com', 'facebook.com'] + ) + ) + ] + ), + ), + exception_if_mldev='not supported in', + ), + pytest_helper.TestTableItem( + name='test_enterprise_web_search_tool_with_blocking_confidence', + parameters=types._GenerateContentParameters( + model=GEMINI_FLASH_LATEST, + contents=t.t_contents('Why is the sky blue?'), + config=types.GenerateContentConfig( + tools=[ + types.Tool( + enterprise_web_search=types.EnterpriseWebSearch( + blocking_confidence=types.PhishBlockThreshold.BLOCK_LOW_AND_ABOVE, + ) + ) + ] + ), + ), + exception_if_mldev='not supported in', + ), + pytest_helper.TestTableItem( + name='test_speech_with_config', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash-preview-tts', + contents=t.t_contents('Produce a speech response saying "Cheese"'), + config=types.GenerateContentConfig( + response_modalities=['audio'], + speech_config=types.SpeechConfig( + voice_config=types.VoiceConfig( + prebuilt_voice_config=types.PrebuiltVoiceConfig( + voice_name='charon' + ) + ) + ), + ), + ), + ), + pytest_helper.TestTableItem( + name='test_speech_with_multi_speaker_voice_config', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash-preview-tts', + contents=t.t_contents( + 'Alice says "Hi", Bob replies with "what\'s up"?' + ), + config=types.GenerateContentConfig( + response_modalities=['audio'], + speech_config=types.SpeechConfig( + multi_speaker_voice_config=types.MultiSpeakerVoiceConfig( + speaker_voice_configs=[ + types.SpeakerVoiceConfig( + speaker='Alice', + voice_config=types.VoiceConfig( + prebuilt_voice_config=types.PrebuiltVoiceConfig( + voice_name='leda' + ) + ), + ), + types.SpeakerVoiceConfig( + speaker='Bob', + voice_config=types.VoiceConfig( + prebuilt_voice_config=types.PrebuiltVoiceConfig( + voice_name='kore' + ) + ), + ), + ], + ) + ), + ), + ), + ), + pytest_helper.TestTableItem( + name='test_speech_error_with_speech_config_and_multi_speech_config', + exception_if_vertex='mutually exclusive', + exception_if_mldev='mutually exclusive', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash-preview-tts', + contents=t.t_contents( + 'Alice says "Hi", Bob replies with "what\'s up"?' + ), + config=types.GenerateContentConfig( + response_modalities=['audio'], + speech_config=types.SpeechConfig( + voice_config=types.VoiceConfig( + prebuilt_voice_config=types.PrebuiltVoiceConfig( + voice_name='puck' + ) + ), + multi_speaker_voice_config=types.MultiSpeakerVoiceConfig( + speaker_voice_configs=[ + types.SpeakerVoiceConfig( + speaker='Alice', + voice_config=types.VoiceConfig( + prebuilt_voice_config=types.PrebuiltVoiceConfig( + voice_name='leda' + ) + ), + ), + types.SpeakerVoiceConfig( + speaker='Bob', + voice_config=types.VoiceConfig( + prebuilt_voice_config=types.PrebuiltVoiceConfig( + voice_name='kore' + ) + ), + ), + ], + ), + ), + ), + ), + ), + pytest_helper.TestTableItem( + name='test_union_speech_string_config', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash-preview-tts', + contents='Say hello!', + config=types.GenerateContentConfig( + response_modalities=['audio'], speech_config='charon' + ), + ), + has_union=True, + ), + pytest_helper.TestTableItem( + name='test_audio_timestamp', + parameters=types._GenerateContentParameters( + model=GEMINI_FLASH_LATEST, + contents=[ + types.Content( + role='user', + parts=[ + types.Part( + file_data=types.FileData( + file_uri='gs://cloud-samples-data/generative-ai/audio/pixel.mp3', + mime_type='audio/mpeg', + ) + ), + types.Part( + text="""Can you transcribe this interview, in the + format of timecode, speaker, caption. Use speaker A, + speaker B, etc. to identify speakers.""" + ), + ], + ) + ], + config=types.GenerateContentConfig(audio_timestamp=True), + ), + exception_if_mldev='not supported', + ), + pytest_helper.TestTableItem( + name='test_response_schema_with_default', + parameters=types._GenerateContentParameters( + model=GEMINI_FLASH_LATEST, + contents=t.t_contents('What is your name?'), + config={ + 'response_mime_type': 'application/json', + 'response_schema': { + 'type': 'OBJECT', + 'properties': { + 'name': { + 'type': 'STRING', + 'default': 'default_name', + }, + }, + }, + }, + ), + ignore_keys=['parsed'], + ), + pytest_helper.TestTableItem( + name='test_invalid_model_parameter_path', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash/../../upload/v1beta/files', + contents=t.t_contents('What is your name?'), + ), + exception_if_vertex='invalid model parameter', + exception_if_mldev='invalid model parameter', + ), + pytest_helper.TestTableItem( + name='test_invalid_model_parameter_question_mark', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash?', + contents=t.t_contents('What is your name?'), + ), + exception_if_vertex='invalid model parameter', + exception_if_mldev='invalid model parameter', + ), + pytest_helper.TestTableItem( + name='test_invalid_model_parameter_ampersand', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash&', + contents=t.t_contents('What is your name?'), + ), + exception_if_vertex='invalid model parameter', + exception_if_mldev='invalid model parameter', + ), + pytest_helper.TestTableItem( + name='test_enhanced_civic_answers', + parameters=types._GenerateContentParameters( + model=GEMINI_FLASH_LATEST, + contents=t.t_contents( + 'Summarize the evidence that confirms widespread voter fraud' + ' was the reason the last national election results were' + ' inaccurate.' + ), + config={ + 'enable_enhanced_civic_answers': True, + }, + ), + exception_if_vertex='not supported', + ), + pytest_helper.TestTableItem( + name='test_model_armor_config', + parameters=types._GenerateContentParameters( + model=GEMINI_FLASH_LATEST, + contents=t.t_contents('What is your name?'), + config={ + 'model_armor_config': { + 'prompt_template_name': '', + 'response_template_name': '', + # Intentionally left blank just to test that the SDK doesn't + # throw an exception. + }, + }, + ), + exception_if_mldev='not supported', + ), + pytest_helper.TestTableItem( + name='test_service_tier', + parameters=types._GenerateContentParameters( + model=GEMINI_FLASH_LATEST, + contents=t.t_contents('What is your name?'), + config={ + 'service_tier': 'FLEX', + }, + ), + exception_if_vertex='400', + ), + pytest_helper.TestTableItem( + name='test_service_tier_lower', + parameters=types._GenerateContentParameters( + model=GEMINI_FLASH_LATEST, + contents=t.t_contents('What is your name?'), + config={ + 'service_tier': 'flex', + }, + ), + exception_if_vertex='400', + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='models.generate_content', + test_table=test_table, +) +pytest_plugins = ('pytest_asyncio',) + + +def test_sync_with_headers(client): + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Tell me a story in 300 words.', + ) + assert response.sdk_http_response.headers is not None + assert response.sdk_http_response.body is None + + +def test_sync_with_full_response(client): + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Tell me a story in 300 words.', + config={ + 'should_return_http_response': True, + }, + ) + print(response.sdk_http_response.body) + assert response.sdk_http_response.headers is not None + assert response.sdk_http_response.body is not None + assert 'candidates' in response.sdk_http_response.body + assert 'content' in response.sdk_http_response.body + assert 'parts' in response.sdk_http_response.body + assert 'usageMetadata' in response.sdk_http_response.body + +@pytest.mark.asyncio +async def test_async(client): + response = await client.aio.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Tell me a story in 300 words.', + config={ + 'http_options': test_http_options, + }, + ) + assert response.text + + +@pytest.mark.asyncio +async def test_async_with_headers(client): + response = await client.aio.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Tell me a story in 300 words.', + ) + assert response.sdk_http_response.headers is not None + assert response.sdk_http_response.body is None + + +@pytest.mark.asyncio +async def test_async_with_full_response(client): + response = await client.aio.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Tell me a story in 300 words.', + config={ + 'should_return_http_response': True, + }, + ) + assert response.sdk_http_response.headers is not None + assert response.sdk_http_response.body is not None + assert 'candidates' in response.sdk_http_response.body + assert 'content' in response.sdk_http_response.body + assert 'parts' in response.sdk_http_response.body + assert 'usageMetadata' in response.sdk_http_response.body + + +def test_sync_stream(client): + response = client.models.generate_content_stream( + model=GEMINI_FLASH_LATEST, + contents='Tell me a story in 300 words.', + config={ + 'http_options': test_http_options, + }, + ) + chunks = 0 + for part in response: + chunks += 1 + assert part.text is not None or part.candidates[0].finish_reason + + assert chunks >= 1 + + +def test_sync_stream_with_should_return_http_headers(client): + response = client.models.generate_content_stream( + model=GEMINI_FLASH_LATEST, + contents='Tell me a story in 300 words.', + config={ + 'http_options': test_http_options, + }, + ) + chunks = 0 + for part in response: + chunks += 1 + assert part.text is not None or part.candidates[0].finish_reason + assert part.sdk_http_response.headers is not None + assert chunks >= 1 + + +def test_sync_stream_with_non_text_modality(client): + response = client.models.generate_content_stream( + model='gemini-2.0-flash-preview-image-generation', + contents=( + 'Generate an image of the Eiffel tower with fireworks in the' + ' background.' + ), + config={ + 'response_modalities': ['IMAGE', 'TEXT'], + }, + ) + chunks = 0 + for chunk in response: + chunks += 1 + if chunk.candidates[0].finish_reason is not None: + continue + for part in chunk.parts: + assert part.text is not None or part.inline_data is not None + + assert chunks >= 1 + + +@pytest.mark.asyncio +async def test_async_stream(client): + chunks = 0 + async for part in await client.aio.models.generate_content_stream( + model=GEMINI_FLASH_LATEST, contents='Tell me a story in 300 words.', + config={ + 'http_options': test_http_options, + }, + ): + chunks += 1 + assert part.text is not None or part.candidates[0].finish_reason + + assert chunks >= 1 + + +@pytest.mark.asyncio +async def test_async_stream_with_headers(client): + chunks = 0 + async for part in await client.aio.models.generate_content_stream( + model=GEMINI_FLASH_LATEST, contents='Tell me a story in 300 words.', + config={ + 'http_options': test_http_options, + }, + ): + chunks += 1 + assert part.text is not None or part.candidates[0].finish_reason + assert part.sdk_http_response.headers is not None + + assert chunks >= 1 + + +@pytest.mark.asyncio +async def test_async_stream_with_non_text_modality(client): + chunks = 0 + async for chunk in await client.aio.models.generate_content_stream( + model=GEMINI_FLASH_IMAGE_LATEST, + contents=( + 'Generate an image of the Eiffel tower with fireworks in the' + ' background.' + ), + config={ + 'response_modalities': ['IMAGE', 'TEXT'], + }, + ): + chunks += 1 + if chunk.candidates[0].finish_reason is not None: + continue + for part in chunk.parts: + assert part.text is not None or part.inline_data is not None + + assert chunks >= 1 + + +def test_simple_shared_generation_config_stream(client): + chunks = 0 + for chunk in client.models.generate_content_stream( + model=GEMINI_FLASH_LATEST, + contents='tell me a story in 300 words', + config={ + 'max_output_tokens': 1000, + 'top_k': 2, + 'temperature': 0.5, + 'top_p': 0.5, + 'response_mime_type': 'application/json', + 'stop_sequences': ['\n'], + 'seed': 42, + }, + ): + chunks += 1 + assert ( + chunk.text is not None or chunk.candidates[0].finish_reason + ), f'vertexai: {client._api_client.vertexai}, {chunk.candidate[0]}' + assert chunks >= 1 + + +@pytest.mark.asyncio +async def test_simple_shared_generation_config_async(client): + response = await client.aio.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='tell me a story in 300 words', + config={ + 'max_output_tokens': 4000, + 'top_k': 2, + 'temperature': 0.5, + 'top_p': 0.5, + 'response_mime_type': 'application/json', + 'stop_sequences': ['\n'], + 'seed': 42, + }, + ) + + +@pytest.mark.asyncio +async def test_simple_shared_generation_config_stream_async(client): + chunks = 0 + async for part in await client.aio.models.generate_content_stream( + model=GEMINI_FLASH_2_0, + contents='tell me a story in 300 words', + config={ + 'max_output_tokens': 400, + 'top_k': 2, + 'temperature': 0.5, + 'top_p': 0.5, + 'response_mime_type': 'application/json', + 'stop_sequences': ['\n'], + 'seed': 42, + }, + ): + chunks += 1 + assert part.text is not None or part.candidates[0].finish_reason + assert chunks >= 1 + + +def test_log_probs(client): + client.models.generate_content( + model=GEMINI_FLASH_2_0, + contents='What is your name?', + config={ + 'logprobs': 2, + 'presence_penalty': 0.5, + 'frequency_penalty': 0.5, + 'response_logprobs': True, + }, + ) + + +def test_simple_config(client): + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='What is your name?', + config={ + 'max_output_tokens': 300, + 'top_k': 2, + }, + ) + assert response.text + + +def test_model_selection_config_dict(client): + if not client.vertexai: + return + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Give me a Taylor Swift lyric and explain its meaning.', + config={ + 'model_selection_config': { + 'feature_selection_preference': 'PRIORITIZE_COST' + } + }, + ) + assert response.text + + +def test_model_selection_config_pydantic(client): + if not client.vertexai: + return + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Give me a Taylor Swift lyric and explain its meaning.', + config=types.GenerateContentConfig( + model_selection_config=types.ModelSelectionConfig( + feature_selection_preference=types.FeatureSelectionPreference.PRIORITIZE_QUALITY + ) + ), + ) + assert response.text + + +def test_sdk_logger_logs_warnings_once(client, caplog): + from ... import types as types_module + + types_module._response_text_warning_logged = False + + caplog.set_level(logging.WARNING, logger='google_genai.types') + + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Tell me a 50 word story about cheese.', + config={ + 'candidate_count': 2, + } + ) + assert response.text + assert 'WARNING' in caplog.text + assert 'there are 2 candidates' in caplog.text + caplog_after_first_call = caplog.text + assert len(caplog.records) == 1 + client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Tell me a 50 word story about cheese.', + config={ + 'candidate_count': 2, + } + ) + assert caplog.text == caplog_after_first_call + assert len(caplog.records) == 1 + + +def test_response_create_time_and_response_id(client): + if client.vertexai: + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='What is your name?', + config={ + 'max_output_tokens': 300, + 'top_k': 2, + }, + ) + # create_time and response_id are not supported in mldev + assert response.create_time + assert response.response_id + assert isinstance(response.create_time, datetime) + + +def test_safety_settings(client): + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='What is your name?', + config={ + 'safety_settings': [{ + 'category': 'HARM_CATEGORY_HATE_SPEECH', + 'threshold': 'BLOCK_ONLY_HIGH', + }] + }, + ) + assert response.text + + +def test_safety_settings_on_difference_stream(client): + safety_settings = [ + { + 'category': 'HARM_CATEGORY_HATE_SPEECH', + 'threshold': 'BLOCK_ONLY_HIGH', + 'method': 'SEVERITY', + }, + { + 'category': 'HARM_CATEGORY_DANGEROUS_CONTENT', + 'threshold': 'BLOCK_LOW_AND_ABOVE', + 'method': 'PROBABILITY', + }, + ] + if client._api_client.vertexai: + for part in client.models.generate_content_stream( + model=GEMINI_FLASH_LATEST, + contents='What is your name?', + config={ + 'safety_settings': safety_settings, + }, + ): + pass + else: + with pytest.raises(ValueError) as e: + for part in client.models.generate_content_stream( + model=GEMINI_FLASH_LATEST, + contents='What is your name?', + config={ + 'safety_settings': safety_settings, + }, + ): + pass + assert 'method' in str(e) + + +def test_safety_settings_on_difference_stream_with_lower_enum(client): + safety_settings = [ + { + 'category': 'harm_category_hate_speech', + 'threshold': 'block_only_high', + 'method': 'severity', + }, + { + 'category': 'harm_category_dangerous_content', + 'threshold': 'block_low_and_above', + 'method': 'probability', + }, + ] + if client._api_client.vertexai: + for part in client.models.generate_content_stream( + model=GEMINI_FLASH_LATEST, + contents='What is your name?', + config={ + 'safety_settings': safety_settings, + }, + ): + pass + else: + with pytest.raises(ValueError) as e: + for part in client.models.generate_content_stream( + model=GEMINI_FLASH_LATEST, + contents='What is your name?', + config={ + 'safety_settings': safety_settings, + }, + ): + pass + assert 'method' in str(e) + + +def test_pydantic_schema(client): + class CountryInfo(BaseModel): + # We need at least one test with `title` in properties in case the schema + # edits go wrong. + title: str + population: int + capital: str + continent: str + gdp: int + official_language: str + total_area_sq_mi: int + + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Give me information of the United States.', + config={ + 'response_mime_type': 'application/json', + 'response_schema': CountryInfo, + }, + ) + assert isinstance(response.parsed, CountryInfo) + +def test_json_schema_fields(client): + class UserRole(str, Enum): + ADMIN = "admin" + VIEWER = "viewer" + class Address(BaseModel): + street: str + city: str + class UserProfile(BaseModel): + username: str = Field(description="User's unique name") + age: Optional[int] = Field(ge=0, le=20) + roles: Set[UserRole] = Field(min_items=1) + contact: Union[Address, str] + + model_config = ConfigDict( + title="User Schema", description="A user profile" + ) # This is the title of the schema + + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Give me information of the United States.', + config={ + 'response_mime_type': 'application/json', + 'response_json_schema': UserProfile.model_json_schema(), + }, + ) + print(response.parsed) + assert response.parsed != None + + +def test_pydantic_schema_orders_properties(client): + class Restaurant(BaseModel): + name: str + rating: int + fun_fact: str + + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Give me information about a restaurant in Boston.', + config={ + 'response_mime_type': 'application/json', + 'response_schema': Restaurant, + }, + ) + response_text_json = json.loads(response.text) + response_keys = list(response_text_json.keys()) + assert response_keys[0] == 'name' + assert response_keys == list(Restaurant.model_fields.keys()) + + +def test_pydantic_schema_with_default_value(client): + class Restaurant(BaseModel): + name: str + rating: int = 0 + city: Optional[str] = 'New York' + + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Can you recommend a restaurant for me?', + config={ + 'response_mime_type': 'application/json', + 'response_schema': Restaurant, + }, + ) + assert isinstance(response.parsed, Restaurant) + + +def test_repeated_pydantic_schema(client): + # This tests the defs handling on the pydantic side. + class Person(BaseModel): + name: str + + class Relationship(BaseModel): + relationship: str + person1: Person + person2: Person + + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Create a couple.', + config={ + 'response_mime_type': 'application/json', + 'response_schema': Relationship, + }, + ) + assert isinstance(response.parsed, Relationship) + + +def test_int_schema(client): + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents="what's your favorite number?", + config={ + 'response_mime_type': 'application/json', + 'response_schema': int, + }, + ) + assert isinstance(response.parsed, int) + + +def test_nested_list_of_int_schema(client): + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents="Can you return two matrices, a 2x3 and a 3x4?", + config={ + 'response_mime_type': 'application/json', + 'response_schema': list[list[list[int]]], + }, + ) + assert isinstance(response.parsed[0][0][0], int) + + +def test_literal_schema(client): + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Which ice cream flavor should I order?', + config={ + 'response_mime_type': 'application/json', + 'response_schema': Literal['chocolate', 'vanilla', 'cookie dough'], + }, + ) + + allowed_values = ['chocolate', 'vanilla', 'cookie dough'] + assert isinstance(response.parsed, str) + assert response.parsed in allowed_values + + +def test_literal_schema_with_non_string_types_raises(client): + with pytest.raises(ValueError) as e: + client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Which ice cream flavor should I order?', + config={ + 'response_mime_type': 'application/json', + 'response_schema': Literal['chocolate', 'vanilla', 1], + }, + ) + assert 'validation error' in str(e) + + +@pytest.mark.skipif( + sys.version_info < (3, 10), + reason='| is not supported in Python 3.9', +) +def test_pydantic_schema_with_literal(client): + class Movie(BaseModel): + name: str + genre: Literal['action', 'comedy', 'drama'] + + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Give me information about the movie "Mean Girls"', + config={ + 'response_mime_type': 'application/json', + 'response_schema': Movie, + }, + ) + assert isinstance(response.parsed, Movie) + assert isinstance(response.parsed.genre, str) + assert response.parsed.genre in ['action', 'comedy', 'drama'] + + +@pytest.mark.skipif( + sys.version_info < (3, 10), + reason='| is not supported in Python 3.9', +) +def test_pydantic_schema_with_single_value_literal(client): + class Movie(BaseModel): + name: str + genre: Literal['action'] + + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Give me information about the movie "The Matrix"', + config={ + 'response_mime_type': 'application/json', + 'response_schema': Movie, + }, + ) + assert isinstance(response.parsed, Movie) + assert response.parsed.genre == 'action' + + +@pytest.mark.skipif( + sys.version_info < (3, 10), + reason='| is not supported in Python 3.9', +) +def test_pydantic_schema_with_none(client): + class CountryInfo(BaseModel): + name: str + total_area_sq_mi: int | None = None + + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Give me information of the United States.', + config={ + 'response_mime_type': 'application/json', + 'response_schema': CountryInfo, + }, + ) + assert isinstance(response.parsed, CountryInfo) + assert type(response.parsed.total_area_sq_mi) in [int, None] + + +def test_pydantic_schema_with_optional_none(client): + class CountryInfo(BaseModel): + name: str + total_area_sq_mi: Optional[int] = None + + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Give me information of the United States but don\'t include the total area.', + config={ + 'response_mime_type': 'application/json', + 'response_schema': CountryInfo, + }, + ) + assert isinstance(response.parsed, CountryInfo) + assert response.parsed.total_area_sq_mi is None + + +def test_pydantic_schema_from_json(client): + class CountryInfo(BaseModel): + name: str + pupulation: int + capital: str + continent: str + gdp: int + official_language: str + total_area_sq_mi: int + + schema = types.Schema.model_validate(CountryInfo.model_json_schema()) + + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Give me information of the United States.', + config=types.GenerateContentConfig( + response_mime_type='application/json', + response_schema=schema, + ), + ) + + assert response.text + + +@pytest.mark.skipif( + sys.version_info < (3, 10), + reason='| is not supported in Python 3.9', +) +def test_schema_with_union_type(client): + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Give me a random number, either as an integers or written out as words.', + config=types.GenerateContentConfig.model_validate(dict( + response_mime_type='application/json', + response_schema=int | str, + )) + ) + assert type(response.parsed) in (int, str) + + +def test_schema_with_union_type_all_py_versions(client): + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents="Give me a random number, either an integer or a float.", + config={ + 'response_mime_type': 'application/json', + 'response_schema': Union[int, float], + }, + ) + assert type(response.parsed) in (int, float) + + +@pytest.mark.skipif( + sys.version_info < (3, 10), + reason='| is not supported in Python 3.9', +) +def test_list_schema_with_union_type(client): + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Give me a list of 5 random numbers, including some integers and some written out as words.', + config=types.GenerateContentConfig( + response_mime_type='application/json', + response_schema=list[int | str], + ) + ) + for item in response.parsed: + assert isinstance(item, int) or isinstance(item, str) + + +def test_list_schema_with_union_type_all_py_versions(client): + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Give me a list of 5 random numbers, including some integers and some written out as words.', + config=types.GenerateContentConfig( + response_mime_type='application/json', + response_schema=list[Union[int, str]], + ) + ) + for item in response.parsed: + assert isinstance(item, int) or isinstance(item, str) + + +def test_pydantic_schema_with_optional_generic_alias(client): + class CountryInfo(BaseModel): + name: str + population: int + capital: str + continent: str + gdp: int + official_languages: Optional[List[str]] + total_area_sq_mi: int + + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Give me information of the United States.', + config={ + 'response_mime_type': 'application/json', + 'response_schema': CountryInfo, + }, + ) + assert isinstance(response.parsed, CountryInfo) + assert isinstance(response.parsed.official_languages, list) or response.parsed.official_languages is None + + +def test_pydantic_schema_with_optional_pydantic(client): + class TestPerson(BaseModel): + first_name: Optional[str] = Field( + description='First name of the person', default=None + ) + last_name: Optional[str] = Field( + description='Last name of the person', default=None + ) + + class TestDocument(BaseModel): + case_number: Optional[str] = Field( + description='Case number assigned to the claim', default=None + ) + filed_by: Optional[TestPerson] = Field( + description='Name of the party that filed or submitted the statement', + default=None, + ) + + test_prompt = """ + Carefully examine the following document and extract the metadata. + Be sure to include the party that filed the document. + + Document Text: + -------------- + Case Number: 20-12345 + File by: John Doe + """ + + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents=test_prompt, + config={ + 'response_mime_type': 'application/json', + 'response_schema': TestDocument, + }, + ) + assert isinstance(response.parsed, TestDocument) + assert isinstance(response.parsed.filed_by, TestPerson) + + +def test_list_of_pydantic_schema(client): + class CountryInfo(BaseModel): + name: str + population: int + capital: str + continent: str + gdp: int + official_language: str + total_area_sq_mi: int + + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Give me information for the United States, Canada, and Mexico.', + config=types.GenerateContentConfig( + response_mime_type='application/json', + response_schema=list[CountryInfo], + ) + ) + assert isinstance(response.parsed, list) + assert len(response.parsed) == 3 + assert isinstance(response.parsed[0], CountryInfo) + + +def test_nested_list_of_pydantic_schema(client): + class Recipe(BaseModel): + name: str + cook_time: str + + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents="I\'m writing three recipe books, one each for United States, Canada, and Mexico. " + "Can you give some recipe ideas, at least 2 per book?", + config=types.GenerateContentConfig( + response_mime_type='application/json', + response_schema=list[list[Recipe]], + ) + ) + assert isinstance(response.parsed, list) + assert len(response.parsed) == 3 + assert isinstance(response.parsed[0][0], Recipe) + + +def test_list_of_pydantic_schema_with_dict_config(client): + class CountryInfo(BaseModel): + name: str + population: int + capital: str + continent: str + gdp: int + official_language: str + total_area_sq_mi: int + + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Give me information for the United States, Canada, and Mexico.', + config={ + 'response_mime_type': 'application/json', + 'response_schema': list[CountryInfo], + } + ) + assert isinstance(response.parsed, list) + assert len(response.parsed) == 3 + assert isinstance(response.parsed[0], CountryInfo) + + +def test_pydantic_schema_with_nested_class(client): + class CurrencyInfo(BaseModel): + name: str + + class CountryInfo(BaseModel): + name: str + currency: CurrencyInfo + + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Give me information for the United States', + config=types.GenerateContentConfig( + response_mime_type='application/json', + response_schema=CountryInfo, + ) + ) + assert isinstance(response.parsed, CountryInfo) + assert isinstance(response.parsed.currency, CurrencyInfo) + + +@pytest.mark.skipif( + sys.version_info < (3, 10), + reason='| is not supported in Python 3.9', +) +def test_pydantic_schema_with_union_type(client): + + class CountryInfo(BaseModel): + name: str + restaurants_per_capita: int | float + + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Give me information for the United States', + config=types.GenerateContentConfig( + response_mime_type='application/json', + response_schema=CountryInfo, + ) + ) + assert isinstance(response.parsed, CountryInfo) + assert type(response.parsed.restaurants_per_capita) in (int, float) + + +def test_pydantic_schema_with_union_type_all_py_versions(client): + + class CountryInfo(BaseModel): + name: str + restaurants_per_capita: Union[int, float] + + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Give me information for the United States', + config=types.GenerateContentConfig( + response_mime_type='application/json', + response_schema=CountryInfo, + ) + ) + assert isinstance(response.parsed, CountryInfo) + assert type(response.parsed.restaurants_per_capita) in (int, float) + + +@pytest.mark.skipif( + sys.version_info < (3, 10), + reason='| is not supported in Python 3.9', +) +def test_union_of_pydantic_schema(client): + + class SongLyric(BaseModel): + song_name: str + lyric: str + artist: str + + class FunFact(BaseModel): + fun_fact: str + + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Can you give me a Taylor Swift song lyric or a fun fact?', + config=types.GenerateContentConfig( + response_mime_type='application/json', + response_schema=SongLyric | FunFact, + ) + ) + assert type(response.parsed) in (SongLyric, FunFact) + + +def test_union_of_pydantic_schema_all_py_versions(client): + + class SongLyric(BaseModel): + song_name: str + lyric: str + artist: str + + class FunFact(BaseModel): + fun_fact: str + + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Can you give me a Taylor Swift song lyric or a fun fact?', + config=types.GenerateContentConfig( + response_mime_type='application/json', + response_schema=Union[SongLyric, FunFact], + ) + ) + assert type(response.parsed) in (SongLyric, FunFact) + + +def test_pydantic_schema_with_nested_enum(client): + class Continent(Enum): + ASIA = 'Asia' + AFRICA = 'Africa' + ANTARCTICA = 'Antarctica' + EUROPE = 'Europe' + NORTH_AMERICA = 'North America' + SOUTH_AMERICA = 'South America' + AUSTRALIA = 'Australia' + + class CountryInfo(BaseModel): + name: str + continent: Continent + + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Give me information for the United States', + config=types.GenerateContentConfig( + response_mime_type='application/json', + response_schema=CountryInfo, + ) + ) + assert isinstance(response.parsed, CountryInfo) + assert isinstance(response.parsed.continent, Continent) + + +def test_pydantic_schema_with_nested_list_class(client): + class CurrencyInfo(BaseModel): + name: str + + class CountryInfo(BaseModel): + name: str + currency: list[CurrencyInfo] + + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Give me information for the United States.', + config=types.GenerateContentConfig( + response_mime_type='application/json', + response_schema=CountryInfo, + ) + ) + assert isinstance(response.parsed, CountryInfo) + assert isinstance(response.parsed.currency[0], CurrencyInfo) + + +def test_list_of_pydantic_schema_with_nested_class(client): + class CurrencyInfo(BaseModel): + name: str + code: str + symbol: str + + class CountryInfo(BaseModel): + name: str + population: int + capital: str + continent: str + gdp: int + official_language: str + total_area_sq_mi: int + currency: CurrencyInfo + + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Give me information for the United States, Canada, and Mexico.', + config=types.GenerateContentConfig( + response_mime_type='application/json', + response_schema=list[CountryInfo], + ) + ) + assert isinstance(response.parsed, list) + assert isinstance(response.parsed[0], CountryInfo) + assert isinstance(response.parsed[0].currency, CurrencyInfo) + + +def test_list_of_pydantic_schema_with_nested_list_class(client): + class CurrencyInfo(BaseModel): + name: str + code: str + symbol: str + + class CountryInfo(BaseModel): + name: str + population: int + capital: str + continent: str + gdp: int + official_language: str + total_area_sq_mi: int + currency: list[CurrencyInfo] + + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Give me information for the United States, Canada, and Mexico.', + config=types.GenerateContentConfig( + response_mime_type='application/json', + response_schema=list[CountryInfo], + ) + ) + assert isinstance(response.parsed, list) + assert isinstance(response.parsed[0], CountryInfo) + assert isinstance(response.parsed[0].currency, list) + assert isinstance(response.parsed[0].currency[0], CurrencyInfo) + + +def test_response_schema_with_dict_of_pydantic_schema(client): + class CountryInfo(BaseModel): + population: int + capital: str + continent: str + gdp: int + official_language: str + total_area_sq_mi: int + + if not client.vertexai: + with pytest.raises(ValueError) as e: + client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Give me information for the United States, Canada, and Mexico.', + config=types.GenerateContentConfig( + response_mime_type='application/json', + response_schema=dict[str, CountryInfo], + ) + ) + else: + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Give me information for the United States, Canada, and Mexico.', + config=types.GenerateContentConfig( + response_mime_type='application/json', + response_schema=dict[str, CountryInfo], + ) + ) + assert response.text + + +def test_schema_with_unsupported_type_raises(client): + with pytest.raises(ValueError) as e: + client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Give me information for the United States, Canada, and Mexico.', + config=types.GenerateContentConfig( + response_mime_type='application/json', + response_schema=types.Schema(), + ) + ) + assert 'Unsupported schema type' in str(e) + + +def test_enum_schema_with_enum_mime_type(client): + response = client.models.generate_content( + model=GEMINI_FLASH_2_0, + contents='What instrument plays multiple notes at once?', + config={ + 'response_mime_type': 'text/x.enum', + 'response_schema': InstrumentEnum, + }, + ) + + instrument_values = {member.value for member in InstrumentEnum} + + assert response.text in instrument_values + assert isinstance(response.parsed, InstrumentEnum) + + +def test_list_of_enum_schema_with_enum_mime_type(client): + with pytest.raises(errors.ClientError) as e: + client.models.generate_content( + model=GEMINI_FLASH_2_0, + contents='What instrument plays single note at once?', + config={ + 'response_mime_type': 'text/x.enum', + 'response_schema': list[InstrumentEnum], + }, + ) + assert '400' in str(e) + + +def test_list_of_enum_schema_with_json_mime_type(client): + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='What instrument plays single note at once?', + config={ + 'response_mime_type': 'application/json', + 'response_schema': list[InstrumentEnum], + }, + ) + + assert isinstance(response.parsed, list) + assert response.parsed + for item in response.parsed: + assert isinstance(item, InstrumentEnum) + + +def test_optional_enum_in_pydantic_schema_with_json_mime_type(client): + class InstrumentInfo(BaseModel): + instrument: Optional[InstrumentEnum] + fun_fact: str + + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='What instrument plays single note at once? Include the name of the instrument in your response.', + config={ + 'response_mime_type': 'application/json', + 'response_schema': InstrumentInfo, + }, + ) + + assert isinstance(response.parsed, InstrumentInfo) + assert isinstance(response.parsed.instrument, InstrumentEnum) + + +def test_enum_schema_with_json_mime_type(client): + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='What instrument plays multiple notes at once?', + config={ + 'response_mime_type': 'application/json', + 'response_schema': InstrumentEnum, + }, + ) + # "application/json" returns response in double quotes. + removed_quotes = response.text.replace('"', '') + instrument_values = {member.value for member in InstrumentEnum} + + assert removed_quotes in instrument_values + assert isinstance(response.parsed, InstrumentEnum) + + +def test_non_string_enum_schema_with_enum_mime_type(client): + class IntegerEnum(Enum): + PERCUSSION = 1 + STRING = 2 + WOODWIND = 3 + BRASS = 4 + KEYBOARD = 5 + + response =client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='What instrument plays multiple notes at once?', + config={ + 'response_mime_type': 'text/x.enum', + 'response_schema': IntegerEnum, + }, + ) + + instrument_values = {str(member.value) for member in IntegerEnum} + + assert response.text in instrument_values + + +def test_json_schema(client): + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Give me information of the United States.', + config={ + 'response_mime_type': 'application/json', + 'response_schema': { + 'required': [ + 'name', + 'population', + 'capital', + 'continent', + 'gdp', + 'official_language', + 'total_area_sq_mi', + ], + 'properties': { + 'name': {'type': 'STRING'}, + 'population': {'type': 'INTEGER'}, + 'capital': {'type': 'STRING'}, + 'continent': {'type': 'STRING'}, + 'gdp': {'type': 'INTEGER'}, + 'official_language': {'type': 'STRING'}, + 'total_area_sq_mi': {'type': 'INTEGER'}, + }, + 'type': 'OBJECT', + }, + }, + ) + assert isinstance(response.parsed, dict) + + +def test_json_schema_with_lower_enum(client): + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Give me information of the United States.', + config={ + 'response_mime_type': 'application/json', + 'response_schema': { + 'required': [ + 'name', + 'pupulation', + 'capital', + 'continent', + 'gdp', + 'official_language', + 'total_area_sq_mi', + ], + 'properties': { + 'name': {'type': 'string'}, + 'pupulation': {'type': 'integer'}, + 'capital': {'type': 'string'}, + 'continent': {'type': 'string'}, + 'gdp': {'type': 'integer'}, + 'official_language': {'type': 'string'}, + 'total_area_sq_mi': {'type': 'integer'}, + }, + 'type': 'OBJECT', + }, + }, + ) + assert isinstance(response.parsed, dict) + + +def test_json_schema_with_any_of(client): + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Give me a fruit basket.', + config={ + 'response_mime_type': 'application/json', + 'response_schema': { + 'type': 'OBJECT', + 'title': 'Fruit Basket', + 'description': 'A structured representation of a fruit basket', + 'required': ['fruit'], + 'properties': { + 'fruit': { + 'type': 'ARRAY', + 'description': ( + 'An ordered list of the fruit in the basket' + ), + 'items': { + 'description': 'A piece of fruit', + 'any_of': [ + { + 'title': 'Apple', + 'description': 'Describes an apple', + 'type': 'OBJECT', + 'properties': { + 'type': { + 'type': 'STRING', + 'description': "Always 'apple'", + }, + 'color': { + 'type': 'STRING', + 'description': ( + 'The color of the apple (e.g.,' + " 'red')" + ), + }, + }, + 'property_ordering': ['type', 'color'], + 'required': ['type', 'color'], + }, + { + 'title': 'Orange', + 'description': 'Describes an orange', + 'type': 'OBJECT', + 'properties': { + 'type': { + 'type': 'STRING', + 'description': "Always 'orange'", + }, + 'size': { + 'type': 'STRING', + 'description': ( + 'The size of the orange (e.g.,' + " 'medium')" + ), + }, + }, + 'property_ordering': ['type', 'size'], + 'required': ['type', 'size'], + }, + ], + }, + } + }, + }, + }, + ) + assert isinstance(response.parsed, dict) + assert 'fruit' in response.parsed + assert isinstance(response.parsed['fruit'], list) + assert 'type' in response.parsed['fruit'][0] + + +def test_schema_with_any_of(client): + response_schema=types.Schema( + type=types.Type.OBJECT, + title='Fruit Basket', + description='A structured representation of a fruit basket', + properties={ + 'fruit': types.Schema( + type=types.Type.ARRAY, + description='An ordered list of the fruit in the basket', + items=types.Schema( + any_of=[ + types.Schema( + title='Apple', + description='Describes an apple', + type=types.Type.OBJECT, + properties={ + 'type': types.Schema(type=types.Type.STRING, description='Always "apple"'), + 'variety': types.Schema( + type=types.Type.STRING, + description='The variety of apple (e.g., "Granny Smith")', + ), + }, + property_ordering=['type', 'variety'], + required=['type', 'variety'], + ), + types.Schema( + title='Orange', + description='Describes an orange', + type=types.Type.OBJECT, + properties={ + 'type': types.Schema(type=types.Type.STRING, description='Always "orange"'), + 'variety': types.Schema( + type=types.Type.STRING, + description='The variety of orange (e.g.,"Navel orange")', + ), + }, + property_ordering=['type', 'variety'], + required=['type', 'variety'], + ), + ], + ), + ), + }, + required=['fruit'], + ) + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Give me a fruit basket.', + config=types.GenerateContentConfig( + response_mime_type='application/json', + response_schema=response_schema, + ), + ) + assert isinstance(response.parsed, dict) + assert 'fruit' in response.parsed + assert isinstance(response.parsed['fruit'], list) + assert 'type' in response.parsed['fruit'][0] + + +def test_replicated_voice_config(client): + with pytest_helper.exception_if_vertex(client, errors.ClientError): + client.models.generate_content( + model='gemini-2.5-flash-preview-tts-voice-replication-rev22-2025-10-28', + contents=t.t_contents( + 'Produce a speech response saying "Cheese"' + ), + config=types.GenerateContentConfig( + response_modalities=['audio'], + speech_config=types.SpeechConfig( + voice_config=types.VoiceConfig( + replicated_voice_config=types.ReplicatedVoiceConfig( + voice_sample_audio=audio_bytes, + mime_type='audio/wav', + ) + ) + ), + ), + ) + + +def test_json_schema_with_streaming(client): + + response = client.models.generate_content_stream( + model=GEMINI_FLASH_LATEST, + contents='Give me information of the United States.', + config={ + 'response_mime_type': 'application/json', + 'response_schema': { + 'properties': { + 'name': {'type': 'STRING'}, + 'population': {'type': 'INTEGER'}, + 'capital': {'type': 'STRING'}, + 'continent': {'type': 'STRING'}, + 'gdp': {'type': 'INTEGER'}, + 'official_language': {'type': 'STRING'}, + 'total_area_sq_mi': {'type': 'INTEGER'}, + }, + 'type': 'OBJECT', + }, + }, + ) + + for r in response: + parts = r.parts + for p in parts: + assert p.text + + +def test_pydantic_schema_with_streaming(client): + + class CountryInfo(BaseModel): + name: str + population: int + capital: str + continent: str + gdp: int + official_language: str + total_area_sq_mi: int + + response = client.models.generate_content_stream( + model=GEMINI_FLASH_LATEST, + contents='Give me information of the United States.', + config={ + 'response_mime_type': 'application/json', + 'response_schema': CountryInfo + }, + ) + + for r in response: + parts = r.parts + for p in parts: + assert p.text + + +def test_schema_from_json(client): + + class Foo(BaseModel): + bar: str + baz: int + qux: list[str] + + schema = types.Schema.model_validate(Foo.model_json_schema()) + + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Fill in the Foo.', + config=types.GenerateContentConfig( + response_mime_type='application/json', + response_schema=schema + ), + ) + + assert response.text + + +def test_schema_from_model_schema(client): + + class Foo(BaseModel): + bar: str + baz: int + qux: list[str] + + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='Fill in the Foo.', + config=types.GenerateContentConfig( + response_mime_type='application/json', + response_schema=Foo.model_json_schema(), + ), + ) + + response.text + + +def test_schema_with_additional_properties(client): + + class Foo(BaseModel): + bar: str + baz: int + qux: dict[str, str] + + if client.vertexai: + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='What is your name?', + config=types.GenerateContentConfig( + response_mime_type='application/json', + response_schema=Foo, + ), + ) + assert response.text + else: + with pytest.raises(ValueError) as e: + client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='What is your name?', + config=types.GenerateContentConfig( + response_mime_type='application/json', + response_schema=Foo, + ), + ) + assert 'additionalProperties is not supported in the Gemini API.' in str(e) + + +def test_function(client): + def get_weather(city: str) -> str: + """Returns the weather in a city.""" + return f'The weather in {city} is sunny and 100 degrees.' + + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents=( + 'What is the weather like in Sunnyvale? Answer in very short' + ' sentence.' + ), + config={ + 'tools': [get_weather], + }, + ) + assert '100' in response.text + + +def test_invalid_input_without_transformer(client): + with pytest.raises(ValidationError) as e: + client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='What is your name', + config={ + 'input_that_does_not_exist': 'what_ever_value', + }, + ) + assert 'input_that_does_not_exist' in str(e) + assert 'Extra inputs are not permitted' in str(e) + + +def test_invalid_input_with_transformer_dict(client): + with pytest.raises(ValidationError) as e: + client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents={'invalid_key': 'invalid_value'}, + ) + assert 'invalid_key' in str(e.value) + + +def test_invalid_input_with_transformer_list(client): + with pytest.raises(ValidationError) as e: + client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents=[{'invalid_key': 'invalid_value'}], + ) + assert 'invalid_key' in str(e.value) + + +def test_invalid_input_for_simple_parameter(client): + with pytest.raises(ValidationError) as e: + client.models.generate_content( + model=5, + contents='What is your name?', + ) + assert 'model' in str(e) + + +def test_catch_stack_trace_in_error_handling(client): + try: + client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='What is your name?', + config={'response_modalities': ['AUDIO']}, + ) + except errors.ClientError as e: + # Note that the stack trace is truncated in replay file, therefore this is + # the best we can do in testing error handling. In api mode, the stack trace + # is: + # { + # 'error': { + # 'code': 400, + # 'message': 'Multi-modal output is not supported.', + # 'status': 'INVALID_ARGUMENT', + # 'details': [{ + # '@type': 'type.googleapis.com/google.rpc.DebugInfo', + # 'detail': '[ORIGINAL ERROR] generic::invalid_argument: ' + # 'Multi-modal output is not supported. ' + # '[google.rpc.error_details_ext] ' + # '{ message: "Multi-modal output is not supported." }' + # }] + # } + # } + if 'error' in e.details: + details = e.details['error'] + else: + details = e.details + assert details['code'] == 400 + assert details['status'] == 'INVALID_ARGUMENT' + + +def test_multiple_strings(client): + class SummaryResponses(BaseModel): + summary: str + person: str + + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents=[ + "Summarize Shakespeare's life work in a few sentences", + "Summarize Hemingway's life work", + ], + config={ + 'response_mime_type': 'application/json', + 'response_schema': list[SummaryResponses], + }, + ) + + assert 'Shakespeare' in response.text + assert 'Hemingway' in response.text + assert 'Shakespeare' in response.parsed[0].person + assert 'Hemingway' in response.parsed[1].person + + +def test_multiple_parts(client): + class SummaryResponses(BaseModel): + summary: str + person: str + + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents=[ + types.Part( + text="Summarize Shakespeare's life work in a few sentences" + ), + types.Part(text="Summarize Hemingway's life work"), + ], + config={ + 'response_mime_type': 'application/json', + 'response_schema': list[SummaryResponses], + }, + ) + + assert 'Shakespeare' in response.text + assert 'Hemingway' in response.text + assert 'Shakespeare' in response.parsed[0].person + assert 'Hemingway' in response.parsed[1].person + + +def test_multiple_function_calls(client): + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents=[ + 'What is the weather in Boston?', + 'What is the stock price of GOOG?', + types.Part.from_function_call( + name='get_weather', + args={'location': 'Boston'}, + ), + types.Part.from_function_call( + name='get_stock_price', + args={'symbol': 'GOOG'}, + ), + types.Part.from_function_response( + name='get_weather', + response={'response': 'It is sunny and 100 degrees.'}, + ), + types.Part.from_function_response( + name='get_stock_price', + response={'response': 'The stock price is $100.'}, + ), + ], + config=types.GenerateContentConfig( + tools=[ + types.Tool( + function_declarations=[ + types.FunctionDeclaration( + name='get_weather', + description='Get the weather in a city.', + parameters=types.Schema( + type=types.Type.OBJECT, + properties={ + 'location': types.Schema( + type=types.Type.STRING + ) + }, + ), + ), + types.FunctionDeclaration( + name='get_stock_price', + description='Get the stock price of a symbol.', + parameters=types.Schema( + type=types.Type.OBJECT, + properties={ + 'symbol': types.Schema( + type=types.Type.STRING + ) + }, + ), + ), + ] + ), + ] + ), + ) + + assert 'Boston' in response.text + assert 'sunny' in response.text + assert '100 degrees' in response.text + assert '$100' in response.text + + +def test_usage_metadata_part_types(client): + contents = [ + 'Hello world.', + types.Part.from_bytes( + data=image_bytes, + mime_type='image/png', + ), + ] + + response = client.models.generate_content( + model=GEMINI_FLASH_2_0, contents=contents + ) + usage_metadata = response.usage_metadata + + assert usage_metadata.candidates_token_count + assert usage_metadata.candidates_tokens_details + modalities = sorted( + [d.modality.name for d in usage_metadata.candidates_tokens_details] + ) + assert modalities == ['TEXT'] + assert isinstance( + usage_metadata.candidates_tokens_details[0].modality, types.MediaModality) + + assert usage_metadata.prompt_token_count + assert usage_metadata.prompt_tokens_details + modalities = sorted( + [d.modality.name for d in usage_metadata.prompt_tokens_details] + ) + assert modalities == ['IMAGE', 'TEXT'] + + +def test_error_handling_stream(client): + if client.vertexai: + return + + try: + for chunk in client.models.generate_content_stream( + model=GEMINI_FLASH_IMAGE_LATEST, + contents=[ + types.Content( + role='user', + parts=[ + types.Part.from_bytes( + data=image_bytes, mime_type='image/png' + ), + types.Part.from_text(text='Make sky more beautiful.'), + ], + ), + ], + config=types.GenerateContentConfig( + response_mime_type='text/plain', + response_modalities=['IMAGE', 'TEXT'], + system_instruction='make the sky more beautiful.', + ), + ): + continue + + except errors.ClientError as e: + assert ( + e.message + == 'Developer instruction is not enabled for' + ' models/gemini-2.5-flash-image' + ) + + +def test_error_handling_unary(client): + if client.vertexai: + return + + try: + client.models.generate_content( + model=GEMINI_FLASH_IMAGE_LATEST, + contents=[ + types.Content( + role='user', + parts=[ + types.Part.from_bytes( + data=image_bytes, mime_type='image/png' + ), + types.Part.from_text(text='Make sky more beautiful.'), + ], + ), + ], + config=types.GenerateContentConfig( + response_mime_type='text/plain', + response_modalities=['IMAGE', 'TEXT'], + system_instruction='make the sky more beautiful.', + ), + ) + + except errors.ClientError as e: + assert ( + e.message + == 'Developer instruction is not enabled for' + ' models/gemini-2.5-flash-image' + ) + + +def test_provisioned_output_dedicated(client): + response = client.models.generate_content( + model=GEMINI_FLASH_LATEST, + contents='What is 1 + 1?', + config=types.GenerateContentConfig( + http_options={'headers': {'X-Vertex-AI-LLM-Request-Type': 'dedicated'}} + ), + ) + if client.vertexai: + assert response.usage_metadata.traffic_type == types.TrafficType.PROVISIONED_THROUGHPUT + else: + assert not response.usage_metadata.traffic_type + + +@pytest.mark.asyncio +async def test_error_handling_unary_async(client): + if client.vertexai: + return + + try: + await client.aio.models.generate_content( + model=GEMINI_FLASH_IMAGE_LATEST, + contents=[ + types.Content( + role='user', + parts=[ + types.Part.from_bytes( + data=image_bytes, mime_type='image/png' + ), + types.Part.from_text(text='Make sky more beautiful.'), + ], + ), + ], + config=types.GenerateContentConfig( + response_mime_type='text/plain', + response_modalities=['IMAGE', 'TEXT'], + system_instruction='make the sky more beautiful.', + ), + ) + + except errors.ClientError as e: + assert ( + e.message + == 'Developer instruction is not enabled for' + ' models/gemini-2.5-flash-image' + ) + + +@pytest.mark.asyncio +async def test_error_handling_stream_async(client): + if client.vertexai: + return + + try: + async for part in await client.aio.models.generate_content_stream( + model=GEMINI_FLASH_IMAGE_LATEST, + contents=[ + types.Content( + role='user', + parts=[ + types.Part.from_bytes( + data=image_bytes, mime_type='image/png' + ), + types.Part.from_text(text='Make sky more beautiful.'), + ], + ), + ], + config=types.GenerateContentConfig( + response_mime_type='text/plain', + response_modalities=['IMAGE', 'TEXT'], + system_instruction='make the sky more beautiful.', + ), + ): + continue + + except errors.ClientError as e: + assert ('Developer instruction is not enabled' in e.message) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_content_cached_content.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_content_cached_content.py new file mode 100644 index 0000000000000000000000000000000000000000..a2a2747d1b7a6c20396b895b8af0e7045dae7214 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_content_cached_content.py @@ -0,0 +1,132 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +from ... import _transformers as t +from ... import types +from .. import pytest_helper + +VERTEX_CACHED_CONTENT_NAME = '8163416782997028864' +MLDEV_CACHED_CONTENT_NAME = 'idv6zldt3p2f1lbm31vn41tx2ld42qngpcnka2s3' + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_cached_content_wrong_name', + exception_if_vertex='INVALID_ARGUMENT', + exception_if_mldev='INVALID_ARGUMENT', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=t.t_contents('What is in these docs?'), + config={ + 'cached_content': 'batchPredictionJobs/123', + }, + ), + ), + pytest_helper.TestTableItem( + name='test_cached_content_partial_vertex_resource_name_0', + exception_if_mldev='INVALID_ARGUMENT', + skip_in_api_mode=( + 'CachedContent API has expiration and permission issues' + ), + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=t.t_contents('What is in these docs?'), + config={ + 'cached_content': f'locations/us-central1/cachedContents/{VERTEX_CACHED_CONTENT_NAME}', + }, + ), + ), + pytest_helper.TestTableItem( + name='test_cached_content_partial_vertex_resource_name_1', + exception_if_mldev='PERMISSION_DENIED', + skip_in_api_mode=( + 'CachedContent API has expiration and permission issues' + ), + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=t.t_contents('What is in these docs?'), + config={ + 'cached_content': ( + f'cachedContents/{VERTEX_CACHED_CONTENT_NAME}' + ), + }, + ), + ), + pytest_helper.TestTableItem( + name='test_cached_content_partial_vertex_resource_name_2', + exception_if_mldev='PERMISSION_DENIED', + skip_in_api_mode=( + 'CachedContent API has expiration and permission issues' + ), + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=t.t_contents('What is in these docs?'), + config={ + 'cached_content': VERTEX_CACHED_CONTENT_NAME, + }, + ), + ), + pytest_helper.TestTableItem( + name='test_cached_content_partial_mldev_resource_name_1', + exception_if_vertex='NOT_FOUND', + skip_in_api_mode=( + 'CachedContent API has expiration and permission issues' + ), + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=t.t_contents('What is in these docs?'), + config={ + 'cached_content': f'{MLDEV_CACHED_CONTENT_NAME}', + }, + ), + ), + pytest_helper.TestTableItem( + name='test_cached_content_for_vertex', + exception_if_mldev='INVALID_ARGUMENT', + skip_in_api_mode=( + 'CachedContent API has expiration and permission issues' + ), + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=t.t_contents('What is in these docs?'), + config={ + 'cached_content': f'projects/964831358985/locations/us-central1/cachedContents/{VERTEX_CACHED_CONTENT_NAME}', + }, + ), + ), + pytest_helper.TestTableItem( + name='test_cached_content_for_mldev', + exception_if_vertex='NOT_FOUND', + skip_in_api_mode=( + 'CachedContent API has expiration and permission issues' + ), + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=t.t_contents('Tell me a story in 300 words.'), + config={ + 'cached_content': f'cachedContents/{MLDEV_CACHED_CONTENT_NAME}', + }, + ), + ), +] + + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='models.generate_content', + test_table=test_table, +) +pytest_plugins = ('pytest_asyncio',) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_content_config_zero_value.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_content_config_zero_value.py new file mode 100644 index 0000000000000000000000000000000000000000..eefd3caca21a3250dcb3178316321c93f72fd63a --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_content_config_zero_value.py @@ -0,0 +1,103 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +from pydantic import BaseModel, ValidationError +import pytest +from ... import _transformers as t +from ... import errors +from ... import types +from .. import pytest_helper + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_candidate_count_zero', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=t.t_contents('What is your name?'), + config={ + 'candidate_count': 0, + }, + ), + exception_if_mldev='400' + ), + pytest_helper.TestTableItem( + name='test_max_output_tokens_zero', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=t.t_contents('What is your name?'), + config={ + 'max_output_tokens': 0, + }, + ), + exception_if_vertex='400', + exception_if_mldev='400', + ), + pytest_helper.TestTableItem( + name='test_logprobs_zero', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=t.t_contents('What is your name?'), + config={ + 'logprobs': 0, + }, + ), + exception_if_mldev='response_logprobs is true', + exception_if_vertex='setting response_logprobs to be true', + skip_in_api_mode='it will encounter 400 for api mode', + ), + pytest_helper.TestTableItem( + name='test_logprobs_zero_with_response_logprobs_true', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=t.t_contents('What is your name?'), + config={ + 'response_logprobs': True, + 'logprobs': 0, + }, + ), + exception_if_mldev=( + 'Logprobs is not enabled for models/gemini-2.5-flash' + ), + ), + pytest_helper.TestTableItem( + name='test_presence_penalty_zero', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=t.t_contents('What is your name?'), + config={ + 'presence_penalty': 0, + }, + ), + ), + pytest_helper.TestTableItem( + name='test_frequency_penalty_zero', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=t.t_contents('What is your name?'), + config={ + 'frequency_penalty': 0, + }, + ), + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='models.generate_content', + test_table=test_table, +) +pytest_plugins = ('pytest_asyncio',) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_content_from_apikey.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_content_from_apikey.py new file mode 100644 index 0000000000000000000000000000000000000000..74ba82e6cdc247e5726041c662c8d4024c71fd22 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_content_from_apikey.py @@ -0,0 +1,44 @@ +import pytest +from .. import pytest_helper + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='models.generate_content', +) + + +def test_simple_request(client): + # TODO(b/388917450): Add Vertex AI in Express mode test suite + client._api_client.project = None + client._api_client.location = None + + # To record a replay file, replace with api key (from Vertex AI Express). + # API mode will not work if the API key is a ML Dev API key. + # After recording, change the string back to 'key'. + client._api_client._http_options.headers['x-goog-api-key'] = 'key' + if not client._api_client.vertexai: + return + response = client.models.generate_content( + model='gemini-2.0-flash-001', contents='Tell me a joke.' + ) + assert response.text + + +def test_simple_request_stream(client): + # TODO(b/388917450): Add Vertex AI in Express mode test suite + client._api_client.project = None + client._api_client.location = None + + # To record a replay file, replace with api key (from Vertex AI Express). + # API mode will not work if the API key is a ML Dev API key. + # After recording, change the string back to 'key'. + client._api_client._http_options.headers['x-goog-api-key'] = 'key' + if not client._api_client.vertexai: + return + + response = client.models.generate_content_stream( + model='gemini-2.0-flash-001', contents='Tell me a joke.' + ) + + assert any(chunk.text for chunk in response) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_content_http_options.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_content_http_options.py new file mode 100644 index 0000000000000000000000000000000000000000..85d3410878362f754b745195f7822302092e272a --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_content_http_options.py @@ -0,0 +1,40 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +from ... import _transformers as t +from ... import types +from .. import pytest_helper + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_generate_content_with_http_options', + parameters=types._GenerateContentParameters( + model='models/gemini-2.5-flash', + contents=t.t_contents('how are you doing?'), + ), + exception_if_vertex='404', + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='models.generate_content', + test_table=test_table, + http_options={ + 'api_version': 'v1alpha', + }, +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_content_image_generation.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_content_image_generation.py new file mode 100644 index 0000000000000000000000000000000000000000..9a9288018da2ae947324077ce047f6346a7e8438 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_content_image_generation.py @@ -0,0 +1,143 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +import pydantic +import pytest + +from ... import _api_client +from ... import _transformers as t +from ... import errors +from ... import types +from .. import pytest_helper + + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_image_generation_config', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash-image', + contents=t.t_contents('A photorealistic red apple on a table.'), + config=types.GenerateContentConfig( + response_modalities=['IMAGE'], + image_config=types.ImageConfig( + aspect_ratio='16:9', + ) + ), + ), + ), + pytest_helper.TestTableItem( + name='test_image_generation_config_output_mime_type', + exception_if_mldev='not supported in Gemini API', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash-image', + contents=t.t_contents('A photorealistic red apple on a table.'), + config=types.GenerateContentConfig( + response_modalities=['IMAGE'], + image_config=types.ImageConfig( + aspect_ratio='16:9', + output_mime_type='image/jpeg', + ) + ), + ), + ), + pytest_helper.TestTableItem( + name='test_image_generation_config_output_compression_quality', + exception_if_mldev='not supported in Gemini API', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash-image', + contents=t.t_contents('A photorealistic red apple on a table.'), + config=types.GenerateContentConfig( + response_modalities=['IMAGE'], + image_config=types.ImageConfig( + aspect_ratio='16:9', + output_compression_quality=80, + ) + ), + ), + ), + pytest_helper.TestTableItem( + name='test_image_generation_filtered', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash-image', + contents=t.t_contents('Make a zombie anime style'), + config=types.GenerateContentConfig( + response_modalities=['IMAGE'], + image_config=types.ImageConfig( + aspect_ratio='16:9', + ) + ), + ), + ), + pytest_helper.TestTableItem( + name='test_image_generation_no_image', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash-image', + contents=t.t_contents('What is your name?'), + config=types.GenerateContentConfig( + response_modalities=['IMAGE'], + image_config=types.ImageConfig( + aspect_ratio='16:9', + ) + ), + ), + ), + pytest_helper.TestTableItem( + name='test_image_generation_config_validation_none', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash-image', + contents=t.t_contents('A photorealistic red apple on a table.'), + config=types.GenerateContentConfig( + response_modalities=['IMAGE'], + image_config=None + ), + ), + ), +] + + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='models.generate_content', + test_table=test_table, +) + + +def test_image_generation_wrong_config(client): + with pytest.raises(pydantic.ValidationError): + client.models.generate_content( + model='gemini-2.5-flash-image', + contents=t.t_contents('A photorealistic red apple on a table.'), + config=types.GenerateContentConfig( + response_modalities=['IMAGE'], + image_config=types.GenerateImagesConfig( + aspect_ratio='16:9', + number_of_images=1, + ) + ), + ) + + +def test_image_generation_validation_model_dump(client): + config = types.GenerateContentConfig( + response_modalities=['IMAGE'], + ) + + class Foo(pydantic.BaseModel): + value: types.GenerateContentConfig + + f = Foo(value=config) + in_memory = f.model_dump(mode='json') + Foo.model_validate(in_memory) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_content_mcp.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_content_mcp.py new file mode 100644 index 0000000000000000000000000000000000000000..233186e88315e24037efe0d900daa365362357a5 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_content_mcp.py @@ -0,0 +1,343 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +from typing import Any +import pytest +from ... import _transformers as t +from ... import errors +from ... import types +from .. import pytest_helper + +try: + from mcp import types as mcp_types + from mcp import ClientSession as McpClientSession +except ImportError as e: + import sys + + if sys.version_info < (3, 10): + raise ImportError( + 'MCP Tool requires Python 3.10 or above. Please upgrade your Python' + ' version.' + ) from e + else: + raise e + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='models.generate_content', +) + + +# Cannot be included in test_table because MCP integration is only supported +# in the Python SDK. +@pytest.mark.asyncio +async def test_mcp_tools_async(client): + response = await client.aio.models.generate_content( + model='gemini-2.5-flash', + contents=t.t_contents('What is the weather in Boston?'), + config={ + 'tools': [ + mcp_types.Tool( + name='get_weather', + description='Get the weather in a city.', + inputSchema={ + 'type': 'object', + 'properties': {'location': {'type': 'string'}}, + }, + ) + ], + }, + ) + assert response.function_calls == [ + types.FunctionCall( + name='get_weather', + args={'location': 'Boston'}, + ) + ] + + +@pytest.mark.asyncio +async def test_mcp_tools_with_custom_headers_async(client): + config = { + 'http_options': { + 'headers': { + 'x-goog-api-client': 'google-genai-sdk/1.0.0 gl-python/1.0.0', + }, + }, + 'tools': [ + mcp_types.Tool( + name='get_weather', + description='Get the weather in a city.', + inputSchema={ + 'type': 'object', + 'properties': {'location': {'type': 'string'}}, + }, + ) + ], + } + response = await client.aio.models.generate_content( + model='gemini-2.5-flash', + contents=t.t_contents('What is the weather in Boston?'), + config=config, + ) + assert response.function_calls == [ + types.FunctionCall( + name='get_weather', + args={'location': 'Boston'}, + ) + ] + # Assert config is not modified. + assert config['http_options']['headers'] == { + 'x-goog-api-client': 'google-genai-sdk/1.0.0 gl-python/1.0.0' + } + + +@pytest.mark.asyncio +async def test_mcp_tools_subsequent_calls_async(client): + class MockMcpClientSession(McpClientSession): + + def __init__(self): + self._read_stream = None + self._write_stream = None + + async def list_tools(self): + return mcp_types.ListToolsResult( + tools=[ + mcp_types.Tool( + name='get_weather', + description='Get the weather in a city.', + inputSchema={ + 'type': 'object', + 'properties': {'location': {'type': 'string'}}, + }, + ), + mcp_types.Tool( + name='add_numbers', + description='Add two numbers together.', + inputSchema={ + 'type': 'object', + 'properties': { + 'a': {'type': 'number'}, + 'b': {'type': 'number'}, + }, + }, + ), + ] + ) + + async def call_tool( + self, + name: str, + arguments: dict[str, Any], + ): + if name == 'get_weather': + return mcp_types.CallToolResult( + content=[mcp_types.TextContent(type='text', text='Sunny')] + ) + else: + return mcp_types.CallToolResult( + content=[mcp_types.TextContent(type='text', text='100')] + ) + + config = { + 'tools': [MockMcpClientSession()], + } + + response = await client.aio.models.generate_content( + model='gemini-2.5-flash', + contents=t.t_contents('What is the weather in Boston?'), + config=config, + ) + assert 'sunny' in response.text.lower() + + response_2 = await client.aio.models.generate_content( + model='gemini-2.5-flash', + contents=t.t_contents('What is 50 + 50?'), + config=config, + ) + assert '100' in response_2.text + + +@pytest.mark.asyncio +async def test_mcp_tools_duplicate_tool_name_raises_error(client): + class MockMcpClientSession(McpClientSession): + + def __init__(self): + self._read_stream = None + self._write_stream = None + + async def list_tools(self): + return mcp_types.ListToolsResult( + tools=[ + mcp_types.Tool( + name='get_weather', + description='Get the weather in a city.', + inputSchema={ + 'type': 'object', + 'properties': {'location': {'type': 'string'}}, + }, + ), + mcp_types.Tool( + name='get_weather', + description='Different tool to get the weather.', + inputSchema={ + 'type': 'object', + 'properties': {'location': {'type': 'string'}}, + }, + ), + ] + ) + + with pytest.raises(ValueError): + await client.aio.models.generate_content( + model='gemini-2.5-flash', + contents=t.t_contents('What is the weather in Boston?'), + config={ + 'tools': [MockMcpClientSession()], + }, + ) + + +def test_mcp_tools_synchronous_call(client): + response = client.models.generate_content( + model='gemini-2.5-flash', + contents=t.t_contents('What is the weather in Boston?'), + config={ + 'tools': [ + mcp_types.Tool( + name='get_weather', + description='Get the weather in a city.', + inputSchema={ + 'type': 'object', + 'properties': {'location': {'type': 'string'}}, + }, + ) + ] + }, + ) + assert response.function_calls == [ + types.FunctionCall( + name='get_weather', + args={'location': 'Boston'}, + ) + ] + + +def test_mcp_session_synchronous_call_raises_error(client): + class MockMcpClientSession(McpClientSession): + + def __init__(self): + self._read_stream = None + self._write_stream = None + + async def list_tools(self): + return mcp_types.ListToolsResult( + tools=[ + mcp_types.Tool( + name='get_weather', + description='Get the weather in a city.', + inputSchema={ + 'type': 'object', + 'properties': {'location': {'type': 'string'}}, + }, + ), + mcp_types.Tool( + name='get_weather', + description='Different tool to get the weather.', + inputSchema={ + 'type': 'object', + 'properties': {'location': {'type': 'string'}}, + }, + ), + ] + ) + + with pytest.raises(errors.UnsupportedFunctionError): + client.models.generate_content( + model='gemini-2.5-flash', + contents=t.t_contents('What is the weather in Boston?'), + config={ + 'tools': [MockMcpClientSession()], + }, + ) + + +def test_mcp_tools_synchronous_stream_call(client): + response = client.models.generate_content_stream( + model='gemini-2.5-flash', + contents=t.t_contents('What is the weather in Boston?'), + config={ + 'tools': [ + mcp_types.Tool( + name='get_weather', + description='Get the weather in a city.', + inputSchema={ + 'type': 'object', + 'properties': {'location': {'type': 'string'}}, + }, + ) + ] + }, + ) + for chunk in response: + assert chunk.function_calls == [ + types.FunctionCall( + name='get_weather', + args={'location': 'Boston'}, + ) + ] + + +def test_mcp_session_synchronous_stream_call_raises_error(client): + class MockMcpClientSession(McpClientSession): + + def __init__(self): + self._read_stream = None + self._write_stream = None + + async def list_tools(self): + return mcp_types.ListToolsResult( + tools=[ + mcp_types.Tool( + name='get_weather', + description='Get the weather in a city.', + inputSchema={ + 'type': 'object', + 'properties': {'location': {'type': 'string'}}, + }, + ), + mcp_types.Tool( + name='get_weather', + description='Different tool to get the weather.', + inputSchema={ + 'type': 'object', + 'properties': {'location': {'type': 'string'}}, + }, + ), + ] + ) + + response = client.models.generate_content_stream( + model='gemini-2.5-flash', + contents=t.t_contents('What is the weather in Boston?'), + config={ + 'tools': [MockMcpClientSession()], + }, + ) + + with pytest.raises(errors.UnsupportedFunctionError): + for chunk in response: + pass diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_content_media_resolution.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_content_media_resolution.py new file mode 100644 index 0000000000000000000000000000000000000000..b9006105a60ed569187094c9d89aa759928b7dfe --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_content_media_resolution.py @@ -0,0 +1,97 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +from ... import types +from .. import pytest_helper + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_video_audio_uri_with_media_resolution', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=[ + types.Content( + role='user', + parts=[ + types.Part.from_text( + text=( + 'Is the audio related to the video? ' + 'If so, how? ' + 'What are the common themes? ' + 'What are the different emphases?' + ) + ) + ], + ), + types.Content( + role='user', + parts=[ + types.Part.from_uri( + file_uri='gs://cloud-samples-data/generative-ai/video/pixel8.mp4', + mime_type='video/mp4', + ) + ], + ), + types.Content( + role='user', + parts=[ + types.Part.from_uri( + file_uri='gs://cloud-samples-data/generative-ai/audio/pixel.mp3', + mime_type='audio/mpeg', + ) + ], + ), + ], + config={ + 'system_instruction': types.Content( + role='user', + parts=[ + types.Part.from_text( + text=( + 'you are a helpful assistant for people with ' + 'visual and hearing disabilities.' + ) + ) + ], + ), + 'media_resolution': 'MEDIA_RESOLUTION_LOW', + }, + ), + exception_if_mldev='400', + ) +] + + +def test_low_media_resolution(client): + with pytest_helper.exception_if_vertex(client, ValueError): + file = client.files.upload(file='tests/data/google.png') + response = client.models.generate_content( + model='gemini-2.5-flash', + contents=[file, 'Describe the image.'], + config=types.GenerateContentConfig( + media_resolution='MEDIA_RESOLUTION_LOW', + http_options= types.HttpOptions(api_version='v1alpha', base_url='https://generativelanguage.googleapis.com') + ), + ) + assert response.text + + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='models.generate_content', + test_table=test_table, +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_content_model.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_content_model.py new file mode 100644 index 0000000000000000000000000000000000000000..a77fdc581d553c2280f9a5d7ceed33a69d9cc08f --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_content_model.py @@ -0,0 +1,139 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +import pytest + +from ... import _transformers as t +from ... import errors +from ... import types +from .. import pytest_helper + +tuned_model_endpoint = ( + 'projects/801452371447/locations/us-central1/endpoints/4095574160837705728' +) + + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_tuned_model', + parameters=types._GenerateContentParameters( + model=tuned_model_endpoint, + contents=t.t_contents('Tell me a story in 300 words.'), + ), + exception_if_mldev='404', + ), + pytest_helper.TestTableItem( + name='test_start_with_publishers', + parameters=types._GenerateContentParameters( + model='publishers/google/models/gemini-2.5-flash', + contents=t.t_contents('Tell me a story in 50 words.'), + ), + exception_if_mldev='404', + ), + pytest_helper.TestTableItem( + name='test_start_with_models', + parameters=types._GenerateContentParameters( + model='models/gemini-2.5-flash', + contents=t.t_contents('Tell me a story in 50 words.'), + ), + exception_if_vertex='404', + ), + pytest_helper.TestTableItem( + name='test_publisher_model', + parameters=types._GenerateContentParameters( + model='google/gemini-2.5-flash', + contents=t.t_contents('Tell me a story in 50 words.'), + ), + exception_if_mldev='404', + ), + pytest_helper.TestTableItem( + name='test_empty_model', + parameters=types._GenerateContentParameters( + model='', + contents=t.t_contents('Tell me a story in 50 words.'), + ), + exception_if_mldev='model', + exception_if_vertex='model', + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='models.generate_content', + test_table=test_table, +) +pytest_plugins = ('pytest_asyncio',) + + +def test_tuned_model_stream(client): + # Vertex AI endpoints is not supported in MLDev. + with pytest_helper.exception_if_mldev(client, errors.ClientError): + chunks = 0 + for chunk in client.models.generate_content_stream( + model=tuned_model_endpoint, + contents='Tell me a story in 300 words.', + ): + chunks += 1 + assert chunk.text is not None or chunk.candidates[0].finish_reason + assert chunks >= 2 + + +def test_start_with_models_stream(client): + # vertex ai require publishers/ prefix for gemini + with pytest_helper.exception_if_vertex(client, errors.ClientError): + chunks = 0 + for chunk in client.models.generate_content_stream( + model='models/gemini-2.5-flash', + contents='Tell me a story in 50 words.', + ): + chunks += 1 + assert chunk.text is not None or chunk.candidates[0].finish_reason + assert chunks >= 2 + + +def test_models_stream_with_non_empty_last_chunk(client): + chunks = list( + client.models.generate_content_stream( + model='gemini-2.5-flash', + contents='Tell me a story in 300 words.', + ) + ) + assert chunks[-1].text + + +@pytest.mark.asyncio +async def test_start_with_models_stream_async(client): + # vertex ai require publishers/ prefix for gemini + with pytest_helper.exception_if_vertex(client, errors.ClientError): + chunks = 0 + async for chunk in await client.aio.models.generate_content_stream( + model='models/gemini-2.5-flash', + contents='Tell me a story in 300 words.', + ): + chunks += 1 + assert chunk.text is not None or chunk.candidates[0].finish_reason + assert chunks > 2 + + +@pytest.mark.asyncio +async def test_start_with_models_async(client): + # vertex ai require publishers/ prefix for gemini + with pytest_helper.exception_if_vertex(client, errors.ClientError): + await client.aio.models.generate_content( + model='models/gemini-2.5-flash', + contents='Tell me a story in 50 words.', + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_content_multi_regional.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_content_multi_regional.py new file mode 100644 index 0000000000000000000000000000000000000000..c43b5eb5e2c9eb2d495fc41a4775863c0f55e1d2 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_content_multi_regional.py @@ -0,0 +1,76 @@ +# Copyright 2026 Google LLC +# +# Licensed 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. +# + +import os + +import pytest + +from ... import _replay_api_client +from ... import Client +from ...models import Models +from .. import pytest_helper + + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='models.generate_content', +) + + +def test_eu_location_routing_prediction_replay(client, request, monkeypatch): + """Tests that the SDK can route to the EU multi-regional endpoint.""" + if not client._api_client.vertexai: + pytest.skip('Test requires Vertex AI') + + mode = request.config.getoption('--mode') + if mode == 'tap': + mode = 'replay' + + # The `client` fixture monkeypatches `Client._get_api_client` to always return + # the fixture's client, which binds to `us-central1` via the environment. + # To test `eu` routing, we bypass the mock by explicitly instantiating a + # ReplayApiClient and injecting it. + with monkeypatch.context() as m: + m.delenv('GOOGLE_CLOUD_LOCATION', raising=False) + + replay_api_client = _replay_api_client.ReplayApiClient( + mode=mode, + replay_id='tests/models/generate_content_multi_regional/test_eu_location_routing_prediction_replay.vertex', + replays_directory=os.environ.get('GOOGLE_GENAI_REPLAYS_DIRECTORY'), + vertexai=True, + project=client._api_client.project, + location='eu', + ) + + eu_client = Client(vertexai=True) + eu_client._api_client = replay_api_client + eu_client._models = Models(replay_api_client) + + try: + # 1. Verify that the SDK correctly resolved the EU REP base URL internally + assert ( + eu_client._api_client._http_options.base_url + == 'https://aiplatform.eu.rep.googleapis.com/' + ) + + # 2. Test the dataplane prediction (generate_content) against EU endpoint + response = eu_client.models.generate_content( + model='gemini-3-flash-preview', + contents='Testing EU multi-regional endpoint routing.', + ) + assert response is not None + finally: + eu_client.close() diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_content_part.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_content_part.py new file mode 100644 index 0000000000000000000000000000000000000000..446b3ac4f93b27dfbbc91383a8e683017d96168c --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_content_part.py @@ -0,0 +1,821 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for generate_content_part.""" + +import base64 +import os + +from pydantic import ValidationError +import pytest + +from ... import _transformers as t +from ... import errors +from ... import types +from .. import pytest_helper + + +IMAGE_PNG_FILE_PATH = os.path.abspath( + os.path.join(os.path.dirname(__file__), '../data/google.png') +) +IMAGE_JPEG_FILE_PATH = os.path.abspath( + os.path.join(os.path.dirname(__file__), '../data/google.jpg') +) +APPLICATION_PDF_FILE_PATH = os.path.abspath( + os.path.join(os.path.dirname(__file__), '../data/story.pdf') +) +VIDEO_MP4_FILE_PATH = os.path.abspath( + os.path.join(os.path.dirname(__file__), '../data/animal.mp4') +) +AUDIO_MP3_FILE_PATH = os.path.abspath( + os.path.join(os.path.dirname(__file__), '../data/pixel.m4a') +) +with open(IMAGE_PNG_FILE_PATH, 'rb') as image_file: + image_bytes = image_file.read() + image_string = base64.b64encode(image_bytes).decode('utf-8') +with open(APPLICATION_PDF_FILE_PATH, 'rb') as pdf_file: + pdf_bytes = pdf_file.read() +with open(VIDEO_MP4_FILE_PATH, 'rb') as video_file: + video_bytes = video_file.read() +with open(AUDIO_MP3_FILE_PATH, 'rb') as audio_file: + audio_bytes = audio_file.read() + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_image_uri', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=[ + t.t_content('What is this image about?'), + t.t_content( + { + 'role': 'user', + 'parts': [ + types.PartDict({ + 'file_data': { + 'file_uri': ( + 'gs://generativeai-downloads/images/scones.jpg' + ), + 'mime_type': 'image/jpeg', + } + }) + ], + }, + ), + ], + ), + exception_if_mldev='400', + ), + pytest_helper.TestTableItem( + name='test_external_file_uri', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=[ + t.t_content('What is this image about?'), + t.t_content( + { + 'role': 'user', + 'parts': [ + types.PartDict({ + 'file_data': { + 'file_uri': ( + 'https://storage.googleapis.com/cloud-samples-data/generative-ai/image/scones.jpg' + ), + 'mime_type': 'image/jpeg', + } + }) + ], + }, + ), + ], + ), + exception_if_mldev='400', + ), + pytest_helper.TestTableItem( + name='test_image_png_file_uri', + skip_in_api_mode=( + 'Name of the file is hardcoded, only supporting replay mode.' + ), + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=[ + t.t_content('What is this image about?'), + t.t_content( + { + 'role': 'user', + 'parts': [ + types.PartDict({ + 'file_data': { + 'file_uri': ( + 'https://generativelanguage.googleapis.com/v1beta/files/864z7ft4m14h' + ), + 'mime_type': 'image/png', + } + }) + ], + }, + ), + ], + ), + exception_if_vertex='403', + ), + pytest_helper.TestTableItem( + name='test_image_jpg_file_uri', + skip_in_api_mode=( + 'Name of the file is hardcoded, only supporting replay mode.' + ), + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=[ + t.t_content('What is this image about?'), + t.t_content( + { + 'role': 'user', + 'parts': [ + types.PartDict({ + 'file_data': { + 'file_uri': ( + 'https://generativelanguage.googleapis.com/v1beta/files/22xab9a8jp0v' + ), + 'mime_type': 'image/jpeg', + } + }) + ], + }, + ), + ], + ), + exception_if_vertex='403', + ), + pytest_helper.TestTableItem( + name='test_image_inline_part_media_resolution', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=[ + t.t_content('What is this image about?'), + t.t_content( + { + 'role': 'user', + 'parts': [ + types.Part( + inline_data=types.Blob( + data=image_string, mime_type='image/png' + ), + media_resolution={'level': 'MEDIA_RESOLUTION_LOW'} + ) + ], + }, + ), + ], + ), + ), + pytest_helper.TestTableItem( + name='test_application_pdf_file_uri', + skip_in_api_mode=( + 'Name of the file is hardcoded, only supporting replay mode.' + ), + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=[ + t.t_content( + 'Summarize the pdf in concise and professional tone.' + ), + t.t_content( + { + 'role': 'user', + 'parts': [ + types.PartDict({ + 'file_data': { + 'file_uri': ( + 'https://generativelanguage.googleapis.com/v1beta/files/9tnpjy0re13a' + ), + 'mime_type': 'application/pdf', + } + }) + ], + }, + ), + ], + ), + exception_if_vertex='403', + ), + pytest_helper.TestTableItem( + name='test_video_mp4_file_uri', + skip_in_api_mode=( + 'Name of the file is hardcoded, only supporting replay mode.' + ), + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=[ + t.t_content( + """ + summarize the video in concise and professional tone. + the summary should include all important information said in the video. + """, + ), + t.t_content( + { + 'role': 'user', + 'parts': [ + types.PartDict({ + 'file_data': { + 'file_uri': ( + 'https://generativelanguage.googleapis.com/v1beta/files/i2ojhd8z99uk' + ), + 'mime_type': 'video/mp4', + } + }) + ], + }, + ), + ], + ), + exception_if_vertex='403', + ), + pytest_helper.TestTableItem( + name='test_audio_m4a_file_uri', + skip_in_api_mode=( + 'Name of the file is hardcoded, only supporting replay mode.' + ), + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=[ + t.t_content( + """ + Provide a summary for the audio in the beginning of the transcript. + Provide concise chapter titles with timestamps. + Do not make up any information that is not part of the audio. + """, + ), + t.t_content( + { + 'role': 'user', + 'parts': [ + types.PartDict({ + 'file_data': { + 'file_uri': ( + 'https://generativelanguage.googleapis.com/v1beta/files/0o9iyit198g1' + ), + 'mime_type': 'audio/mp4', + } + }) + ], + }, + ), + ], + ), + exception_if_vertex='403', + ), + pytest_helper.TestTableItem( + name='test_mldev_video_offset_and_fps', + skip_in_api_mode=( + 'Name of the file is hardcoded, only supporting replay mode.' + ), + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=[ + types.Content( + role='user', + parts=[ + types.Part(text='summarize this video'), + types.Part( + file_data=types.FileData( + file_uri='https://generativelanguage.googleapis.com/v1beta/files/fq9r5ftyqrho', + mime_type= 'video/mp4', + ), + video_metadata=types.VideoMetadata( + start_offset='0s', + end_offset= '5s', + fps= 3, + ) + ) + ] + ), + ], + ), + exception_if_vertex='403', + ), + pytest_helper.TestTableItem( + name='test_video_gcs_file_uri', + skip_in_api_mode=( + 'Name of the file is hardcoded, only supporting replay mode.' + ), + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=[ + t.t_content('what is the video about?'), + t.t_content( + { + 'role': 'user', + 'parts': [ + types.PartDict({ + 'file_data': { + 'file_uri': ( + 'gs://generativeai-downloads/videos/Big_Buck_Bunny.mp4' + ), + 'mime_type': 'video/mp4', + }, + 'video_metadata': { + 'start_offset': '0s', + 'end_offset': '10s', + 'fps': 3, + }, + }) + ], + }, + ), + ], + ), + exception_if_mldev='400', + ), + pytest_helper.TestTableItem( + name='test_image_base64', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=[ + t.t_content('What is this image about?'), + t.t_content( + { + 'role': 'user', + 'parts': [ + types.Part( + inline_data=types.Blob( + data=image_string, mime_type='image/png' + ) + ) + ], + }, + ), + ], + ), + ), + pytest_helper.TestTableItem( + name='test_union_none_part', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=[], + ), + exception_if_mldev='contents', + exception_if_vertex='contents', + has_union=True, + ), + pytest_helper.TestTableItem( + name='test_dict_content', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=t.t_contents( + types.ContentDict( + {'role': 'user', 'parts': [{'text': 'what is your name?'}]} + ), + ), + ), + ), + pytest_helper.TestTableItem( + name='test_union_part_list', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=['What is your name?'], + ), + has_union=True, + ), +] +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='models.generate_content', + test_table=test_table, +) +pytest_plugins = ('pytest_asyncio',) + + +def test_empty_part(client): + client.models.generate_content( + model='gemini-2.5-flash', + contents=t.t_contents(['']), + ) + + +def test_none_list_part(client): + # pydantic will raise ValidationError + with pytest.raises(ValidationError): + client.models.generate_content( + model='gemini-2.5-flash', + contents=[None], + ) + + +def test_image_file(client): + client.models.generate_content( + model='gemini-2.5-flash', + contents=[ + 'What is this image about?', + {'inline_data': {'data': image_bytes, 'mimeType': 'image/png'}}, + ], + ) + + +def test_image_jpeg(client, image_jpeg): + client.models.generate_content( + model='gemini-2.5-flash', + contents=['What is this image about?', image_jpeg], + ) + + +def test_from_uri(client): + # gs://generativeai-downloads/images/scones.jpg isn't supported in MLDev + with pytest_helper.exception_if_mldev(client, errors.ClientError): + client.models.generate_content( + model='gemini-2.5-flash', + contents=[ + 'What is this image about?', + types.Part.from_uri( + file_uri='gs://generativeai-downloads/images/scones.jpg', + mime_type='image/jpeg', + ), + ], + ) + + +def test_user_content_text(client): + response = client.models.generate_content( + model='gemini-2.5-flash', + contents=types.UserContent(parts='why is the sky blue?'), + ) + assert response.text + + +def test_user_content_part(client): + with pytest_helper.exception_if_mldev(client, errors.ClientError): + response = client.models.generate_content( + model='gemini-2.5-flash', + contents=types.UserContent( + parts=[ + 'what is this image about?', + types.Part.from_uri( + file_uri='gs://generativeai-downloads/images/scones.jpg', + mime_type='image/jpeg', + ), + ] + ), + ) + assert response.text + + +def test_model_content_text(client): + with pytest_helper.exception_if_mldev(client, errors.ClientError): + response = client.models.generate_content( + model='gemini-2.5-flash', + contents=[ + types.UserContent( + parts=[ + 'what is this image about?', + types.Part.from_uri( + file_uri=( + 'gs://generativeai-downloads/images/scones.jpg' + ), + mime_type='image/jpeg', + ), + ] + ), + types.ModelContent( + parts=( + 'The image is about a cozy breakfast or brunch with' + ' blueberry scones, coffee, and fresh flowers.' + ) + ), + types.UserContent( + parts='Is this a good environment for a family gathering?' + ), + ], + ) + assert response.text + + +def test_from_file_input(client): + with pytest_helper.exception_if_vertex(client, ValueError): + file = client.files.upload(file='tests/data/story.txt') + client.models.generate_content( + model='gemini-2.5-flash', + contents=file, + ) + client.models.generate_content( + model='gemini-2.5-flash', + contents=[ + 'Summarize this file', + file, + ], + ) + client.models.generate_content( + model='gemini-2.5-flash', + contents=[['Summarize this file', file]], + ) + + +def test_from_file_dict_input(client): + with pytest_helper.exception_if_vertex(client, ValueError): + file = client.files.upload(file='tests/data/story.txt') + file_dict = file.model_dump() + client.models.generate_content( + model='gemini-2.5-flash', + contents=file_dict, + ) + client.models.generate_content( + model='gemini-2.5-flash', + contents=[ + 'Summarize this file', + file_dict, + ], + ) + client.models.generate_content( + model='gemini-2.5-flash', + contents=[['Summarize this file', file_dict]], + ) + + +def test_from_uploaded_file_uri(client): + with pytest_helper.exception_if_vertex(client, ValueError): + file = client.files.upload(file='tests/data/story.txt') + file_part = types.Part.from_uri(file_uri=file.uri, mime_type='text/plain') + client.models.generate_content( + model='gemini-2.5-flash', + contents=file_part, + ) + client.models.generate_content( + model='gemini-2.5-flash', + contents=[ + 'Summarize this file', + file_part, + ], + ) + client.models.generate_content( + model='gemini-2.5-flash', + contents=[['Summarize this file', file_part]], + ) + + +def test_from_uri_inferred_mime_type(client): + # gs://generativeai-downloads/images/scones.jpg isn't supported in MLDev + with pytest_helper.exception_if_mldev(client, errors.ClientError): + client.models.generate_content( + model='gemini-2.5-flash', + contents=[ + 'What is this image about?', + types.Part.from_uri( + file_uri='gs://generativeai-downloads/images/scones.jpg' + ), + ], + ) + + +def test_from_uri_invalid_inferred_mime_type(client): + # Throws ValueError if mime_type cannot be inferred. + with pytest.raises(ValueError): + client.models.generate_content( + model='gemini-2.5-flash', + contents=[ + 'What is this image about?', + types.Part.from_uri( + file_uri='uri/without/mime/type' + ), + ], + ) + + +def test_audio_uri(client): + with pytest_helper.exception_if_mldev(client, errors.ClientError): + client.models.generate_content( + model='gemini-2.5-flash', + contents=[ + """ + Provide a summary for the audio in the beginning of the transcript. + Provide concise chapter titles with timestamps. + Do not make up any information that is not part of the audio. + """, + types.Part.from_uri( + file_uri='gs://cloud-samples-data/generative-ai/audio/pixel.mp3', + mime_type='audio/mpeg', + ), + ], + config={ + 'system_instruction': ( + 'You are a helpful assistant for audio transcription.' + ) + }, + ) + + +def test_pdf_uri(client): + with pytest_helper.exception_if_mldev(client, errors.ClientError): + client.models.generate_content( + model='gemini-2.5-flash', + contents=[ + 'summarize the pdf in concise and professional tone', + types.Part.from_uri( + file_uri='gs://cloud-samples-data/generative-ai/pdf/2403.05530.pdf', + mime_type='application/pdf', + ), + ], + config={ + 'system_instruction': ( + 'You are a helpful assistant for academic literature review.' + ) + }, + ) + + +def test_video_uri(client): + with pytest_helper.exception_if_mldev(client, errors.ClientError): + client.models.generate_content( + model='gemini-2.5-flash', + contents=[ + """ + summarize the video in concise and professional tone. + the summary should include all important information said in the video. + """, + types.Part.from_uri( + file_uri='gs://cloud-samples-data/generative-ai/video/pixel8.mp4', + mime_type='video/mp4', + ), + ], + config={ + 'system_instruction': ( + 'you are a helpful assistant for market research.' + ) + }, + ) + + +def test_video_audio_uri(client): + with pytest_helper.exception_if_mldev(client, errors.ClientError): + client.models.generate_content( + model='gemini-2.5-flash', + contents=[ + """ + Is the audio related to the video? + If so, how? + What are the common themes? + What are the different emphases? + """, + types.Part.from_uri( + file_uri='gs://cloud-samples-data/generative-ai/video/pixel8.mp4', + mime_type='video/mp4', + ), + types.Part.from_uri( + file_uri='gs://cloud-samples-data/generative-ai/audio/pixel.mp3', + mime_type='audio/mpeg', + ), + ], + config={ + 'system_instruction': ( + 'you are a helpful assistant for people with visual and hearing' + ' disabilities.' + ) + }, + ) + + +def test_file(client): + with pytest_helper.exception_if_vertex(client, errors.ClientError): + file = types.File( + uri='https://generativelanguage.googleapis.com/v1beta/files/8q6j6weg80ey', + mime_type='text/plain', + ) + client.models.generate_content( + model='gemini-2.5-flash', + contents=[ + 'Summarize this file', + file, + ], + ) + + +def test_file_error(client): + # missing mime_type + with pytest.raises(ValueError): + file = types.File( + uri='https://generativelanguage.googleapis.com/v1beta/files/8q6j6weg80ey', + ) + client.models.generate_content( + model='gemini-2.5-flash', + contents=[ + 'Summarize this file', + file, + ], + ) + + +def test_from_text(client): + client.models.generate_content( + model='gemini-2.5-flash', + contents=[types.Part.from_text(text='What is your name?')], + ) + + +def test_from_bytes_image(client): + client.models.generate_content( + model='gemini-2.5-flash', + contents=[ + 'What is this image about?', + types.Part.from_bytes(data=image_bytes, mime_type='image/png'), + ], + ) + + +def test_from_bytes_image_dict(client): + client.models.generate_content( + model='gemini-2.5-flash', + contents=[ + {'text': 'What is this image about?'}, + {'inline_data': {'data': image_bytes, 'mimeType': 'image/png'}}, + ], + ) + + +def test_from_bytes_image_none(client): + with pytest.raises(errors.ClientError) as e: + client.models.generate_content( + model='gemini-2.5-flash', + contents=[ + {'text': 'What is this image about?'}, + {'inline_data': {'data': None, 'mimeType': 'image/png'}}, + ], + ) + assert 'INVALID_ARGUMENT' in str(e) + + +def test_from_bytes_video(client): + client.models.generate_content( + model='gemini-2.5-flash', + contents=[ + 'What is this video about?', + types.Part.from_bytes(data=video_bytes, mime_type='video/mp4'), + ], + ) + + +def test_from_bytes_audio(client): + client.models.generate_content( + model='gemini-2.5-flash', + contents=[ + 'What is this audio about?', + types.Part.from_bytes(data=audio_bytes, mime_type='audio/mpeg'), + ], + ) + + +def test_from_bytes_pdf(client): + client.models.generate_content( + model='gemini-2.5-flash', + contents=[ + 'What is this pdf about?', + types.Part.from_bytes(data=pdf_bytes, mime_type='application/pdf'), + ], + ) + + +def test_from_function_call_response(client): + function_call = types.Part.from_function_call( + name='get_weather', args={'location': 'Boston'} + ) + function_response = types.Part.from_function_response( + name='get_weather', response={'weather': 'sunny'} + ) + response = client.models.generate_content( + model='gemini-2.5-flash', + contents=[ + 'what is the weather in Boston?', + function_call, + function_response, + ], + ) + + assert 'sunny' in response.text + assert 'Boston' in response.text + + +@pytest.mark.asyncio +async def test_image_base64_stream_async(client): + async for part in await client.aio.models.generate_content_stream( + model='gemini-2.5-flash', + contents=[ + 'What is this image about?', + {'inline_data': {'data': image_string, 'mimeType': 'image/png'}}, + ], + ): + pass + + +# function_call and function_response are tested in generate_content_tools.py diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_content_thought.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_content_thought.py new file mode 100644 index 0000000000000000000000000000000000000000..70032ecbfd1290fbcc985e9e72b9c45731f98c47 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_content_thought.py @@ -0,0 +1,76 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +from ... import _api_client +from ... import _transformers as t +from ... import errors +from ... import types +from .. import pytest_helper + + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_disable_thinking', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=t.t_contents('Explain the monty hall problem.'), + config={ + 'thinking_config': { + 'thinking_budget': 0}, + }, + ), + ), + pytest_helper.TestTableItem( + name='test_thinking_level', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=t.t_contents('Explain the monty hall problem.'), + config={ + 'thinking_config': { + 'thinking_level': "LOW" + }, + }, + ), + ), +] + + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='models.generate_content', + test_table=test_table, +) + + +def test_thinking_budget(client): + response = client.models.generate_content( + model='gemini-2.5-pro', + contents='What is the sum of natural numbers from 1 to 100?', + config={ + 'thinking_config': { + 'include_thoughts': True, + 'thinking_budget': 10000, + }, + }, + ) + has_thought = False + if response.candidates: + for candidate in response.candidates: + for part in candidate.content.parts: + if part.thought: + has_thought = True + break + assert has_thought diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_content_tools.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_content_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..eb50488710d803d75b50d32731a750f362f1ee17 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_content_tools.py @@ -0,0 +1,1905 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +import collections +import logging +import os +import sys +import typing + +import pydantic +import pytest + +from ... import _transformers as t +from ... import errors +from ... import types +from .. import pytest_helper + +GOOGLE_HOMEPAGE_FILE_PATH = os.path.abspath( + os.path.join(os.path.dirname(__file__), '../data/google_homepage.png') +) +with open(GOOGLE_HOMEPAGE_FILE_PATH, 'rb') as image_file: + google_homepage_screenshot_bytes = image_file.read() + +function_declarations = [{ + 'name': 'get_current_weather', + 'description': 'Get the current weather in a city', + 'parameters': { + 'type': 'OBJECT', + 'properties': { + 'location': { + 'type': 'STRING', + 'description': 'The location to get the weather for', + }, + 'unit': { + 'type': 'STRING', + 'enum': ['C', 'F'], + }, + }, + }, +}] +computer_use_override_function_declarations = [{ + 'name': 'type_text_at', + 'description': 'Types text at a certain coordinate.', + 'parameters': { + 'type': 'OBJECT', + 'properties': { + 'y': { + 'type': 'INTEGER', + 'description': 'The y-coordinate, normalized from 0 to 1000.', + }, + 'x': { + 'type': 'INTEGER', + 'description': 'The x-coordinate, normalized from 0 to 1000.', + }, + 'press_enter': { + 'type': 'BOOLEAN', + 'description': 'Whether to press enter after typing the text.' + }, + 'text': { + 'type': 'STRING', + 'description': 'The text to type.', + }, + }, + }, +}] +function_response_parts = [ + { + 'function_response': { + 'name': 'get_current_weather', + 'response': { + 'name': 'get_current_weather', + 'content': {'weather': 'super nice'}, + }, + }, + }, +] +manual_function_calling_contents = [ + {'role': 'user', 'parts': [{'text': 'What is the weather in Boston?'}]}, + { + 'role': 'model', + 'parts': [{ + 'function_call': { + 'name': 'get_current_weather', + 'args': {'location': 'Boston'}, + } + }], + }, + {'role': 'user', 'parts': function_response_parts}, +] +computer_use_multi_turn_contents = [ + { + 'role': 'user', + 'parts': [{'text': 'Go to google and search nano banana'}], + }, + { + 'role': 'model', + 'parts': [{'function_call': {'name': 'open_web_browser', 'args': {}}}], + }, + { + 'role': 'user', + 'parts': [{ + 'function_response': { + 'name': 'open_web_browser', + 'response': { + 'url': 'http://www.google.com', + }, + 'parts': [{ + 'inline_data': { + 'data': google_homepage_screenshot_bytes, + 'mime_type': 'image/png', + } + }], + } + }], + }, +] + + +def get_weather(city: str) -> str: + return f'The weather in {city} is sunny and 100 degrees.' + + +def get_weather_declaration_only(city: str) -> str: + """Get the current weather in a given city. + + Args: + city: The city to get the weather for. + """ + pass + + +def get_stock_price(symbol: str) -> str: + if symbol == 'GOOG': + return '1000' + else: + return '100' + + +def divide_integers(a: int, b: int) -> int: + """Divide two integers.""" + return a // b + + +async def divide_floats_async(numerator: float, denominator: float) -> float: + """Divide two floats.""" + return numerator / denominator + + +def divide_floats(a: float, b: float) -> float: + """Divide two floats.""" + return a / b + + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_google_search', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=t.t_contents('Why is the sky blue?'), + config={'tools': [{'google_search': {}}]}, + ), + ), + pytest_helper.TestTableItem( + name='test_vai_search', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=t.t_contents('what is vertex ai search?'), + config={ + 'tools': [{ + 'retrieval': { + 'vertex_ai_search': { + 'datastore': ( + 'projects/vertex-sdk-dev/locations/global/collections/default_collection/dataStores/yvonne_1728691676574' + ) + } + } + }] + }, + ), + exception_if_mldev='retrieval', + ), + pytest_helper.TestTableItem( + name='test_vai_google_search', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=t.t_contents('why is the sky blue?'), + config={ + 'tools': [ + types.Tool( + retrieval=types.Retrieval( + vertex_ai_search=types.VertexAISearch( + datastore='projects/vertex-sdk-dev/locations/global/collections/default_collection/dataStores/yvonne_1728691676574' + ) + ), + google_search_retrieval=types.GoogleSearchRetrieval(), + ), + ] + }, + ), + exception_if_mldev='retrieval', + exception_if_vertex='400', + ), + pytest_helper.TestTableItem( + name='test_vai_search_engine', + parameters=types._GenerateContentParameters( + model='gemini-2.0-flash-001', + contents=t.t_contents('why is the sky blue?'), + config={ + 'tools': [ + types.Tool( + retrieval=types.Retrieval( + vertex_ai_search=types.VertexAISearch( + engine='projects/862721868538/locations/global/collections/default_collection/engines/teamfood-v11_1720671063545' + ) + ) + ), + ] + }, + ), + exception_if_mldev='retrieval', + ), + pytest_helper.TestTableItem( + name='test_rag_model_old', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=t.t_contents( + 'How much gain or loss did Google get in the Motorola Mobile' + ' deal in 2014?', + ), + config={ + 'tools': [ + types.Tool( + retrieval=types.Retrieval( + vertex_rag_store=types.VertexRagStore( + rag_resources=[ + types.VertexRagStoreRagResource( + rag_corpus='projects/964831358985/locations/us-central1/ragCorpora/3379951520341557248' + ) + ], + similarity_top_k=3, + ) + ), + ), + ] + }, + ), + exception_if_mldev='retrieval', + ), + pytest_helper.TestTableItem( + name='test_rag_model_ga', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=t.t_contents( + 'How much gain or loss did Google get in the Motorola Mobile' + ' deal in 2014?', + ), + config={ + 'tools': [ + types.Tool( + retrieval=types.Retrieval( + vertex_rag_store=types.VertexRagStore( + rag_resources=[ + types.VertexRagStoreRagResource( + rag_corpus='projects/964831358985/locations/us-central1/ragCorpora/3379951520341557248' + ) + ], + rag_retrieval_config=types.RagRetrievalConfig( + top_k=3, + filter=types.RagRetrievalConfigFilter( + vector_similarity_threshold=0.5, + ), + ), + ) + ), + ), + ] + }, + ), + exception_if_mldev='retrieval', + ), + pytest_helper.TestTableItem( + name='test_file_search', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=t.t_contents( + 'can you tell me the author of "A Survey of Modernist Poetry"?', + ), + config={ + 'tools': [ + types.Tool( + file_search=types.FileSearch( + file_search_store_names=[ + 'fileSearchStores/5en07ei3kojo-yo8sjqgvx2xf' + ] + ), + ), + ], + }, + ), + exception_if_vertex='is not supported in Vertex AI', + ), + pytest_helper.TestTableItem( + name='test_file_search_non_existent_file_search_store', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=t.t_contents( + 'can you tell me the author of "A Survey of Modernist Poetry"?', + ), + config={ + 'tools': [ + types.Tool( + file_search=types.FileSearch( + file_search_store_names=[ + 'fileSearchStores/test-non-existent-rag-store' + ], + ), + ), + ], + }, + ), + exception_if_mldev='not exist', + exception_if_vertex='is not supported in Vertex AI', + ), + pytest_helper.TestTableItem( + name='test_file_search_with_metadata_filter', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=t.t_contents( + 'can you tell me the author of "A Survey of Modernist Poetry"?', + ), + config={ + 'tools': [ + types.Tool( + file_search=types.FileSearch( + file_search_store_names=[ + 'fileSearchStores/5en07ei3kojo-yo8sjqgvx2xf' + ], + metadata_filter='tag=science', + ), + ), + ], + }, + ), + exception_if_vertex='is not supported in Vertex AI', + ), + pytest_helper.TestTableItem( + name='test_file_search_with_metadata_filter_and_top_k', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=t.t_contents( + 'can you tell me the author of "A Survey of Modernist Poetry"', + ), + config={ + 'tools': [ + types.Tool( + file_search=types.FileSearch( + file_search_store_names=[ + 'fileSearchStores/5en07ei3kojo-yo8sjqgvx2xf' + ], + metadata_filter='tag=science', + top_k=1, + ), + ), + ], + }, + ), + exception_if_vertex='is not supported in Vertex AI', + ), + pytest_helper.TestTableItem( + name='test_function_call', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=manual_function_calling_contents, + config={ + 'tools': [{'function_declarations': function_declarations}] + }, + ), + ), + pytest_helper.TestTableItem( + # TODO(b/382547236) add the test back in api mode when the code + # execution is supported. + skip_in_api_mode=( + 'Model gemini-2.5-flash-001 does not support code execution for' + ' Vertex API.' + ), + name='test_code_execution', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=t.t_contents( + 'What is the sum of the first 50 prime numbers? ' + + 'Generate and run code for the calculation, and make sure you' + ' get all 50.', + ), + config={'tools': [{'code_execution': {}}]}, + ), + ), + pytest_helper.TestTableItem( + name='test_function_google_search_with_long_lat', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=t.t_contents('what is the price of GOOG?'), + config=types.GenerateContentConfig( + tools=[ + types.Tool( + google_search=types.GoogleSearch(), + ), + ], + tool_config=types.ToolConfig( + retrieval_config=types.RetrievalConfig( + lat_lng=types.LatLngDict( + latitude=37.7749, longitude=-122.4194 + ) + ) + ), + ), + ), + ), + pytest_helper.TestTableItem( + name='test_url_context', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=t.t_contents( + 'what are the top headlines on https://news.google.com' + ), + config={'tools': [{'url_context': {}}]}, + ), + ), + pytest_helper.TestTableItem( + name='test_url_context_paywall_status', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=t.t_contents( + 'Read the content of this URL:' + ' https://unsplash.com/photos/portrait-of-an-adorable-golden-retriever-puppy-studio-shot-isolated-on-black-yRYCnnQASnc' + ), + config={'tools': [{'url_context': {}}]}, + ), + ), + pytest_helper.TestTableItem( + name='test_url_context_unsafe_status', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=t.t_contents( + 'Fetch the content of http://0k9.me/test.html' + ), + config={'tools': [{'url_context': {}}]}, + ), + ), + pytest_helper.TestTableItem( + name='test_computer_use', + parameters=types._GenerateContentParameters( + model='gemini-2.5-computer-use-preview-10-2025', + contents=t.t_contents('Go to google and search nano banana'), + config={'tools': [{'computer_use': {}}]}, + ), + exception_if_vertex='404', + ), + pytest_helper.TestTableItem( + name='test_computer_use_with_browser_environment', + parameters=types._GenerateContentParameters( + model='gemini-2.5-computer-use-preview-10-2025', + contents=t.t_contents('Go to google and search nano banana'), + config={ + 'tools': [ + {'computer_use': {'environment': 'ENVIRONMENT_BROWSER'}} + ] + }, + ), + exception_if_vertex='404', + ), + pytest_helper.TestTableItem( + name='test_computer_use_multi_turn', + parameters=types._GenerateContentParameters( + model='gemini-2.5-computer-use-preview-10-2025', + contents=computer_use_multi_turn_contents, + config={ + 'tools': [ + {'computer_use': {'environment': 'ENVIRONMENT_BROWSER'}} + ] + }, + ), + exception_if_vertex='404', + ), + pytest_helper.TestTableItem( + name='test_computer_use_exclude_predefined_functions', + parameters=types._GenerateContentParameters( + model='gemini-2.5-computer-use-preview-10-2025', + contents='cheapest flight to NYC on Mar 18 2025 on Google Flights', + config={ + 'tools': [ + { + 'computer_use': { + 'environment': 'ENVIRONMENT_BROWSER', + 'excluded_predefined_functions': ['click_at'], + }, + }, + ] + }, + ), + exception_if_vertex='404', + ), + pytest_helper.TestTableItem( + name='test_computer_use_override_default_function', + parameters=types._GenerateContentParameters( + model='gemini-2.5-computer-use-preview-10-2025', + contents=computer_use_multi_turn_contents, + config={ + 'tools': [ + { + 'computer_use': { + 'environment': 'ENVIRONMENT_BROWSER', + 'excluded_predefined_functions': ['type_text_at'], + }, + }, + { + 'function_declarations': ( + computer_use_override_function_declarations + ) + }, + ] + }, + ), + exception_if_vertex='404', + ), + pytest_helper.TestTableItem( + # https://github.com/googleapis/python-genai/issues/830 + # - models started returning empty thought in response to queries + # containing tools. + # - The API needs to accept any Content response it sends (otherwise + # chat breaks) + # - MLDev is not returning the, so it's okay that MLDev doesn't accept + # them? + # - This is also important to configm forward compatibility. + # when the models start returning thought_signature, those will get + # dropped by the SDK leaving a `{'thought: True}` part. + name='test_chat_tools_empty_thoughts', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=[ + types.Content.model_validate(item) + for item in [ + { + 'parts': [{'text': 'Who won the 1955 world cup?'}], + 'role': 'user', + }, + { + 'parts': [ + {'thought': True}, + { + 'text': ( + 'The FIFA World Cup is held every four' + ' years. The 1954 FIFA World Cup was won by' + ' West Germany, who defeated Hungary in the' + ' final.' + ) + }, + ], + 'role': 'model', + }, + { + 'parts': [{ + 'text': 'What was the population of canada in 1955?' + }], + 'role': 'user', + }, + ] + ], + config={ + 'tools': [{'function_declarations': function_declarations}], + }, + ), + ), + pytest_helper.TestTableItem( + name='test_function_calling_config_validated_mode', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=t.t_contents('How is the weather in Kirkland?'), + config={ + 'tools': [{'function_declarations': function_declarations}], + 'tool_config': { + 'function_calling_config': {'mode': 'VALIDATED'} + }, + }, + ), + ), + pytest_helper.TestTableItem( + name='test_google_maps_with_enable_widget', + parameters=types._GenerateContentParameters( + model='gemini-2.5-flash', + contents=t.t_contents('What is the nearest airport to Seattle?'), + config={'tools': [{'google_maps': {'enable_widget': True}}]}, + ), + ), + pytest_helper.TestTableItem( + name='test_include_server_side_tool_invocations', + parameters=types._GenerateContentParameters( + model='gemini-3.1-pro-preview', + contents=t.t_contents( + 'Use Google Search to tell me about the 1970 world cup match'), + config=types.GenerateContentConfig( + tools=[ + types.Tool( + google_search=types.GoogleSearch(), + ), + ], + tool_config=types.ToolConfig( + include_server_side_tool_invocations=True, + ), + ), + ), + exception_if_vertex='parameter is not supported', + ), + pytest_helper.TestTableItem( + name='test_include_server_side_tool_invocations_with_tool_call_echo', + parameters=types._GenerateContentParameters( + model='gemini-3.1-pro-preview', + contents=[ + types.Content.model_validate(item) + for item in [ + { + 'role': 'user', + 'parts': [{'text': 'Why is the sky blue?'}], + }, + { + 'role': 'model', + 'parts': [ + { + 'tool_call': { + 'tool_type': 'GOOGLE_SEARCH', + 'args': { + 'query': 'why is the sky blue', + }, + }, + }, + { + 'tool_response': { + 'tool_type': 'GOOGLE_SEARCH', + 'response': { + 'result': ( + 'The sky is blue because of' + ' Rayleigh scattering.' + ), + }, + }, + }, + { + 'text': ( + 'The sky is blue due to a phenomenon called' + ' Rayleigh scattering.' + ), + }, + ], + }, + { + 'role': 'user', + 'parts': [{'text': 'What about Mars?'}], + }, + ] + ], + config=types.GenerateContentConfig( + tools=[ + types.Tool( + google_search=types.GoogleSearch(), + ), + ], + tool_config=types.ToolConfig( + include_server_side_tool_invocations=True, + ), + ), + ), + exception_if_vertex='parameter is not supported', + ), +] + + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='models.generate_content', + test_table=test_table, +) +pytest_plugins = ('pytest_asyncio',) + + +# Cannot be included in test_table because json serialization fails on function. +def test_function_google_search(client): + contents = 'What is the price of GOOG?.' + config = types.GenerateContentConfig( + tools=[ + types.Tool( + google_search=types.GoogleSearch(), + ), + get_stock_price, + ], + tool_config=types.ToolConfig( + function_calling_config=types.FunctionCallingConfig(mode='AUTO') + ), + ) + # bad request to combine function call and google search retrieval + with pytest.raises(errors.ClientError): + client.models.generate_content( + model='gemini-2.5-flash', + contents=contents, + config=config, + ) + + +def test_google_search_stream(client): + for part in client.models.generate_content_stream( + model='gemini-2.5-flash', + contents=types.Content( + role='user', + parts=[types.Part(text='Why is the sky blue?')], + ), + config=types.GenerateContentConfig( + tools=[types.ToolDict({'google_search': {}})], + ), + ): + pass + + +@pytest.mark.skipif( + sys.version_info >= (3, 13), + reason=( + 'object type is dumped as as opposed to' + ' "OBJECT" in Python 3.13' + ), +) +def test_function_calling_without_implementation(client): + response = client.models.generate_content( + model='gemini-2.5-flash', + contents='What is the weather in Boston?', + config={ + 'tools': [get_weather_declaration_only], + 'automatic_function_calling': {'ignore_call_history': True}, + }, + ) + + +def test_2_function(client): + response = client.models.generate_content( + model='gemini-2.5-flash', + contents='What is the price of GOOG? And what is the weather in Boston?', + config={ + 'tools': [get_weather, get_stock_price], + 'automatic_function_calling': {'ignore_call_history': True}, + }, + ) + assert '1000' in response.text + assert 'Boston' in response.text + assert 'sunny' in response.text + + +@pytest.mark.asyncio +async def test_2_function_async(client): + response = await client.aio.models.generate_content( + model='gemini-2.5-flash', + contents='What is the price of GOOG? And what is the weather in Boston?', + config={ + 'tools': [get_weather, get_stock_price], + 'automatic_function_calling': {'ignore_call_history': True}, + }, + ) + assert '1000' in response.text + assert 'Boston' in response.text + assert 'sunny' in response.text + + +def test_automatic_function_calling_with_customized_math_rule(client): + def customized_divide_integers(numerator: int, denominator: int) -> int: + """Divide two integers with customized math rule.""" + return numerator // denominator + 1 + + response = client.models.generate_content( + model='gemini-2.5-flash', + contents='what is the result of 1000/2?', + config={ + 'tools': [customized_divide_integers], + }, + ) + assert '501' in response.text + + +def test_automatic_function_calling(client): + response = client.models.generate_content( + model='gemini-2.5-flash', + contents='what is the result of 1000/2?', + config={ + 'tools': [divide_integers], + 'automatic_function_calling': {'ignore_call_history': True}, + }, + ) + + assert '500' in response.text + + +@pytest.mark.asyncio +async def test_automatic_function_calling_with_async_function(client): + response = await client.aio.models.generate_content( + model='gemini-2.5-flash', + contents='what is the result of 1001.0/2.0?', + config={ + 'tools': [divide_floats_async], + 'automatic_function_calling': {'ignore_call_history': True}, + }, + ) + + assert '500.5' in response.text + + +def test_automatic_function_calling_stream(client): + response = client.models.generate_content_stream( + model='gemini-2.5-flash', + contents='what is the result of 1000/2?', + config={ + 'tools': [divide_integers], + 'automatic_function_calling': {'ignore_call_history': True}, + }, + ) + chunks = 0 + for part in response: + chunks += 1 + assert part.text is not None or part.candidates[0].finish_reason + + +def test_disable_automatic_function_calling_stream(client): + # If AFC is disabled, the response should contain a function call. + response = client.models.generate_content_stream( + model='gemini-2.5-flash', + contents='what is the result of 1000/2?', + config={ + 'tools': [divide_integers], + 'automatic_function_calling': {'disable': True}, + }, + ) + chunks = 0 + for chunk in response: + chunks += 1 + assert chunk.parts[0].function_call is not None + + +def test_automatic_function_calling_no_function_response_stream(client): + response = client.models.generate_content_stream( + model='gemini-2.5-flash', + contents='what is the weather in Boston?', + config={ + 'tools': [divide_integers], + 'automatic_function_calling': {'ignore_call_history': True}, + }, + ) + chunks = 0 + for part in response: + chunks += 1 + assert part.text is not None or part.candidates[0].finish_reason + + +@pytest.mark.asyncio +async def test_disable_automatic_function_calling_stream_async(client): + # If AFC is disabled, the response should contain a function call. + response = await client.aio.models.generate_content_stream( + model='gemini-2.5-flash', + contents='what is the result of 1000/2?', + config={ + 'tools': [divide_integers], + 'automatic_function_calling': {'disable': True}, + }, + ) + chunks = 0 + async for chunk in response: + chunks += 1 + assert chunk.parts[0].function_call is not None + + +@pytest.mark.asyncio +async def test_automatic_function_calling_no_function_response_stream_async( + client, +): + response = await client.aio.models.generate_content_stream( + model='gemini-2.5-flash', + contents='what is the weather in Boston?', + config={ + 'tools': [divide_integers], + 'automatic_function_calling': {'ignore_call_history': True}, + }, + ) + chunks = 0 + async for chunk in response: + chunks += 1 + assert chunk.text is not None or chunk.candidates[0].finish_reason + + +@pytest.mark.asyncio +async def test_automatic_function_calling_stream_async(client): + response = await client.aio.models.generate_content_stream( + model='gemini-2.5-flash', + contents='what is the result of 1000/2?', + config={ + 'tools': [divide_integers], + 'automatic_function_calling': {'ignore_call_history': True}, + }, + ) + chunks = 0 + async for chunk in response: + chunks += 1 + assert chunk.text is not None or chunk.candidates[0].finish_reason + + +def test_callable_tools_user_disable_afc(client): + response = client.models.generate_content( + model='gemini-2.5-flash', + contents='what is the result of 1000/2?', + config={ + 'tools': [divide_integers], + 'automatic_function_calling': { + 'disable': True, + 'ignore_call_history': True, + }, + }, + ) + + +def test_callable_tools_user_disable_afc_with_max_remote_calls(client): + response = client.models.generate_content( + model='gemini-2.5-flash', + contents='what is the result of 1000/2?', + config={ + 'tools': [divide_integers], + 'automatic_function_calling': { + 'disable': True, + 'maximum_remote_calls': 2, + 'ignore_call_history': True, + }, + }, + ) + + +def test_callable_tools_user_disable_afc_with_max_remote_calls_negative( + client, +): + response = client.models.generate_content( + model='gemini-2.5-flash', + contents='what is the result of 1000/2?', + config={ + 'tools': [divide_integers], + 'automatic_function_calling': { + 'disable': True, + 'maximum_remote_calls': -1, + 'ignore_call_history': True, + }, + }, + ) + + +def test_callable_tools_user_disable_afc_with_max_remote_calls_zero(client): + response = client.models.generate_content( + model='gemini-2.5-flash', + contents='what is the result of 1000/2?', + config={ + 'tools': [divide_integers], + 'automatic_function_calling': { + 'disable': True, + 'maximum_remote_calls': 0, + 'ignore_call_history': True, + }, + }, + ) + + +def test_callable_tools_user_enable_afc(client): + response = client.models.generate_content( + model='gemini-2.5-flash', + contents='what is the result of 1000/2?', + config={ + 'tools': [divide_integers], + 'automatic_function_calling': { + 'disable': False, + 'ignore_call_history': True, + }, + }, + ) + + +def test_callable_tools_user_enable_afc_with_max_remote_calls(client): + response = client.models.generate_content( + model='gemini-2.5-flash', + contents='what is the result of 1000/2?', + config={ + 'tools': [divide_integers], + 'automatic_function_calling': { + 'disable': False, + 'maximum_remote_calls': 2, + 'ignore_call_history': True, + }, + }, + ) + + +def test_callable_tools_user_enable_afc_with_max_remote_calls_negative( + client, +): + response = client.models.generate_content( + model='gemini-2.5-flash', + contents='what is the result of 1000/2?', + config={ + 'tools': [divide_integers], + 'automatic_function_calling': { + 'disable': False, + 'maximum_remote_calls': -1, + 'ignore_call_history': True, + }, + }, + ) + + +def test_callable_tools_user_enable_afc_with_max_remote_calls_zero(client): + response = client.models.generate_content( + model='gemini-2.5-flash', + contents='what is the result of 1000/2?', + config={ + 'tools': [divide_integers], + 'automatic_function_calling': { + 'disable': False, + 'maximum_remote_calls': 0, + 'ignore_call_history': True, + }, + }, + ) + + +def test_automatic_function_calling_with_exception(client): + client.models.generate_content( + model='gemini-2.5-flash', + contents='what is the result of 1000/0?', + config={ + 'tools': [divide_integers], + 'automatic_function_calling': {'ignore_call_history': True}, + }, + ) + + +def test_automatic_function_calling_float_without_decimal(client): + response = client.models.generate_content( + model='gemini-2.5-flash', + contents='what is the result of 1000.0/2.0?', + config={ + 'tools': [divide_floats, divide_integers], + 'automatic_function_calling': {'ignore_call_history': True}, + }, + ) + + assert '500.0' in response.text + + +def test_automatic_function_calling_with_pydantic_model(client): + class CityObject(pydantic.BaseModel): + city_name: str + + def get_weather_pydantic_model( + city_object: CityObject, is_winter: bool + ) -> str: + if is_winter: + return f'The weather in {city_object.city_name} is cold and 10 degrees.' + else: + return f'The weather in {city_object.city_name} is sunny and 100 degrees.' + + response = client.models.generate_content( + model='gemini-2.5-flash', + contents='it is winter now, what is the weather in Boston?', + config={ + 'tools': [get_weather_pydantic_model], + 'automatic_function_calling': {'ignore_call_history': True}, + }, + ) + + assert 'cold' in response.text and 'Boston' in response.text + + +def test_automatic_function_calling_with_pydantic_model_in_list_type(client): + class CityObject(pydantic.BaseModel): + city_name: str + + def get_weather_from_list_of_cities( + city_object_list: list[CityObject], is_winter: bool + ) -> str: + result = '' + if is_winter: + for city_object in city_object_list: + result += ( + f'The weather in {city_object.city_name} is cold and 10 degrees.\n' + ) + else: + for city_object in city_object_list: + result += ( + f'The weather in {city_object.city_name} is sunny and 100' + ' degrees.\n' + ) + return result + + response = client.models.generate_content( + model='gemini-2.5-flash', + contents='it is winter now, what is the weather in Boston and New York?', + config={ + 'tools': [get_weather_from_list_of_cities], + 'automatic_function_calling': {'ignore_call_history': True}, + }, + ) + + assert 'cold' in response.text and 'Boston' in response.text + assert 'cold' in response.text and 'New York' in response.text + + +# TODO(b/397404656): modify this test to pass in api mode +def test_automatic_function_calling_with_pydantic_model_in_union_type(client): + class AnimalObject(pydantic.BaseModel): + name: str + age: int + species: str + + class PlantObject(pydantic.BaseModel): + name: str + height: float + color: str + + def get_information( + object_of_interest: typing.Union[AnimalObject, PlantObject], + ) -> str: + if isinstance(object_of_interest, AnimalObject): + return ( + f'The animal is of {object_of_interest.species} species and is named' + f' {object_of_interest.name} is {object_of_interest.age} years old' + ) + elif isinstance(object_of_interest, PlantObject): + return ( + f'The plant is named {object_of_interest.name} and is' + f' {object_of_interest.height} meters tall and is' + f' {object_of_interest.color} color' + ) + else: + return 'The animal is not supported' + + with pytest_helper.exception_if_vertex(client, errors.ClientError): + response = client.models.generate_content( + model='gemini-2.5-flash', + contents=( + 'I have a one year old cat named Sundae, can you get the' + ' information of the cat for me?' + ), + config={ + 'system_instruction': ( + 'you answer questions based on the tools provided' + ), + 'tools': [get_information], + 'automatic_function_calling': {'ignore_call_history': True}, + }, + ) + assert 'Sundae' in response.text + assert 'cat' in response.text + + +def test_automatic_function_calling_with_union_operator(client): + class AnimalObject(pydantic.BaseModel): + name: str + age: int + species: str + + def get_information( + object_of_interest: str | AnimalObject, + ) -> str: + if isinstance(object_of_interest, AnimalObject): + return ( + f'The animal is of {object_of_interest.species} species and is named' + f' {object_of_interest.name} is {object_of_interest.age} years old' + ) + else: + return f'The object of interest is {object_of_interest}' + + response = client.models.generate_content( + model='gemini-2.5-flash', + contents=( + 'I have a one year old cat named Sundae, can you get the' + ' information of the cat for me?' + ), + config={ + 'tools': [get_information], + 'automatic_function_calling': {'ignore_call_history': True}, + }, + ) + assert response.text + + +def test_automatic_function_calling_with_tuple_param(client): + def output_latlng( + latlng: tuple[float, float], + ) -> str: + return f'The latitude is {latlng[0]} and the longitude is {latlng[1]}' + + response = client.models.generate_content( + model='gemini-2.5-flash', + contents=( + 'The coordinates are (51.509, -0.118). What is the latitude and longitude?' + ), + config={ + 'tools': [output_latlng], + 'automatic_function_calling': {'ignore_call_history': True}, + }, + ) + assert response.text + + +@pytest.mark.skipif( + sys.version_info < (3, 10), + reason='| is only supported in Python 3.10 and above.', +) +def test_automatic_function_calling_with_union_operator_return_type(client): + def get_cheese_age(cheese: int) -> int | float: + """ + Retrieves data about the age of the cheese given its ID. + + Args: + cheese_id: The ID of the cheese. + + Returns: + An int or float of the age of the cheese. + """ + if cheese == 1: + return 2.5 + elif cheese == 2: + return 3 + else: + return 0.0 + + response = client.models.generate_content( + model='gemini-2.5-flash', + contents='How old is the cheese with id 2?', + config={ + 'tools': [get_cheese_age], + 'automatic_function_calling': {'ignore_call_history': True}, + }, + ) + assert '3' in response.text + + +def test_automatic_function_calling_with_parameterized_generic_union_type( + client, +): + def describe_cities( + country: str, + cities: typing.Optional[list[str]] = None, + ) -> str: + 'Given a country and an optional list of cities, describe the cities.' + if cities is None: + return 'There are no cities to describe.' + else: + return ( + f'The cities in {country} are: {", ".join(cities)} and they are nice.' + ) + + response = client.models.generate_content( + model='gemini-2.5-flash', + contents='Can you describe the city of San Francisco, USA?', + config={ + 'tools': [describe_cities], + 'automatic_function_calling': {'ignore_call_history': True}, + }, + ) + assert 'San Francisco' in response.text + + +@pytest.mark.asyncio +async def test_google_search_async(client): + await client.aio.models.generate_content( + model='gemini-2.5-flash', + contents=[ + types.ContentDict( + {'role': 'user', 'parts': [{'text': 'Why is the sky blue?'}]} + ) + ], + config={'tools': [{'google_search': {}}]}, + ) + + +def test_empty_tools(client): + client.models.generate_content( + model='gemini-2.5-flash', + contents='What is the price of GOOG?.', + config={'tools': []}, + ) + + +def test_with_1_empty_tool(client): + # Bad request for empty tool. + with pytest_helper.exception_if_vertex(client, errors.ClientError): + client.models.generate_content( + model='gemini-2.5-flash', + contents='What is the price of GOOG?.', + config={ + 'tools': [{}, get_stock_price], + 'automatic_function_calling': {'ignore_call_history': True}, + }, + ) + + +@pytest.mark.asyncio +async def test_google_search_stream_async(client): + async for part in await client.aio.models.generate_content_stream( + model='gemini-2.5-flash', + contents='Why is the sky blue?', + config={'tools': [{'google_search': {}}]}, + ): + pass + + +@pytest.mark.asyncio +async def test_vai_search_stream_async(client): + if client._api_client.vertexai: + async for part in await client.aio.models.generate_content_stream( + model='gemini-2.5-flash', + contents='what is vertex ai search?', + config={ + 'tools': [{ + 'retrieval': { + 'vertex_ai_search': { + 'datastore': ( + 'projects/vertex-sdk-dev/locations/global/collections/default_collection/dataStores/yvonne_1728691676574' + ) + } + } + }] + }, + ): + pass + else: + with pytest.raises(ValueError) as e: + async for part in await client.aio.models.generate_content_stream( + model='gemini-2.5-flash', + contents='Why is the sky blue?', + config={ + 'tools': [{ + 'retrieval': { + 'vertex_ai_search': { + 'datastore': ( + 'projects/vertex-sdk-dev/locations/global/collections/default_collection/dataStores/yvonne_1728691676574' + ) + } + } + }] + }, + ): + pass + assert 'retrieval' in str(e) + + +def test_automatic_function_calling_with_coroutine_function(client): + async def divide_integers(a: int, b: int) -> int: + return a // b + + with pytest.raises(errors.UnsupportedFunctionError): + client.models.generate_content( + model='gemini-2.5-flash', + contents='what is the result of 1000/2?', + config={ + 'tools': [divide_integers], + 'automatic_function_calling': {'ignore_call_history': True}, + }, + ) + + +@pytest.mark.asyncio +async def test_automatic_function_calling_with_coroutine_function_async( + client, +): + async def divide_integers(a: int, b: int) -> int: + return a // b + + response = await client.aio.models.generate_content( + model='gemini-2.5-flash', + contents='what is the result of 1000/2?', + config={ + 'tools': [divide_integers], + 'automatic_function_calling': {'ignore_call_history': True}, + }, + ) + + assert '500' in response.text + + +@pytest.mark.asyncio +async def test_automatic_function_calling_async(client): + def divide_integers(a: int, b: int) -> int: + return a // b + + response = await client.aio.models.generate_content( + model='gemini-2.5-flash', + contents='what is the result of 1000/2?', + config={ + 'tools': [divide_integers], + 'automatic_function_calling': {'ignore_call_history': True}, + }, + ) + + assert '500' in response.text + + +@pytest.mark.asyncio +async def test_automatic_function_calling_async_with_exception(client): + def mystery_function(a: int, b: int) -> int: + return a // b + + response = await client.aio.models.generate_content( + model='gemini-2.5-flash', + contents='what is the result of 1000/0?', + config={ + 'tools': [divide_integers], + 'system_instruction': ( + 'you must first look at the tools and then think about answers' + ), + }, + ) + assert response.automatic_function_calling_history + assert ( + response.automatic_function_calling_history[-1] + .parts[0] + .function_response.response['error'] + ) + + +@pytest.mark.asyncio +async def test_automatic_function_calling_async_float_without_decimal(client): + response = await client.aio.models.generate_content( + model='gemini-2.5-flash', + contents='what is the result of 1000.0/2.0?', + config={ + 'tools': [divide_floats, divide_integers], + 'automatic_function_calling': {'ignore_call_history': True}, + }, + ) + + assert '500.0' in response.text + + +@pytest.mark.asyncio +async def test_automatic_function_calling_async_with_pydantic_model(client): + class CityObject(pydantic.BaseModel): + city_name: str + + def get_weather_pydantic_model( + city_object: CityObject, is_winter: bool + ) -> str: + if is_winter: + return f'The weather in {city_object.city_name} is cold and 10 degrees.' + else: + return f'The weather in {city_object.city_name} is sunny and 100 degrees.' + + response = await client.aio.models.generate_content( + model='gemini-2.5-flash', + contents='it is winter now, what is the weather in Boston?', + config={ + 'tools': [get_weather_pydantic_model], + 'automatic_function_calling': {'ignore_call_history': True}, + }, + ) + + # ML Dev couldn't understand pydantic model + if client.vertexai: + assert 'cold' in response.text and 'Boston' in response.text + + +@pytest.mark.asyncio +async def test_automatic_function_calling_async_with_async_function(client): + async def get_current_weather_async(city: str) -> str: + """Returns the current weather in the city.""" + + return 'windy' + + response = await client.aio.models.generate_content( + model='gemini-2.5-flash', + contents='what is the weather in San Francisco?', + config={ + 'tools': [get_current_weather_async], + 'automatic_function_calling': {'ignore_call_history': True}, + }, + ) + + assert 'windy' in response.text + assert 'San Francisco' in response.text + + +@pytest.mark.asyncio +async def test_automatic_function_calling_async_with_async_function_stream( + client, +): + async def get_current_weather_async(city: str) -> str: + """Returns the current weather in the city.""" + + return 'windy' + + response = await client.aio.models.generate_content_stream( + model='gemini-2.5-flash', + contents='what is the weather in San Francisco?', + config={ + 'tools': [get_current_weather_async], + 'automatic_function_calling': {'ignore_call_history': True}, + }, + ) + + chunk = None + async for chunk in response: + if chunk.parts[0].function_call: + assert chunk.parts[0].function_call.name == 'get_current_weather_async' + assert chunk.parts[0].function_call.args['city'] == 'San Francisco' + + +def test_2_function_with_history(client): + response = client.models.generate_content( + model='gemini-2.5-flash', + contents='What is the price of GOOG? And what is the weather in Boston?', + config={ + 'tools': [get_weather, get_stock_price], + 'automatic_function_calling': {'ignore_call_history': False}, + }, + ) + + actual_history = response.automatic_function_calling_history + + assert actual_history[0].role == 'user' + assert ( + actual_history[0].parts[0].text + == 'What is the price of GOOG? And what is the weather in Boston?' + ) + + assert actual_history[1].role == 'model' + assert actual_history[1].parts[0].function_call.model_dump_json( + exclude_none=True + ) == types.FunctionCall( + name='get_stock_price', + args={'symbol': 'GOOG'}, + ).model_dump_json( + exclude_none=True + ) + assert actual_history[1].parts[1].function_call.model_dump_json( + exclude_none=True + ) == types.FunctionCall( + name='get_weather', + args={'city': 'Boston'}, + ).model_dump_json( + exclude_none=True + ) + + assert actual_history[2].role == 'user' + assert actual_history[2].parts[0].function_response.model_dump_json( + exclude_none=True + ) == types.FunctionResponse( + name='get_stock_price', response={'result': '1000'} + ).model_dump_json( + exclude_none=True + ) + assert actual_history[2].parts[1].function_response.model_dump_json( + exclude_none=True + ) == types.FunctionResponse( + name='get_weather', + response={'result': 'The weather in Boston is sunny and 100 degrees.'}, + ).model_dump_json( + exclude_none=True + ) + + +@pytest.mark.asyncio +async def test_2_function_with_history_async(client): + response = await client.aio.models.generate_content( + model='gemini-2.5-flash', + contents='What is the price of GOOG? And what is the weather in Boston?', + config={ + 'tools': [get_weather, get_stock_price], + 'automatic_function_calling': {'ignore_call_history': False}, + }, + ) + + actual_history = response.automatic_function_calling_history + + assert actual_history[0].role == 'user' + assert ( + actual_history[0].parts[0].text + == 'What is the price of GOOG? And what is the weather in Boston?' + ) + + assert actual_history[1].role == 'model' + assert actual_history[1].parts[0].function_call.model_dump_json( + exclude_none=True + ) == types.FunctionCall( + name='get_stock_price', + args={'symbol': 'GOOG'}, + ).model_dump_json( + exclude_none=True + ) + assert actual_history[1].parts[1].function_call.model_dump_json( + exclude_none=True + ) == types.FunctionCall( + name='get_weather', + args={'city': 'Boston'}, + ).model_dump_json( + exclude_none=True + ) + + assert actual_history[2].role == 'user' + assert actual_history[2].parts[0].function_response.model_dump_json( + exclude_none=True + ) == types.FunctionResponse( + name='get_stock_price', response={'result': '1000'} + ).model_dump_json( + exclude_none=True + ) + assert actual_history[2].parts[1].function_response.model_dump_json( + exclude_none=True + ) == types.FunctionResponse( + name='get_weather', + response={'result': 'The weather in Boston is sunny and 100 degrees.'}, + ).model_dump_json( + exclude_none=True + ) + + +class FunctionHolder: + NAME = 'FunctionHolder' + + def is_a_duck(self, number: int) -> str: + return self.NAME + 'says isOdd: ' + str(number % 2 == 1) + + def is_a_rabbit(self, number: int) -> str: + return self.NAME + 'says isEven: ' + str(number % 2 == 0) + + +def test_class_method_tools(client): + # This test is to make sure that instance method tools can be used in + # the generate_content request. + + function_holder = FunctionHolder() + response = client.models.generate_content( + model='gemini-2.0-flash-exp', + contents=( + 'Print the verbatim output of is_a_duck and is_a_rabbit for the' + ' number 100.' + ), + config={ + 'tools': [function_holder.is_a_duck, function_holder.is_a_rabbit], + }, + ) + assert 'FunctionHolder' in response.text + + +def test_disable_afc_in_any_mode(client): + response = client.models.generate_content( + model='gemini-2.5-flash', + contents='what is the result of 1000/2?', + config=types.GenerateContentConfig( + tools=[divide_integers], + automatic_function_calling=types.AutomaticFunctionCallingConfig( + disable=True + ), + tool_config=types.ToolConfig( + function_calling_config=types.FunctionCallingConfig(mode='ANY') + ), + ), + ) + + +def test_afc_once_in_any_mode(client): + response = client.models.generate_content( + model='gemini-2.5-flash', + contents='what is the result of 1000/2?', + config=types.GenerateContentConfig( + tools=[divide_integers], + automatic_function_calling=types.AutomaticFunctionCallingConfig( + maximum_remote_calls=2 + ), + tool_config=types.ToolConfig( + function_calling_config=types.FunctionCallingConfig(mode='ANY') + ), + ), + ) + + +def test_code_execution_tool(client): + response = client.models.generate_content( + model='gemini-2.0-flash-exp', + contents=( + 'What is the sum of the first 50 prime numbers? Generate and run code' + ' for the calculation, and make sure you get all 50.' + ), + config=types.GenerateContentConfig( + tools=[types.Tool(code_execution=types.ToolCodeExecution)] + ), + ) + + assert response.executable_code + assert ( + 'prime' in response.code_execution_result.lower() + or '5117' in response.code_execution_result + ) + + +def test_afc_logs_to_logger_instance(client, caplog): + caplog.set_level(logging.DEBUG, logger='google_genai.models') + client.models.generate_content( + model='gemini-2.5-flash', + contents='what is the result of 1000/2?', + config={ + 'tools': [divide_integers], + 'automatic_function_calling': { + 'disable': False, + 'maximum_remote_calls': 1, + 'ignore_call_history': True, + }, + }, + ) + for log in caplog.records: + assert log.levelname == 'INFO' + assert log.name == 'google_genai.models' + + assert 'AFC is enabled with max remote calls: 1' in caplog.text + assert 'remote call 1 is done' in caplog.text + assert 'Reached max remote calls' in caplog.text + + +def test_suppress_logs_with_sdk_logger(client, caplog): + caplog.set_level(logging.DEBUG, logger='google_genai.models') + sdk_logger = logging.getLogger('google_genai.models') + sdk_logger.setLevel(logging.ERROR) + client.models.generate_content( + model='gemini-2.5-flash', + contents='what is the result of 1000/2?', + config={ + 'tools': [divide_integers], + 'automatic_function_calling': { + 'disable': False, + 'maximum_remote_calls': 2, + 'ignore_call_history': True, + }, + }, + ) + assert not caplog.text + + +def test_tools_chat_curation(client, caplog): + caplog.set_level(logging.DEBUG, logger='google_genai.models') + sdk_logger = logging.getLogger('google_genai.models') + sdk_logger.setLevel(logging.ERROR) + + config = { + 'tools': [{'function_declarations': function_declarations}], + } + + chat = client.chats.create( + model='gemini-2.5-flash', + config=config, + ) + + response = chat.send_message( + message='Who won the 1955 world cup?', + ) + + response = chat.send_message( + message='What was the population of canada in 1955?', + ) + + history = chat.get_history(curated=True) + assert len(history) == 4 + + +def test_function_declaration_with_callable(client): + response = client.models.generate_content( + model='gemini-2.5-pro', + contents=( + 'Divide 1000 by 2. And tell' + ' me the weather in London.' + ), + config={ + 'tools': [ + divide_integers, + {'function_declarations': function_declarations}, + ], + }, + ) + assert response.function_calls is not None + +def test_function_declaration_with_callable_stream_now(client): + for chunk in client.models.generate_content_stream( + model='gemini-2.5-pro', + contents='Divide 1000 by 2. And tell me the weather in London.', + config={ + 'tools': [ + divide_integers, + {'function_declarations': function_declarations}, + ], + }, + ): + pass + +@pytest.mark.asyncio +async def test_function_declaration_with_callable_async(client): + response = await client.aio.models.generate_content( + model='gemini-2.5-pro', + contents=( + 'Divide 1000 by 2. And tell' + ' me the weather in London.' + ), + config={ + 'tools': [ + divide_integers, + {'function_declarations': function_declarations}, + ], + }, + ) + assert response.function_calls is not None + + +@pytest.mark.asyncio +async def test_function_declaration_with_callable_async_stream(client): + async for chunk in await client.aio.models.generate_content_stream( + model='gemini-2.5-pro', + contents='Divide 1000 by 2. And tell me the weather in London.', + config={ + 'tools': [ + divide_integers, + {'function_declarations': function_declarations}, + ], + }, + ): + pass + +def test_server_side_mcp_only(client): + """Test server side mcp, happy path.""" + with pytest_helper.exception_if_vertex(client, ValueError): + response = client.models.generate_content( + model='gemini-2.5-pro', + contents=('What is the weather like in New York (NY) on 02/02/2026?'), + config=types.GenerateContentConfig( + tools=[types.Tool( + mcp_servers=[types.McpServer( + name='get_weather', + streamable_http_transport=types.StreamableHttpTransport( + url='https://gemini-api-demos.uc.r.appspot.com/mcp', + headers={'AUTHORIZATION': 'Bearer github_pat_XXXX'}, + ), + )] + )] + ) + ) + assert response.text + +@pytest.mark.asyncio +async def test_server_side_mcp_only_async(client): + """Test server side mcp, happy path.""" + with pytest_helper.exception_if_vertex(client, ValueError): + response = await client.aio.models.generate_content( + model='gemini-2.5-flash', + contents=( + 'What is the weather like in New York on 02/02/2026?' + ), + config=types.GenerateContentConfig( + tools=[types.Tool( + mcp_servers=[types.McpServer( + name='get_weather', + streamable_http_transport=types.StreamableHttpTransport( + url='https://gemini-api-demos.uc.r.appspot.com/mcp', + headers={'AUTHORIZATION': 'Bearer github_pat_XXXX'}, + ), + )] + + )] + ) + ) + assert response.text + +def test_server_side_mcp_only_stream(client): + """Test server side mcp, happy path.""" + with pytest_helper.exception_if_vertex(client, ValueError): + response = client.models.generate_content_stream( + model='gemini-2.5-pro', + contents=('What is the weather like in New York (NY) on 02/02/2026?'), + config=types.GenerateContentConfig( + tools=[types.Tool( + mcp_servers=[types.McpServer( + name='get_weather', + streamable_http_transport=types.StreamableHttpTransport( + url='https://gemini-api-demos.uc.r.appspot.com/mcp', + headers={'AUTHORIZATION': 'Bearer github_pat_XXXX'}, + ), + )] + )] + ) + ) + for chunk in response: + pass diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_images.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_images.py new file mode 100644 index 0000000000000000000000000000000000000000..24e4cbc73bd061fbe4155df14a77af222b1fcbe6 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_images.py @@ -0,0 +1,191 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for generate_images.""" + +import pytest + +from ... import types +from .. import pytest_helper + +IMAGEN_MODEL_LATEST = 'imagen-4.0-generate-001' + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_simple_prompt', + parameters=types._GenerateImagesParameters( + model=IMAGEN_MODEL_LATEST, + prompt='Red skateboard', + config=types.GenerateImagesConfig( + number_of_images=1, + output_mime_type='image/jpeg', + ), + ), + ), + pytest_helper.TestTableItem( + name='test_all_vertexai_config_parameters', + exception_if_mldev='not supported in Gemini API', + parameters=types._GenerateImagesParameters( + model=IMAGEN_MODEL_LATEST, + prompt='Red skateboard', + config=types.GenerateImagesConfig( + image_size='2K', + aspect_ratio='1:1', + guidance_scale=15.0, + safety_filter_level=types.SafetyFilterLevel.BLOCK_MEDIUM_AND_ABOVE, + number_of_images=1, + person_generation=types.PersonGeneration.DONT_ALLOW, + include_safety_attributes=True, + include_rai_reason=True, + output_mime_type='image/jpeg', + output_compression_quality=80, + # The below parameters are not supported in Gemini Developer API. + negative_prompt='human', + add_watermark=False, + seed=1337, + language='en', + enhance_prompt=True, + labels={'imagen_label_key': 'generate_images'} + ), + ), + ), + pytest_helper.TestTableItem( + name='test_all_vertexai_config_person_generation_enum_parameters', + exception_if_mldev='enum value is not supported', + parameters=types._GenerateImagesParameters( + model=IMAGEN_MODEL_LATEST, + prompt='Robot holding a red skateboard', + config=types.GenerateImagesConfig( + person_generation='ALLOW_ALL', + number_of_images=1, + output_mime_type='image/jpeg', + ), + ), + ), + pytest_helper.TestTableItem( + name='test_all_vertexai_config_person_generation_enum_parameters_2', + exception_if_mldev='enum value is not supported', + parameters=types._GenerateImagesParameters( + model=IMAGEN_MODEL_LATEST, + prompt='Robot holding a red skateboard', + config=types.GenerateImagesConfig( + person_generation='allow_all', + number_of_images=1, + output_mime_type='image/jpeg', + ), + ), + ), + pytest_helper.TestTableItem( + name='test_all_vertexai_config_person_generation_enum_parameters_3', + exception_if_mldev='enum value is not supported', + parameters=types._GenerateImagesParameters( + model=IMAGEN_MODEL_LATEST, + prompt='Robot holding a red skateboard', + config=types.GenerateImagesConfig( + person_generation=types.PersonGeneration.ALLOW_ALL, + number_of_images=1, + output_mime_type='image/jpeg', + ), + ), + ), + pytest_helper.TestTableItem( + name='test_all_vertexai_config_safety_filter_level_enum_parameters', + parameters=types._GenerateImagesParameters( + model=IMAGEN_MODEL_LATEST, + prompt='Robot holding a red skateboard', + config=types.GenerateImagesConfig( + safety_filter_level='BLOCK_LOW_AND_ABOVE', + number_of_images=1, + output_mime_type='image/jpeg', + ), + ), + ), + pytest_helper.TestTableItem( + name='test_all_vertexai_config_safety_filter_level_enum_parameters_2', + parameters=types._GenerateImagesParameters( + model=IMAGEN_MODEL_LATEST, + prompt='Robot holding a red skateboard', + config=types.GenerateImagesConfig( + safety_filter_level='block_low_and_above', + number_of_images=1, + output_mime_type='image/jpeg', + ), + ), + ), + pytest_helper.TestTableItem( + name='test_all_vertexai_config_safety_filter_level_enum_parameters_3', + parameters=types._GenerateImagesParameters( + model=IMAGEN_MODEL_LATEST, + prompt='Robot holding a red skateboard', + config=types.GenerateImagesConfig( + safety_filter_level=types.SafetyFilterLevel.BLOCK_LOW_AND_ABOVE, + number_of_images=1, + output_mime_type='image/jpeg', + ), + ), + ), + pytest_helper.TestTableItem( + name='test_all_mldev_config_parameters', + parameters=types._GenerateImagesParameters( + model=IMAGEN_MODEL_LATEST, + prompt='Red skateboard', + config=types.GenerateImagesConfig( + image_size='2K', + aspect_ratio='1:1', + guidance_scale=15.0, + safety_filter_level='BLOCK_LOW_AND_ABOVE', + number_of_images=1, + person_generation='DONT_ALLOW', + include_safety_attributes=True, + include_rai_reason=True, + output_mime_type='image/jpeg', + output_compression_quality=80, + ), + ), + ), +] +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='models.generate_images', + test_table=test_table, +) + + +@pytest.mark.asyncio +async def test_simple_prompt_async(client): + response = await client.aio.models.generate_images( + model=IMAGEN_MODEL_LATEST, + prompt='Red skateboard', + config=types.GenerateImagesConfig( + number_of_images=1, + output_mime_type='image/jpeg', + include_safety_attributes=True, + include_rai_reason=True, + ), + ) + + assert response.generated_images[0].image.image_bytes + # Verify the images accessor works correctly. + assert ( + response.generated_images[0].image.image_bytes + == response.images[0].image_bytes + ) + assert len(response.generated_images) == 1 + assert ( + response.positive_prompt_safety_attributes.content_type + == 'Positive Prompt' + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_videos.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_videos.py new file mode 100644 index 0000000000000000000000000000000000000000..97c4f3553b34cc039535a1e409832c63d9510f7a --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_generate_videos.py @@ -0,0 +1,788 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for generate_videos.""" + +import os +import time +import pytest + +from ... import _replay_api_client +from ... import types +from .. import pytest_helper + +VEO_MODEL_LATEST = "veo-3.1-generate-preview" +VEO_MODEL_2 = "veo-2.0-generate-001" +VEO_MODEL_2_EXP = "veo-2.0-generate-exp" + +OUTPUT_GCS_URI = "gs://genai-sdk-tests/temp/videos/" + +GCS_IMAGE = types.Image( + gcs_uri="gs://cloud-samples-data/vertex-ai/llm/prompts/landmark1.png", + # Required + mime_type="image/png", +) + +GCS_IMAGE2 = types.Image( + gcs_uri="gs://cloud-samples-data/vertex-ai/llm/prompts/landmark2.png", + # Required + mime_type="image/png", +) + +IMAGE_FILE_PATH = os.path.abspath( + os.path.join(os.path.dirname(__file__), "../data/bridge1.png") +) +LOCAL_IMAGE = types.Image.from_file(location=IMAGE_FILE_PATH) + +LOCAL_IMAGE_MAN = types.Image.from_file( + location=os.path.abspath( + os.path.join(os.path.dirname(__file__), "../data/man.jpg") + ) +) + +LOCAL_IMAGE_DOG = types.Image.from_file( + location=os.path.abspath( + os.path.join(os.path.dirname(__file__), "../data/dog.jpg") + ) +) + +GCS_OUTPAINT_MASK = types.Image( + gcs_uri="gs://genai-sdk-tests/inputs/videos/video_outpaint_mask.png", + mime_type="image/png", +) + +GCS_REMOVE_MASK = types.Image( + gcs_uri="gs://genai-sdk-tests/inputs/videos/video_remove_mask.png", + mime_type="image/png", +) + +GCS_REMOVE_STATIC_MASK = types.Image( + gcs_uri="gs://genai-sdk-tests/inputs/videos/video_remove_static_mask.png", + mime_type="image/png", +) + + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name="test_simple_prompt", + parameters=types._GenerateVideosParameters( + model=VEO_MODEL_LATEST, + prompt="Man with a dog", + ), + ), + pytest_helper.TestTableItem( + name="test_all_parameters_vertex", + parameters=types._GenerateVideosParameters( + model=VEO_MODEL_LATEST, + prompt="A neon hologram of a cat driving at top speed", + config=types.GenerateVideosConfig( + number_of_videos=1, + output_gcs_uri=OUTPUT_GCS_URI, + fps=30, + duration_seconds=6, + seed=1, + aspect_ratio="16:9", + resolution="720p", + person_generation="allow_adult", + # pubsub_topic="projects//topics/video-generation-test", + negative_prompt="ugly, low quality", + enhance_prompt=True, + compression_quality=types.VideoCompressionQuality.LOSSLESS, + labels={"veo_label_key": "generate_videos"}, + ), + ), + exception_if_mldev="not supported in Gemini API", + ), + pytest_helper.TestTableItem( + name="test_from_text_source", + parameters=types._GenerateVideosParameters( + model=VEO_MODEL_LATEST, + source=types.GenerateVideosSource(prompt="Man with a dog"), + config=types.GenerateVideosConfig( + number_of_videos=1, + ), + ), + ), + pytest_helper.TestTableItem( + name="test_from_image_source", + parameters=types._GenerateVideosParameters( + model=VEO_MODEL_LATEST, + source=types.GenerateVideosSource( + image=LOCAL_IMAGE, + ), + config=types.GenerateVideosConfig( + number_of_videos=1, + ), + ), + ), + pytest_helper.TestTableItem( + name="test_from_text_and_image_source", + parameters=types._GenerateVideosParameters( + model=VEO_MODEL_LATEST, + source=types.GenerateVideosSource( + prompt="Lightning storm", + image=LOCAL_IMAGE, + ), + config=types.GenerateVideosConfig( + number_of_videos=1, + ), + ), + ), + pytest_helper.TestTableItem( + name="test_from_video_source", + parameters=types._GenerateVideosParameters( + model=VEO_MODEL_LATEST, + source=types.GenerateVideosSource( + video=types.Video( + uri="gs://genai-sdk-tests/inputs/videos/cat_driving.mp4", + mime_type="video/mp4", + ), + ), + config=types.GenerateVideosConfig( + number_of_videos=1, + output_gcs_uri=OUTPUT_GCS_URI, + ), + ), + exception_if_mldev=( + "output_gcs_uri parameter is not supported in Gemini API" + ), + ), + pytest_helper.TestTableItem( + name="test_from_text_and_video_source", + parameters=types._GenerateVideosParameters( + model=VEO_MODEL_LATEST, + source=types.GenerateVideosSource( + prompt="Rain", + video=types.Video( + uri="gs://genai-sdk-tests/inputs/videos/cat_driving.mp4", + mime_type="video/mp4", + ), + ), + config=types.GenerateVideosConfig( + number_of_videos=1, + output_gcs_uri=OUTPUT_GCS_URI, + ), + ), + exception_if_mldev=( + "output_gcs_uri parameter is not supported in Gemini API" + ), + ), + pytest_helper.TestTableItem( + name="test_video_edit_outpaint", + parameters=types._GenerateVideosParameters( + model=VEO_MODEL_2_EXP, + source=types.GenerateVideosSource( + prompt="A mountain landscape", + video=types.Video( + uri="gs://genai-sdk-tests/inputs/videos/editing_demo.mp4", + mime_type="video/mp4", + ), + ), + config=types.GenerateVideosConfig( + output_gcs_uri=OUTPUT_GCS_URI, + aspect_ratio="16:9", + mask=types.VideoGenerationMask( + image=GCS_OUTPAINT_MASK, + mask_mode=types.VideoGenerationMaskMode.OUTPAINT, + ), + ), + ), + exception_if_mldev="not supported in Gemini API", + ), + pytest_helper.TestTableItem( + name="test_all_parameters_mldev", + parameters=types._GenerateVideosParameters( + model=VEO_MODEL_2, + prompt="A neon hologram of a cat driving at top speed", + config=types.GenerateVideosConfig( + number_of_videos=1, + duration_seconds=6, + aspect_ratio="16:9", + person_generation="allow_adult", + negative_prompt="ugly, low quality", + enhance_prompt=True, + ), + ), + ), + pytest_helper.TestTableItem( + name="test_all_parameters_veo3_mldev", + parameters=types._GenerateVideosParameters( + model=VEO_MODEL_LATEST, + prompt="A neon hologram of a cat driving at top speed", + config=types.GenerateVideosConfig( + number_of_videos=1, + aspect_ratio="16:9", + resolution="1080p", + negative_prompt="ugly, low quality", + ), + ), + ), + pytest_helper.TestTableItem( + name="test_reference_to_video", + parameters=types._GenerateVideosParameters( + model=VEO_MODEL_LATEST, + prompt="Rain", + config=types.GenerateVideosConfig( + output_gcs_uri=OUTPUT_GCS_URI, + reference_images=[ + types.VideoGenerationReferenceImage( + image=GCS_IMAGE, + reference_type=types.VideoGenerationReferenceType.ASSET, + ) + ], + ), + ), + exception_if_mldev=( + "output_gcs_uri parameter is not supported in Gemini API" + ), + ), + pytest_helper.TestTableItem( + name="test_with_webhook_config", + parameters=types._GenerateVideosParameters( + model=VEO_MODEL_LATEST, + prompt="Man with a dog", + config=types.GenerateVideosConfig( + number_of_videos=1, + webhook_config=types.WebhookConfig( + uris=["https://example.com/webhook"], + user_metadata={"job_id": "video_123"}, + ), + ), + ), + exception_if_vertex=( + "webhook_config parameter is not supported in Vertex AI" + ), + ), + pytest_helper.TestTableItem( + name="test_with_webhook_config_dict", + parameters=types._GenerateVideosParameters( + model=VEO_MODEL_LATEST, + prompt="Man with a dog", + config={ + "number_of_videos": 1, + "webhook_config": { + "uris": ["https://example.com/webhook"], + }, + }, + ), + exception_if_vertex=( + "webhook_config parameter is not supported in Vertex AI" + ), + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method="models.generate_videos", + test_table=test_table, +) + + +def test_text_to_video_poll(client): + operation = client.models.generate_videos( + model=VEO_MODEL_LATEST, + prompt="A neon hologram of a cat driving at top speed", + config=types.GenerateVideosConfig( + output_gcs_uri=OUTPUT_GCS_URI if client.vertexai else None, + ), + ) + while not operation.done: + # Skip the sleep when in replay mode. + if client._api_client._mode not in ("replay", "auto"): + time.sleep(20) + operation = client.operations.get(operation=operation) + + assert operation.result.generated_videos[0].video.uri + + +def test_image_to_video_poll(client): + operation = client.models.generate_videos( + model=VEO_MODEL_LATEST, + image=GCS_IMAGE if client.vertexai else LOCAL_IMAGE, + config=types.GenerateVideosConfig( + output_gcs_uri=OUTPUT_GCS_URI if client.vertexai else None, + ), + ) + while not operation.done: + # Skip the sleep when in replay mode. + if client._api_client._mode not in ("replay", "auto"): + time.sleep(20) + operation = client.operations.get(operation=operation) + + assert operation.result.generated_videos[0].video.uri + + +def test_text_and_image_to_video_poll(client): + operation = client.models.generate_videos( + model=VEO_MODEL_LATEST, + prompt="Lightning storm", + image=GCS_IMAGE if client.vertexai else LOCAL_IMAGE, + config=types.GenerateVideosConfig( + output_gcs_uri=OUTPUT_GCS_URI if client.vertexai else None, + ), + ) + while not operation.done: + # Skip the sleep when in replay mode. + if client._api_client._mode not in ("replay", "auto"): + time.sleep(20) + operation = client.operations.get(operation=operation) + + assert operation.result.generated_videos[0].video.uri + + +def test_video_to_video_poll(client): + # GCS URI video input is only supported in Vertex AI. + if not client.vertexai: + return + + operation = client.models.generate_videos( + model=VEO_MODEL_2, + video=types.Video( + uri="gs://genai-sdk-tests/inputs/videos/cat_driving.mp4", + mime_type="video/mp4", + ), + config=types.GenerateVideosConfig( + output_gcs_uri=OUTPUT_GCS_URI, + ), + ) + while not operation.done: + # Skip the sleep when in replay mode. + if client._api_client._mode not in ("replay", "auto"): + time.sleep(20) + operation = client.operations.get(operation=operation) + + assert operation.result.generated_videos[0].video.uri + + +def test_text_and_video_to_video_poll(client): + # GCS URI video input is only supported in Vertex AI. + if not client.vertexai: + return + + operation = client.models.generate_videos( + model=VEO_MODEL_2, + prompt="Rain", + video=types.Video( + uri="gs://genai-sdk-tests/inputs/videos/cat_driving.mp4", + mime_type="video/mp4", + ), + config=types.GenerateVideosConfig( + output_gcs_uri=OUTPUT_GCS_URI, + ), + ) + while not operation.done: + # Skip the sleep when in replay mode. + if client._api_client._mode not in ("replay", "auto"): + time.sleep(20) + operation = client.operations.get(operation=operation) + + assert operation.result.generated_videos[0].video.uri + + +def test_generated_video_extension_poll(client): + # Gemini API only supports video extension on generated videos. + if client.vertexai: + return + + operation1 = client.models.generate_videos( + model=VEO_MODEL_LATEST, + prompt="Rain", + config=types.GenerateVideosConfig( + number_of_videos=1, + ), + ) + while not operation1.done: + # Skip the sleep when in replay mode. + if client._api_client._mode not in ("replay", "auto"): + time.sleep(20) + operation1 = client.operations.get(operation=operation1) + + video1 = operation1.result.generated_videos[0].video + assert video1.uri + client.files.download(file=video1) + assert video1.video_bytes + + operation2 = client.models.generate_videos( + model=VEO_MODEL_LATEST, + prompt="Sun", + video=video1, + config=types.GenerateVideosConfig( + number_of_videos=1, + ), + ) + while not operation2.done: + # Skip the sleep when in replay mode. + if client._api_client._mode not in ("replay", "auto"): + time.sleep(20) + operation2 = client.operations.get(operation=operation2) + + video2 = operation2.result.generated_videos[0].video + assert video2.uri + client.files.download(file=video2) + assert video2.video_bytes + + +def test_generated_video_extension_from_source_poll(client): + # Gemini API only supports video extension on generated videos. + if client.vertexai: + return + + operation1 = client.models.generate_videos( + model=VEO_MODEL_LATEST, + prompt="Rain", + config=types.GenerateVideosConfig( + number_of_videos=1, + ), + ) + while not operation1.done: + # Skip the sleep when in replay mode. + if client._api_client._mode not in ("replay", "auto"): + time.sleep(20) + operation1 = client.operations.get(operation=operation1) + + video1 = operation1.result.generated_videos[0].video + assert video1.uri + client.files.download(file=video1) + assert video1.video_bytes + + operation2 = client.models.generate_videos( + model=VEO_MODEL_LATEST, + source=types.GenerateVideosSource( + prompt="Sun", + video=video1 + ), + config=types.GenerateVideosConfig( + number_of_videos=1, + ), + ) + while not operation2.done: + # Skip the sleep when in replay mode. + if client._api_client._mode not in ("replay", "auto"): + time.sleep(20) + operation2 = client.operations.get(operation=operation2) + + video2 = operation2.result.generated_videos[0].video + assert video2.uri + client.files.download(file=video2) + assert video2.video_bytes + + +def test_generated_video_extension_from_source_dict_poll(client): + # Gemini API only supports video extension on generated videos. + if client.vertexai: + return + + operation1 = client.models.generate_videos( + model=VEO_MODEL_LATEST, + prompt="Rain", + config=types.GenerateVideosConfig( + number_of_videos=1, + ), + ) + while not operation1.done: + # Skip the sleep when in replay mode. + if client._api_client._mode not in ("replay", "auto"): + time.sleep(20) + operation1 = client.operations.get(operation=operation1) + + video1 = operation1.result.generated_videos[0].video + assert video1.uri + client.files.download(file=video1) + assert video1.video_bytes + + operation2 = client.models.generate_videos( + model=VEO_MODEL_LATEST, + source={ + "prompt": "Sun", + "video": video1, + }, + config=types.GenerateVideosConfig( + number_of_videos=1, + ), + ) + while not operation2.done: + # Skip the sleep when in replay mode. + if client._api_client._mode not in ("replay", "auto"): + time.sleep(20) + operation2 = client.operations.get(operation=operation2) + + video2 = operation2.result.generated_videos[0].video + assert video2.uri + client.files.download(file=video2) + assert video2.video_bytes + + +def test_image_to_video_frame_interpolation_poll(client): + operation = client.models.generate_videos( + model=VEO_MODEL_LATEST, + prompt="Rain", + image=GCS_IMAGE if client.vertexai else LOCAL_IMAGE_MAN, + config=types.GenerateVideosConfig( + output_gcs_uri=OUTPUT_GCS_URI if client.vertexai else None, + last_frame=GCS_IMAGE2 if client.vertexai else LOCAL_IMAGE_DOG, + ), + ) + while not operation.done: + # Skip the sleep when in replay mode. + if client._api_client._mode not in ("replay", "auto"): + time.sleep(20) + operation = client.operations.get(operation=operation) + + assert operation.result.generated_videos[0].video.uri + + +def test_reference_images_to_video_poll(client): + operation = client.models.generate_videos( + model=VEO_MODEL_LATEST, + prompt="Chirping birds in a colorful forest", + config=types.GenerateVideosConfig( + output_gcs_uri=OUTPUT_GCS_URI if client.vertexai else None, + reference_images=[ + types.VideoGenerationReferenceImage( + image=GCS_IMAGE if client.vertexai else LOCAL_IMAGE_MAN, + reference_type=types.VideoGenerationReferenceType.ASSET, + ), + ], + ), + ) + while not operation.done: + # Skip the sleep when in replay mode. + if client._api_client._mode not in ("replay", "auto"): + time.sleep(20) + operation = client.operations.get(operation=operation) + + assert operation.result.generated_videos[0].video.uri + + +def test_video_edit_outpaint_poll(client): + # Editing videos is only supported in Vertex AI. + if not client.vertexai: + return + + operation = client.models.generate_videos( + model=VEO_MODEL_2_EXP, + source=types.GenerateVideosSource( + prompt="A mountain landscape", + video=types.Video( + uri="gs://genai-sdk-tests/inputs/videos/editing_demo.mp4", + mime_type="video/mp4", + ), + ), + config=types.GenerateVideosConfig( + output_gcs_uri=OUTPUT_GCS_URI, + aspect_ratio="16:9", + mask=types.VideoGenerationMask( + image=GCS_OUTPAINT_MASK, + mask_mode=types.VideoGenerationMaskMode.OUTPAINT, + ), + ), + ) + while not operation.done: + # Skip the sleep when in replay mode. + if client._api_client._mode not in ("replay", "auto"): + time.sleep(20) + operation = client.operations.get(operation=operation) + + assert operation.result.generated_videos[0].video.uri + + +def test_video_edit_remove_poll(client): + # Editing videos is only supported in Vertex AI. + if not client.vertexai: + return + + operation = client.models.generate_videos( + model=VEO_MODEL_2_EXP, + source=types.GenerateVideosSource( + prompt="A red dune buggy", + video=types.Video( + uri="gs://genai-sdk-tests/inputs/videos/editing_demo.mp4", + mime_type="video/mp4", + ), + ), + config=types.GenerateVideosConfig( + output_gcs_uri=OUTPUT_GCS_URI, + aspect_ratio="16:9", + mask=types.VideoGenerationMask( + image=GCS_REMOVE_MASK, + mask_mode=types.VideoGenerationMaskMode.REMOVE, + ), + ), + ) + while not operation.done: + # Skip the sleep when in replay mode. + if client._api_client._mode not in ("replay", "auto"): + time.sleep(20) + operation = client.operations.get(operation=operation) + + assert operation.result.generated_videos[0].video.uri + + +def test_video_edit_remove_static_poll(client): + # Editing videos is only supported in Vertex AI. + if not client.vertexai: + return + + operation = client.models.generate_videos( + model=VEO_MODEL_2_EXP, + source=types.GenerateVideosSource( + prompt="A red dune buggy", + video=types.Video( + uri="gs://genai-sdk-tests/inputs/videos/editing_demo.mp4", + mime_type="video/mp4", + ), + ), + config=types.GenerateVideosConfig( + output_gcs_uri=OUTPUT_GCS_URI, + aspect_ratio="16:9", + mask=types.VideoGenerationMask( + image=GCS_REMOVE_STATIC_MASK, + mask_mode=types.VideoGenerationMaskMode.REMOVE_STATIC, + ), + ), + ) + while not operation.done: + # Skip the sleep when in replay mode. + if client._api_client._mode not in ("replay", "auto"): + time.sleep(20) + operation = client.operations.get(operation=operation) + + assert operation.result.generated_videos[0].video.uri + + +def test_video_edit_insert_poll(client): + # Editing videos is only supported in Vertex AI. + if not client.vertexai: + return + + operation = client.models.generate_videos( + model=VEO_MODEL_2_EXP, + source=types.GenerateVideosSource( + prompt="Bike", + video=types.Video( + uri="gs://genai-sdk-tests/inputs/videos/editing_demo.mp4", + mime_type="video/mp4", + ), + ), + config=types.GenerateVideosConfig( + output_gcs_uri=OUTPUT_GCS_URI, + aspect_ratio="16:9", + mask=types.VideoGenerationMask( + # Insert and remove masks are the same for this input. + image=GCS_REMOVE_MASK, + mask_mode=types.VideoGenerationMaskMode.INSERT, + ), + ), + ) + while not operation.done: + # Skip the sleep when in replay mode. + if client._api_client._mode not in ("replay", "auto"): + time.sleep(20) + operation = client.operations.get(operation=operation) + + assert operation.result.generated_videos[0].video.uri + + +def test_create_operation_to_poll(client): + if client.vertexai: + # Fill in project and location for record mode + operation_name = "projects//locations//publishers/google/models/veo-3.1-generate-preview/operations/9d2fc0b5-5bdf-4b5f-9a41-82970515e20b" + else: + operation_name = "models/veo-3.1-generate-preview/operations/vz341u0pmdlc" + + operation = types.GenerateVideosOperation( + name=operation_name, + ) + operation = client.operations.get(operation=operation) + while not operation.done: + # Skip the sleep when in replay mode. + if client._api_client._mode not in ("replay", "auto"): + time.sleep(20) + operation = client.operations.get(operation=operation) + + assert operation.result.generated_videos[0].video.uri + + +def test_source_and_prompt_raises(client): + with pytest.raises(ValueError): + client.models.generate_videos( + model=VEO_MODEL_LATEST, + prompt="Prompt 1", + source=types.GenerateVideosSource(prompt="Prompt 2"), + ) + + +@pytest.mark.asyncio +async def test_text_to_video_poll_async(client): + operation = await client.aio.models.generate_videos( + model=VEO_MODEL_LATEST, + prompt="A neon hologram of a cat driving at top speed", + config=types.GenerateVideosConfig( + output_gcs_uri=OUTPUT_GCS_URI if client.vertexai else None, + ), + ) + while not operation.done: + # Skip the sleep when in replay mode. + if client._api_client._mode not in ("replay", "auto"): + time.sleep(20) + operation = await client.aio.operations.get(operation=operation) + + assert operation.result.generated_videos[0].video.uri + + +@pytest.mark.asyncio +async def test_generated_video_extension_from_source_poll_async(client): + # Gemini API only supports video extension on generated videos. + if client.vertexai: + return + + operation1 = await client.aio.models.generate_videos( + model=VEO_MODEL_LATEST, + prompt="Rain", + config=types.GenerateVideosConfig( + number_of_videos=1, + ), + ) + while not operation1.done: + # Skip the sleep when in replay mode. + if client._api_client._mode not in ("replay", "auto"): + time.sleep(20) + operation1 = await client.aio.operations.get(operation=operation1) + + video1 = operation1.result.generated_videos[0].video + assert video1.uri + assert await client.aio.files.download(file=video1) + + operation2 = await client.aio.models.generate_videos( + model=VEO_MODEL_LATEST, + source=types.GenerateVideosSource( + prompt="Sun", + video=video1 + ), + config=types.GenerateVideosConfig( + number_of_videos=1, + ), + ) + while not operation2.done: + # Skip the sleep when in replay mode. + if client._api_client._mode not in ("replay", "auto"): + time.sleep(20) + operation2 = await client.aio.operations.get(operation=operation2) + + video2 = operation2.result.generated_videos[0].video + assert video2.uri + assert await client.aio.files.download(file=video2) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_get.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_get.py new file mode 100644 index 0000000000000000000000000000000000000000..41dca9bf4d5092fcd693d48b4446b51e6973e867 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_get.py @@ -0,0 +1,104 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for models.get.""" + +import pytest +from ... import errors +from ... import types +from .. import pytest_helper + + +test_http_options = {'api_version': 'v1', 'headers': {'test': 'headers'}} + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_get_vertex_tuned_model', + parameters=types._GetModelParameters( + model='models/2171259487439028224' + ), + exception_if_mldev='404', + ), + pytest_helper.TestTableItem( + name='test_get_mldev_tuned_model', + parameters=types._GetModelParameters( + model='tunedModels/generatenum5443-ekrw7ie9wis23zbeogbw6jq8' + ), + exception_if_vertex='404', + ), + pytest_helper.TestTableItem( + name='test_get_vertex_tuned_model_with_http_options_in_method', + parameters=types._GetModelParameters( + model='models/2171259487439028224', + config={ + 'http_options': test_http_options, + }, + ), + exception_if_mldev='404', + ), + pytest_helper.TestTableItem( + name='test_get_mldev_base_model_with_http_options_in_method', + parameters=types._GetModelParameters( + model='gemini-2.5-flash', + config={ + 'http_options': test_http_options, + }, + ), + ), + pytest_helper.TestTableItem( + name='test_get_base_model', + parameters=types._GetModelParameters(model='gemini-2.5-flash'), + ), + pytest_helper.TestTableItem( + name='test_get_base_model_with_models_prefix', + parameters=types._GetModelParameters(model='models/gemini-2.5-flash'), + exception_if_vertex='400', + ), +] +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='models.get', + test_table=test_table, +) + + +@pytest.mark.asyncio +async def test_async_get_tuned_model(client): + if client._api_client.vertexai: + with pytest.raises(errors.ClientError) as e: + await client.aio.models.get(model='tunedModels/generate-num-1896') + assert '404' in str(e) + else: + response = await client.aio.models.get( + model='tunedModels/generate-num-1896' + ) + + +@pytest.mark.asyncio +async def test_async_get_model(client): + if client._api_client.vertexai: + response = await client.aio.models.get( + model='models/7687416965014487040', + config={'http_options': test_http_options}, + ) + else: + with pytest.raises(errors.ClientError) as e: + await client.aio.models.get( + model='models/7687416965014487040', + config={'http_options': test_http_options}, + ) + assert '404' in str(e) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_list.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_list.py new file mode 100644 index 0000000000000000000000000000000000000000..06a196b1f8f08c09a40e2b27948bb868bfe5d910 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_list.py @@ -0,0 +1,233 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for models.list.""" + +from unittest import mock + +import pytest + +from ... import client as genai_client +from ... import _api_client +from ... import types +from .. import pytest_helper + +test_http_options = {'headers': {'test': 'headers'}} + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_tuned_models', + parameters=types._ListModelsParameters( + config={'query_base': False, 'page_size': 3} + ), + ), + pytest_helper.TestTableItem( + name='test_tuned_models_with_filter', + parameters=types._ListModelsParameters( + config={'query_base': False, + 'page_size': 3, + 'filter': 'displayName="gemini-2.5-flash-1b0689e3-9773-43b4-97eb-c8140d5f183b"'} + ), + ), + pytest_helper.TestTableItem( + name='test_base_models', + parameters=types._ListModelsParameters(), + ), + pytest_helper.TestTableItem( + name='test_base_models_with_config', + parameters=types._ListModelsParameters(config={'query_base': True, 'page_size': 10}), + ), + pytest_helper.TestTableItem( + name='test_with_config', + parameters=types._ListModelsParameters(config={'page_size': 3}), + ), + pytest_helper.TestTableItem( + name='test_list_models_with_http_options_in_method', + parameters=types._ListModelsParameters( + config={'page_size': 3, 'http_options': test_http_options} + ), + ), +] +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='models.list', + test_table=test_table, +) + + +@pytest.fixture() +def mock_api_client(): + api_client = mock.MagicMock(spec=genai_client.BaseApiClient) + api_client.api_key = 'fake_api_key' + api_client._host = lambda: 'fake_host' + api_client._http_options = {'headers': {}} + api_client.vertexai = False + return api_client + + +def test_tuned_models_pager(client): + pager = client.models.list(config={'page_size': 10}) + + assert pager.name == 'models' + assert pager.page_size == 10 + assert len(pager) <= 10 + + # Iterate through all the pages. Then next_page() should raise an exception. + for _ in pager: + pass + with pytest.raises(IndexError, match='No more pages to fetch.'): + pager.next_page() + + +def test_base_models_pager(client): + pager = client.models.list(config={'page_size': 10, 'query_base': True}) + + assert pager.name == 'models' + assert pager.page_size == 10 + assert len(pager) <= 10 + + # Iterate through all the pages. Then next_page() should raise an exception. + for _ in pager: + assert 'content-type' in pager.sdk_http_response.headers + assert 'content-encoding' in pager.sdk_http_response.headers + pass + with pytest.raises(IndexError, match='No more pages to fetch.'): + pager.next_page() + + +def test_base_response_with_empty_json_payload_and_http_headers( + mock_api_client, client +): + with mock.patch.object( + genai_client.Client, '_get_api_client' + ) as patch_api_client: + patch_api_client.return_value = mock_api_client + mock_client = genai_client.Client() + sdk_http_response = types.HttpResponse( + headers={'header_key': 'header_value'}, + body='{}', + ) + with mock.patch.object( + mock_api_client, 'request', return_value=sdk_http_response + ): + pager = mock_client.models.list() + + assert len(pager) == 0 + + +def test_unknown_json_payload(mock_api_client, client): + with mock.patch.object( + genai_client.Client, '_get_api_client' + ) as patch_api_client: + patch_api_client.return_value = mock_api_client + mock_client = genai_client.Client() + sdk_http_response = types.HttpResponse( + headers={'header_key': 'header_value'}, + body='{"unknown_key": "unknown_value"}', + ) + with mock.patch.object( + mock_api_client, 'request', return_value=sdk_http_response + ) : + pager = mock_client.models.list() + + assert len(pager) == 0 + + +def test_empty_json_payload(mock_api_client, client): + with mock.patch.object( + genai_client.Client, '_get_api_client' + ) as patch_api_client: + patch_api_client.return_value = mock_api_client + mock_client = genai_client.Client() + sdk_http_response = types.HttpResponse( + headers={'header_key': 'header_value'}, + body='', + ) + with mock.patch.object( + mock_api_client, 'request', return_value=sdk_http_response + ) : + pager = mock_client.models.list() + + assert len(pager) == 0 + + +def test_empty_api_response_none_headers(mock_api_client, client): + with mock.patch.object( + genai_client.Client, '_get_api_client' + ) as patch_api_client: + patch_api_client.return_value = mock_api_client + mock_client = genai_client.Client() + sdk_http_response = types.HttpResponse( + headers=None, + body='{}', + ) + with mock.patch.object( + mock_api_client, 'request', return_value=sdk_http_response + ): + pager = mock_client.models.list() + + assert len(pager) == 0 + + +def test_empty_api_response_empty_dict_headers(mock_api_client, client): + with mock.patch.object( + genai_client.Client, '_get_api_client' + ) as patch_api_client: + patch_api_client.return_value = mock_api_client + mock_client = genai_client.Client() + sdk_http_response = types.HttpResponse( + headers={}, + body='{}', + ) + with mock.patch.object( + mock_api_client, 'request', return_value=sdk_http_response + ): + pager = mock_client.models.list() + + assert len(pager) == 0 + + +@pytest.mark.asyncio +async def test_tuned_models_async_pager(client): + pager = await client.aio.models.list(config={'page_size': 3, 'query_base': False}) + + assert 'Content-Type' in pager.sdk_http_response.headers + assert 'Content-Encoding' in pager.sdk_http_response.headers + assert pager.name == 'models' + assert pager.page_size == 3 + assert len(pager) <= 3 + + # Iterate through all the pages. Then next_page() should raise an exception. + async for _ in pager: + pass + with pytest.raises(IndexError, match='No more pages to fetch.'): + await pager.next_page() + + +@pytest.mark.asyncio +async def test_base_models_async_pager(client): + pager = await client.aio.models.list(config={'page_size': 10}) + + assert pager.name == 'models' + assert pager.page_size == 10 + assert len(pager) <= 10 + + # Iterate through all the pages. Then next_page() should raise an exception. + async for _ in pager: + pass + with pytest.raises(IndexError, match='No more pages to fetch.'): + await pager.next_page() diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_recontext_image.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_recontext_image.py new file mode 100644 index 0000000000000000000000000000000000000000..94fa7d52a438fa1b70cd1d42305bb2083a7c1307 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_recontext_image.py @@ -0,0 +1,104 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for recontext_image.""" + +import pytest + +from ... import types +from .. import pytest_helper + +VIRTUAL_TRY_ON_IMAGE_MODEL_LATEST = 'virtual-try-on-001' + +PERSON_IMAGE = types.Image( + gcs_uri='gs://genai-sdk-tests/inputs/images/man.jpg', +) + +PANTS = types.Image( + gcs_uri='gs://genai-sdk-tests/inputs/images/pants.jpg', +) + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_virtual_try_on', + exception_if_mldev='only supported in the Vertex AI client', + parameters=types._RecontextImageParameters( + model=VIRTUAL_TRY_ON_IMAGE_MODEL_LATEST, + source=types.RecontextImageSource( + person_image=PERSON_IMAGE, + product_images=[ + types.ProductImage(product_image=PANTS) + ], + ), + config=types.RecontextImageConfig( + number_of_images=1, + output_mime_type='image/jpeg', + ), + ), + ), + pytest_helper.TestTableItem( + name='test_virtual_try_on_all_config', + exception_if_mldev='only supported in the Vertex AI client', + parameters=types._RecontextImageParameters( + model=VIRTUAL_TRY_ON_IMAGE_MODEL_LATEST, + source=types.RecontextImageSource( + person_image=PERSON_IMAGE, + product_images=[ + types.ProductImage( + product_image=PANTS + ) + ], + ), + config=types.RecontextImageConfig( + number_of_images=1, + output_mime_type='image/jpeg', + base_steps=32, + seed=1337, + add_watermark=False, + safety_filter_level=types.SafetyFilterLevel.BLOCK_MEDIUM_AND_ABOVE, + person_generation=types.PersonGeneration.ALLOW_ADULT, + output_compression_quality=75, + enhance_prompt=False, + ), + ), + ), +] +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='models.recontext_image', + test_table=test_table, +) + + +@pytest.mark.asyncio +async def test_virtual_try_on_async(client): + with pytest_helper.exception_if_mldev(client, ValueError): + response = await client.aio.models.recontext_image( + model=VIRTUAL_TRY_ON_IMAGE_MODEL_LATEST, + source=types.RecontextImageSource( + person_image=PERSON_IMAGE, + product_images=[ + types.ProductImage(product_image=PANTS) + ], + ), + config=types.RecontextImageConfig( + number_of_images=1, + output_mime_type='image/jpeg', + ), + ) + assert len(response.generated_images) == 1 + assert response.generated_images[0].image.image_bytes diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_segment_image.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_segment_image.py new file mode 100644 index 0000000000000000000000000000000000000000..0d6d43ffa9fe4856d175b9868f1be43bffe9477a --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_segment_image.py @@ -0,0 +1,148 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for segment_image.""" + +import os + +import pytest + +from ... import types +from .. import pytest_helper + +SEGMENT_IMAGE_MODEL_LATEST = 'image-segmentation-001' + +SOURCE_IMAGE_FILE_PATH1 = os.path.abspath( + os.path.join(os.path.dirname(__file__), '../data/google.png') +) + +SOURCE_IMAGE1 = types.Image.from_file(location=SOURCE_IMAGE_FILE_PATH1) + +SOURCE_IMAGE_FILE_PATH2 = os.path.abspath( + os.path.join(os.path.dirname(__file__), '../data/skateboard_stop_sign.jpg') +) + +SOURCE_IMAGE2 = types.Image.from_file(location=SOURCE_IMAGE_FILE_PATH2) + +SCRIBBLE_IMAGE_FILE_PATH = os.path.abspath( + os.path.join(os.path.dirname(__file__), '../data/segmentation_scribble.jpg') +) + +SCRIBBLE_IMAGE = types.Image.from_file(location=SCRIBBLE_IMAGE_FILE_PATH) + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_segment_foreground', + exception_if_mldev='only supported in the Vertex AI client', + parameters=types._SegmentImageParameters( + model=SEGMENT_IMAGE_MODEL_LATEST, + source=types.SegmentImageSource( + image=SOURCE_IMAGE1, + ), + config=types.SegmentImageConfig( + mode=types.SegmentMode.FOREGROUND, + max_predictions=1, + confidence_threshold=0.02, + mask_dilation=0.02, + binary_color_threshold=98, + labels={'imagen_label_key': 'segment_image'} + ), + ), + ), + pytest_helper.TestTableItem( + name='test_segment_background', + exception_if_mldev='only supported in the Vertex AI client', + parameters=types._SegmentImageParameters( + model=SEGMENT_IMAGE_MODEL_LATEST, + source=types.SegmentImageSource( + image=SOURCE_IMAGE1, + ), + config=types.SegmentImageConfig( + mode=types.SegmentMode.BACKGROUND, + ), + ), + ), + pytest_helper.TestTableItem( + name='test_segment_prompt', + exception_if_mldev='only supported in the Vertex AI client', + parameters=types._SegmentImageParameters( + model=SEGMENT_IMAGE_MODEL_LATEST, + source=types.SegmentImageSource( + image=SOURCE_IMAGE1, + prompt='The letter G', + ), + config=types.SegmentImageConfig( + mode=types.SegmentMode.PROMPT, + ), + ), + ), + pytest_helper.TestTableItem( + name='test_segment_semantic', + exception_if_mldev='only supported in the Vertex AI client', + parameters=types._SegmentImageParameters( + model=SEGMENT_IMAGE_MODEL_LATEST, + source=types.SegmentImageSource( + image=SOURCE_IMAGE2, + prompt='skateboard', + ), + config=types.SegmentImageConfig( + mode=types.SegmentMode.SEMANTIC, + ), + ), + ), + pytest_helper.TestTableItem( + name='test_segment_interactive', + exception_if_mldev='only supported in the Vertex AI client', + parameters=types._SegmentImageParameters( + model=SEGMENT_IMAGE_MODEL_LATEST, + source=types.SegmentImageSource( + image=SOURCE_IMAGE2, + scribble_image=types.ScribbleImage(image=SCRIBBLE_IMAGE), + ), + config=types.SegmentImageConfig( + mode=types.SegmentMode.INTERACTIVE, + ), + ), + ), +] +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='models.segment_image', + test_table=test_table, +) + + +@pytest.mark.asyncio +async def test_segment_foreground_async(client): + with pytest_helper.exception_if_mldev(client, ValueError): + response = await client.aio.models.segment_image( + model=SEGMENT_IMAGE_MODEL_LATEST, + source=types.SegmentImageSource( + image=SOURCE_IMAGE2, + ), + config=types.SegmentImageConfig( + mode=types.SegmentMode.FOREGROUND, + max_predictions=1, + confidence_threshold=0.02, + mask_dilation=0.02, + binary_color_threshold=98, + ) + ) + assert response.generated_masks[0].mask.image_bytes + assert len(response.generated_masks) == 1 + assert response.generated_masks[0].labels[0].label == 'foreground' + assert response.generated_masks[0].labels[0].score > 0 diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_update.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_update.py new file mode 100644 index 0000000000000000000000000000000000000000..f9e6a1d0281b36a88a02eba50835796ae89fdc7e --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_update.py @@ -0,0 +1,95 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +import pytest +from ... import errors +from ... import types +from .. import pytest_helper + +test_http_options = {'headers': {'test': 'headers'}} + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_vertex_tuned_models_update', + parameters=types._UpdateModelParameters( + model='models/2171259487439028224', + config={ + 'description': ( + 'My SupervisedTuningJob' + ), + 'default_checkpoint_id': '8', + }, + ), + exception_if_mldev='404', + ), + pytest_helper.TestTableItem( + name='test_vertex_tuned_models_update_with_http_options_in_method', + parameters=types._UpdateModelParameters( + model='models/2171259487439028224', + config={ + 'description': ( + 'My SupervisedTuningJob' + ), + 'default_checkpoint_id': '8', + 'http_options': test_http_options, + }, + ), + exception_if_mldev='404', + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='models.update', + test_table=test_table, +) + + +@pytest.mark.asyncio +async def test_async_update_tuned_model(client): + if client._api_client.vertexai: + with pytest.raises(errors.ClientError) as e: + await client.aio.models.update( + model='tunedModels/generatenum5443-ekrw7ie9wis23zbeogbw6jq8', + config={ + 'description': 'My tuned gemini model', + 'http_options': test_http_options, + }, + ) + assert '404' in str(e) + + +@pytest.mark.asyncio +async def test_async_update_model(client): + if client._api_client.vertexai: + response = await client.aio.models.update( + model='models/2171259487439028224', + config={ + 'display_name': 'My tuned gemini model', + 'http_options': test_http_options, + }, + ) + else: + with pytest.raises(errors.ClientError) as e: + await client.aio.models.update( + model='models/2171259487439028224', + config={ + 'display_name': 'My tuned gemini model', + 'http_options': test_http_options, + }, + ) + assert '404' in str(e) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_upscale_image.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_upscale_image.py new file mode 100644 index 0000000000000000000000000000000000000000..2a21ec66cfb36c7cf4d99db0578624b6c9deabe2 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/models/test_upscale_image.py @@ -0,0 +1,157 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for upscale_image.""" + +import os + +from pydantic import ValidationError +import pytest + +from ... import types +from .. import pytest_helper + +IMAGEN_MODEL_LATEST = 'imagen-4.0-upscale-preview' + +IMAGE_FILE_PATH = os.path.abspath( + os.path.join(os.path.dirname(__file__), '../data/bridge1.png') +) + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_upscale_no_config', + exception_if_mldev='only supported in the Vertex AI client', + parameters=types.UpscaleImageParameters( + model=IMAGEN_MODEL_LATEST, + image=types.Image.from_file(location=IMAGE_FILE_PATH), + upscale_factor='x2', + ), + ), + pytest_helper.TestTableItem( + name='test_upscale', + exception_if_mldev='only supported in the Vertex AI client', + parameters=types.UpscaleImageParameters( + model=IMAGEN_MODEL_LATEST, + image=types.Image.from_file(location=IMAGE_FILE_PATH), + upscale_factor='x2', + config=types.UpscaleImageConfig( + include_rai_reason=True, + person_generation=types.PersonGeneration.ALLOW_ADULT, + safety_filter_level=types.SafetyFilterLevel.BLOCK_LOW_AND_ABOVE, + output_mime_type='image/jpeg', + output_compression_quality=80, + enhance_input_image=True, + image_preservation_factor=0.6, + labels={'imagen_label_key': 'upscale_image'} + ), + ), + ), + pytest_helper.TestTableItem( + name='test_upscale_gcs', + exception_if_mldev='only supported in the Vertex AI client', + parameters=types.UpscaleImageParameters( + model=IMAGEN_MODEL_LATEST, + image=types.Image.from_file(location=IMAGE_FILE_PATH), + upscale_factor='x2', + config=types.UpscaleImageConfig( + output_gcs_uri='gs://genai-sdk-tests/temp/images/', + ), + ), + ), +] +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='models.upscale_image', + test_table=test_table, +) + + +def test_upscale_extra_config_parameters(client): + # MLDev currently does not support upscale_image, but the ValidationError + # occurs before the ValueError. + try: + # User is not allowed to set mode or number_of_images + client.models.upscale_image( + model=IMAGEN_MODEL_LATEST, + image=types.Image.from_file(location=IMAGE_FILE_PATH), + upscale_factor='x2', + config={ + 'mode': 'upscale', + 'number_of_images': 1, + } + ) + # Should never reach this. + assert False + except Exception as e: + assert isinstance(e, ValidationError) + assert 'Extra inputs are not permitted' in str(e) + + +@pytest.mark.asyncio +async def test_upscale_async(client): + with pytest_helper.exception_if_mldev(client, ValueError): + response = await client.aio.models.upscale_image( + model=IMAGEN_MODEL_LATEST, + image=types.Image.from_file(location=IMAGE_FILE_PATH), + upscale_factor='x2', + config=types.UpscaleImageConfig( + person_generation=types.PersonGeneration.ALLOW_ADULT, + safety_filter_level=types.SafetyFilterLevel.BLOCK_LOW_AND_ABOVE, + include_rai_reason=True, + output_mime_type='image/jpeg', + output_compression_quality=80, + enhance_input_image=True, + image_preservation_factor=0.6, + ), + ) + assert response.generated_images[0].image.image_bytes + + +@pytest.mark.asyncio +async def test_upscale_gcs_async(client): + with pytest_helper.exception_if_mldev(client, ValueError): + response = await client.aio.models.upscale_image( + model=IMAGEN_MODEL_LATEST, + image=types.Image.from_file(location=IMAGE_FILE_PATH), + upscale_factor='x2', + config=types.UpscaleImageConfig( + output_gcs_uri='gs://genai-sdk-tests/temp/images/', + ), + ) + assert response.generated_images[0].image.gcs_uri + + +@pytest.mark.asyncio +async def test_upscale_extra_config_parameters_async(client): + # MLDev currently does not support upscale_image, but the ValidationError + # occurs before the ValueError. + try: + # User is not allowed to set mode or number_of_images + await client.aio.models.upscale_image( + model=IMAGEN_MODEL_LATEST, + image=types.Image.from_file(location=IMAGE_FILE_PATH), + upscale_factor='x2', + config={ + 'mode': 'upscale', + 'number_of_images': 1, + }, + ) + # Should never reach this. + assert False + except Exception as e: + assert isinstance(e, ValidationError) + assert 'Extra inputs are not permitted' in str(e) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/operations/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/operations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b609d4865ea4c3693f7b6c6485be879d7968194d --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/operations/__init__.py @@ -0,0 +1,17 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for operations.get.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/operations/test_get.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/operations/test_get.py new file mode 100644 index 0000000000000000000000000000000000000000..36b1e08fab612fcd1e55d824dd0c48d4140b3ae5 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/operations/test_get.py @@ -0,0 +1,38 @@ + # Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for operations._get.""" + +from .. import pytest_helper +from ... import types + + +def test_project_operation_get(client): + test_operation_id = '3787416390563004416' + if client._api_client.vertexai: + operation = client.operations._get( + operation_id=test_operation_id + ) + assert operation.name.endswith(test_operation_id) + assert operation.done + assert isinstance(operation, types.ProjectOperation) + + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='operations._get', +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/public_samples/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/public_samples/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..27f10d2aa508bce746682fa28e238221e7226095 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/public_samples/__init__.py @@ -0,0 +1,17 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Public Samples and Tests for the Google GenAI SDK.""" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/public_samples/test_gemini_text_only.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/public_samples/test_gemini_text_only.py new file mode 100644 index 0000000000000000000000000000000000000000..ea9cb2127d37262a3665113694485b4fb02e850b --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/public_samples/test_gemini_text_only.py @@ -0,0 +1,34 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Test for the code sample for Gemini text-only request.""" + +from .. import pytest_helper + +pytestmark = pytest_helper.setup(file=__file__) + + +def test_sample(client): + # [START generativeaionvertexai_gemini_text_only] + response = client.models.generate_content( + model="gemini-2.5-flash", + contents=( + "What's a good name for a flower shop that specializes in selling" + " bouquets of dried flowers?" + ), + ) + print(response.text) + # [END generativeaionvertexai_gemini_text_only] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/pytest_helper.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/pytest_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..17076cd829bd2a32e04abac11cf20ee533de937c --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/pytest_helper.py @@ -0,0 +1,246 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +import contextlib +import json +import os +import pathlib +from typing import Any, Optional +from pydantic import BaseModel, Field, SerializeAsAny +import pytest +import re +from .. import _common +from .. import _replay_api_client +from .. import types +from .._api_client import HttpOptions + +is_api_mode = "config.getoption('--mode') == 'api'" + + +class TestTableItem(types.TestTableItem): + # This is not a test suite class. + __test__ = False + + # Overrides to support Pydantic models. + parameters: SerializeAsAny[BaseModel] = Field( + description="""The parameters to the test. Use pydantic models.""", + ) + + +def base_test_function( + client, + use_vertex: bool, + replays_prefix: str, + test_method: str, + test_table_item: TestTableItem, + globals_for_file: dict[str, Any], +): + replay_id = ( + test_table_item.override_replay_id + if test_table_item.override_replay_id + else test_table_item.name + ) + api_type = 'vertex' if use_vertex else 'mldev' + replay_id = f'{replays_prefix}/{replay_id}.{api_type}' + client._api_client.initialize_replay_session(replay_id) + # vars().copy() provides a shallow copy of the parameters. + parameters_dict = vars(test_table_item.parameters).copy() + try: + if '.' in test_method: + method_name_parts = test_method.split('.') + module_path_parts = method_name_parts[:-1] + method_name = method_name_parts[-1] + # Iterates the nested module starting from client + current_object = client + for part in module_path_parts: + current_object = getattr(current_object, part) + method = getattr(current_object, method_name) + method(**parameters_dict) + else: + custom_method = globals_for_file[test_method] + custom_method(client, test_table_item.parameters) + # Should not reach here if expecting an exception. + if test_table_item.exception_if_mldev and not client._api_client.vertexai: + assert False, 'Should have raised exception in MLDev.' + elif test_table_item.exception_if_vertex and client._api_client.vertexai: + assert False, 'Should have raised exception in Vertex.' + client._api_client.close() + except Exception as e: + if test_table_item.exception_if_mldev and not client._api_client.vertexai: + if test_table_item.exception_if_mldev not in str(e): + raise AssertionError( + f"'{test_table_item.exception_if_mldev}' not in '{str(e)}'" + ) from e + elif test_table_item.exception_if_vertex and client._api_client.vertexai: + if test_table_item.exception_if_vertex not in str(e): + raise AssertionError( + f"'{test_table_item.exception_if_vertex}' not in '{str(e)}'" + ) from e + else: + raise e + + +def create_test_for_table_item( + globals_for_file: dict[str, Any], + test_method: str, + test_table_item: TestTableItem, +): + return lambda client, use_vertex, replays_prefix: base_test_function( + client, + use_vertex, + replays_prefix, + test_method, + test_table_item, + globals_for_file, + ) + + +def create_test_for_table( + globals_for_file: dict[str, Any], + test_method: str, + test_table: list[TestTableItem], +): + for test_table_item in test_table: + if test_table_item.has_union: + assert test_table_item.name.startswith('test_union_'), f""" + test: {test_table_item.name} + When has_union is true, it must be a test that explicitly test the + non-canonical type in the union. + For all other tests, use transformers to convert data to the canonical + type of the field so it can be tested in other languages. + If this test is truly about testing the non-canonical type of the union, + rename the test to start with 'test_union_'. E.g. + test_union_contents_is_string()""" + globals_for_file[test_table_item.name] = create_test_for_table_item( + globals_for_file, test_method, test_table_item + ) + + +# Sets up the test framework. +# file: Always use __file__ +# globals_for_file: Always use globals() +# test_table: The test table for the file. +# Use test table over individual tests whenever possible. +# Tests built with test_table will run in all other languages automatically. +# Otherwise, you will need to write tests in all other languages manually. +def setup( + *, + file: str, + globals_for_file: Optional[dict[str, Any]] = None, + test_method: Optional[str] = None, + test_table: Optional[list[TestTableItem]] = None, + http_options: Optional[HttpOptions] = None, +): + """Generates parameterization for tests, run for both Vertex and MLDev.""" + replays_directory = ( + file.replace(os.path.dirname(__file__), 'tests') + .replace('.py', '') + .replace('/test_', '/') + ) + + is_tap_mode = False + if os.environ.get('UNITTEST_ON_FORGE', None) is not None: + is_tap_mode = True + + if test_table: + create_test_for_table(globals_for_file, test_method, test_table) + + if test_table and not is_tap_mode: + replays_root_directory = os.environ.get( + 'GOOGLE_GENAI_REPLAYS_DIRECTORY', None + ) + if replays_root_directory is None: + raise ValueError( + 'GOOGLE_GENAI_REPLAYS_DIRECTORY environment variable is not set' + ) + abs_replay_directory = os.path.join( + replays_root_directory, replays_directory + ) + test_table_file_path = os.path.join( + abs_replay_directory, '_test_table.json' + ) + + pathlib.Path(abs_replay_directory).mkdir(parents=True, exist_ok=True) + assert isinstance( + test_table[0].parameters, BaseModel + ), f'{test_table_file_path} parameters must be a BaseModel.' + test_table_file = types.TestTableFile( + comment='Auto-generated. Do not edit.', + test_method=test_method, + parameter_names=list(test_table[0].parameters.model_fields.keys()), + test_table=test_table, + ) + os.makedirs(os.path.dirname(test_table_file_path), exist_ok=True) + + with open(test_table_file_path, 'w') as f: + f.write( + test_table_file.model_dump_json(exclude_none=True, by_alias=True, indent=2), + ) + + # Add fixture for requested client option. + return pytest.mark.parametrize( + 'use_vertex, replays_prefix, http_options', + [ + (True, replays_directory, http_options), + (False, replays_directory, http_options), + ], + ) + + +def exception_if_mldev(client, exception_type: type[Exception]): + if client._api_client.vertexai: + return contextlib.nullcontext() + else: + return pytest.raises(exception_type) + + +def exception_if_vertex(client, exception_type: type[Exception]): + if client._api_client.vertexai: + return pytest.raises(exception_type) + else: + return contextlib.nullcontext() + + +def snake_to_camel(snake_str: str) -> str: + """Converts a snake_case string to CamelCase.""" + return re.sub(r'_([a-zA-Z])', lambda match: match.group(1).upper(), snake_str) + + +def camel_to_snake(camel_str: str) -> str: + """Converts a CamelCase string to snake_case.""" + return re.sub(r'([A-Z])', r'_\1', camel_str).lower().lstrip('_') + + +def get_value_ignore_key_case(obj, key): + """Returns the value of the key in the object, converting to camelCase or snake_case if necessary.""" + return obj.get(snake_to_camel(key), obj.get(camel_to_snake(key), None)) + + +def camel_to_snake_all_keys(data): + """Converts all keys in a dictionary or list to snake_case.""" + if isinstance(data, dict): + new_dict = {} + for key, value in data.items(): + if isinstance(key, str): + new_key = camel_to_snake(key) + else: + new_key = key + new_dict[new_key] = camel_to_snake_all_keys(value) + return new_dict + elif isinstance(data, list): + return [camel_to_snake_all_keys(item) for item in data] + else: + return data diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..66e21cef88ff3772d37f5b8d6eac646a5963c406 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/__init__.py @@ -0,0 +1,16 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/batches/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/batches/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3d87ee089ead76049cb0192040e174fb8470e9df --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/batches/__init__.py @@ -0,0 +1,14 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/batches/test_create_delete.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/batches/test_create_delete.py new file mode 100644 index 0000000000000000000000000000000000000000..447df2e6068aad8f6e36e470209a1a8fe1deb4fd --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/batches/test_create_delete.py @@ -0,0 +1,57 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +"""Tests batches.create(), batches.delete().""" + +from .... import types as genai_types +from ... import pytest_helper + + +def create_delete(client, parameters): + batch_job = client.batches.create( + model=parameters.model, + src=parameters.src, + config=parameters.config, + ) + # if pending then don't delete to avoid error + batch_job = client.batches.get(name=batch_job.name) + if batch_job.state != genai_types.JobState.JOB_STATE_PENDING: + client.batches.delete(name=batch_job.name) + + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name="test_create_delete_mldev", + parameters=genai_types._CreateBatchJobParameters( + model="gemini-2.5-flash", + src=[{ + "contents": [{ + "parts": [{"text": "Why is the sky blue?"}], + "role": "user", + }] + }], + ), + exception_if_vertex="not supported in Vertex AI.", + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method="create_delete", + test_table=test_table, +) + +pytest_plugins = ("pytest_asyncio",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/batches/test_create_get_cancel.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/batches/test_create_get_cancel.py new file mode 100644 index 0000000000000000000000000000000000000000..c990828606950d099b70816bdf11e1543e5a4bf5 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/batches/test_create_get_cancel.py @@ -0,0 +1,56 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests batches.create(), batches.get(), batches.cancel().""" + +from .... import types as genai_types +from ... import pytest_helper + + +def create_get_cancel(client, parameters): + batch_job = client.batches.create( + model=parameters.model, + src=parameters.src, + config=parameters.config, + ) + batch_job = client.batches.get(name=batch_job.name) + client.batches.cancel(name=batch_job.name) + + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name="test_create_get_cancel_mldev", + parameters=genai_types._CreateBatchJobParameters( + model="gemini-2.5-flash", + src=[{ + "contents": [{ + "parts": [{"text": "Why is the sky blue?"}], + "role": "user", + }] + }], + ), + exception_if_vertex="not supported in Vertex AI.", + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method="create_get_cancel", + test_table=test_table, +) + +pytest_plugins = ("pytest_asyncio",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/batches/test_list.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/batches/test_list.py new file mode 100644 index 0000000000000000000000000000000000000000..fb5141ab408a50cf3e1fafc44fe9f92548bb9305 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/batches/test_list.py @@ -0,0 +1,40 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +"""Tests for batches.list().""" + +from .... import types as genai_types +from ... import pytest_helper + + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_list_batch_jobs', + parameters=genai_types._ListBatchJobsParameters( + config=genai_types.ListBatchJobsConfig( + page_size=2, + ), + ), + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='batches.list', + test_table=test_table, +) + +pytest_plugins = ('pytest_asyncio',) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/caches/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/caches/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3d87ee089ead76049cb0192040e174fb8470e9df --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/caches/__init__.py @@ -0,0 +1,14 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/caches/test_create_get_delete.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/caches/test_create_get_delete.py new file mode 100644 index 0000000000000000000000000000000000000000..8325d0b46b93ff026a23e99041dc01ba49d2ce06 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/caches/test_create_get_delete.py @@ -0,0 +1,67 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +"""Tests for caches.create(), caches.get(), and caches.delete().""" + +from .... import types as genai_types +from ... import pytest_helper + + +def create_get_delete(client, parameters): + if client.vertexai: + cache = client.caches.create( + model=parameters.model, + config=parameters.config, + ) + else: + # For MLDev, we must create the file before creating the cache. + file = client.files.upload(file="tests/data/a-man-and-a-dog.png") + config = genai_types.CreateCachedContentConfig( + contents=[ + genai_types.Part.from_uri( + file_uri=file.uri, + mime_type=file.mime_type, + ) + ] + * 5 + ) + cache = client.caches.create(model=parameters.model, config=config) + got_cache = client.caches.get(name=cache.name) + client.caches.delete(name=got_cache.name) + + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name="test_create_get_delete", + parameters=genai_types._CreateCachedContentParameters( + model="gemini-2.5-flash", + config=genai_types.CreateCachedContentConfig( + contents=[genai_types.Part.from_uri( + file_uri="gs://cloud-samples-data/generative-ai/image/a-man-and-a-dog.png", + mime_type="image/png", + )] * 5 + ), + ), + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method="create_get_delete", + test_table=test_table, +) + +pytest_plugins = ("pytest_asyncio",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/caches/test_create_update_get.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/caches/test_create_update_get.py new file mode 100644 index 0000000000000000000000000000000000000000..e40777b4a9e123c9592917bf76d51109af653ff0 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/caches/test_create_update_get.py @@ -0,0 +1,71 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +"""Tests for caches.create(), caches.update(), and caches.get().""" + +from .... import types as genai_types +from ... import pytest_helper + + +def create_update_get(client, parameters): + if client.vertexai: + cache = client.caches.create( + model=parameters.model, + config=parameters.config, + ) + else: + # For MLDev, we must create the file before creating the cache. + file = client.files.upload(file="tests/data/a-man-and-a-dog.png") + config = genai_types.CreateCachedContentConfig( + contents=[ + genai_types.Part.from_uri( + file_uri=file.uri, + mime_type=file.mime_type, + ) + ] + * 5 + ) + cache = client.caches.create(model=parameters.model, config=config) + + updated_cache = client.caches.update( + name=cache.name, + config=genai_types.UpdateCachedContentConfig(ttl="7200s"), + ) + _ = client.caches.get(name=updated_cache.name) + + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name="test_create_update_get", + parameters=genai_types._CreateCachedContentParameters( + model="gemini-2.5-flash", + config=genai_types.CreateCachedContentConfig( + contents=[genai_types.Part.from_uri( + file_uri="gs://cloud-samples-data/generative-ai/image/a-man-and-a-dog.png", + mime_type="image/png", + )] * 5 + ), + ), + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method="create_update_get", + test_table=test_table, +) + +pytest_plugins = ("pytest_asyncio",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/caches/test_list.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/caches/test_list.py new file mode 100644 index 0000000000000000000000000000000000000000..aea1c6515f9eb0c72b3f570f66a00e4213dead29 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/caches/test_list.py @@ -0,0 +1,40 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +"""Tests for caches.list().""" + +from .... import types as genai_types +from ... import pytest_helper + + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_list_cached_contents', + parameters=genai_types._ListCachedContentsParameters( + config=genai_types.ListCachedContentsConfig( + page_size=2, + ), + ), + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='caches.list', + test_table=test_table, +) + +pytest_plugins = ('pytest_asyncio',) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/chats/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/chats/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3d87ee089ead76049cb0192040e174fb8470e9df --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/chats/__init__.py @@ -0,0 +1,14 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/chats/test_send_message.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/chats/test_send_message.py new file mode 100644 index 0000000000000000000000000000000000000000..58be63d04bf7f33c09204cfae868162a07e60e4f --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/chats/test_send_message.py @@ -0,0 +1,48 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +"""Table tests for chats.send_message().""" + +from ... import pytest_helper +from pydantic import BaseModel + + +class _SendMessageParameters(BaseModel): + model: str + message: str + + +def send_message(client, parameters): + chat = client.chats.create(model=parameters.model) + chat.send_message(parameters.message) + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name="test_send_message", + parameters=_SendMessageParameters( + model="gemini-2.5-flash", + message="Hello", + ), + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method="send_message", + test_table=test_table, +) + +pytest_plugins = ("pytest_asyncio",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/chats/test_send_message_stream.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/chats/test_send_message_stream.py new file mode 100644 index 0000000000000000000000000000000000000000..98b65cdacf6144dad4a90fa99fc9ff801236f6db --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/chats/test_send_message_stream.py @@ -0,0 +1,50 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +"""Table tests for chats.send_message_stream().""" + +from ... import pytest_helper +from pydantic import BaseModel + + +class _SendMessageStreamParameters(BaseModel): + model: str + message: str + + +def send_message_stream(client, parameters): + chat = client.chats.create(model=parameters.model) + response = chat.send_message_stream(parameters.message) + for _ in response: + pass + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name="test_send_message_stream", + parameters=_SendMessageStreamParameters( + model="gemini-2.5-flash", + message="Tell a joke.", + ), + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method="send_message_stream", + test_table=test_table, +) + +pytest_plugins = ("pytest_asyncio",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/files/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/files/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3d87ee089ead76049cb0192040e174fb8470e9df --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/files/__init__.py @@ -0,0 +1,14 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/files/test_list.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/files/test_list.py new file mode 100644 index 0000000000000000000000000000000000000000..9fbcb9b979110dc890a5077b1078cab9ffba0d5a --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/files/test_list.py @@ -0,0 +1,41 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +"""Tests for files.list().""" + +from .... import types as genai_types +from ... import pytest_helper + + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_list_files', + parameters=genai_types._ListFilesParameters( + config=genai_types.ListFilesConfig( + page_size=2, + ), + ), + exception_if_vertex='only supported in the Gemini Developer client', + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='files.list', + test_table=test_table, +) + +pytest_plugins = ('pytest_asyncio',) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/files/test_upload_get_delete.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/files/test_upload_get_delete.py new file mode 100644 index 0000000000000000000000000000000000000000..0f3c6a007d36eb0b29ed73eed3860d6e30b1ed43 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/files/test_upload_get_delete.py @@ -0,0 +1,54 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +"""Tests for files.upload(), files.get(), and files.delete().""" + +from pydantic import BaseModel +from ... import pytest_helper + + +class _UploadGetDeleteParameters(BaseModel): + file_path: str + + +def upload_get_delete(client, parameters): + file = None + try: + file = client.files.upload(file=parameters.file_path) + assert file.name + got_file = client.files.get(name=file.name) + assert got_file.name == file.name + finally: + if file and file.name: + client.files.delete(name=file.name) + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name="test_upload_get_delete_image", + parameters=_UploadGetDeleteParameters( + file_path="tests/data/google.png", + ), + exception_if_vertex='only supported in the Gemini Developer client', + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method="upload_get_delete", + test_table=test_table, +) + +pytest_plugins = ("pytest_asyncio",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/models/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3d87ee089ead76049cb0192040e174fb8470e9df --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/models/__init__.py @@ -0,0 +1,14 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/models/test_compute_tokens.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/models/test_compute_tokens.py new file mode 100644 index 0000000000000000000000000000000000000000..9c5cc3f46f62c0cdd2816d7d8761064ac183aa35 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/models/test_compute_tokens.py @@ -0,0 +1,41 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for models.compute_tokens().""" + +from .... import types as genai_types +from ... import pytest_helper + + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_compute_tokens', + parameters=genai_types._ComputeTokensParameters( + model='gemini-2.5-flash', + contents='The quick brown fox jumps over the lazy dog.', + ), + exception_if_mldev='only supported in the Vertex AI', + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='models.compute_tokens', + test_table=test_table, +) + +pytest_plugins = ('pytest_asyncio',) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/models/test_count_tokens.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/models/test_count_tokens.py new file mode 100644 index 0000000000000000000000000000000000000000..82732fa3ff5e975acbb791487264b1d3ac851783 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/models/test_count_tokens.py @@ -0,0 +1,40 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for models.count_tokens().""" + +from .... import types as genai_types +from ... import pytest_helper + + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_count_tokens', + parameters=genai_types._CountTokensParameters( + model='gemini-2.5-flash', + contents='The quick brown fox jumps over the lazy dog.', + ), + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='models.count_tokens', + test_table=test_table, +) + +pytest_plugins = ('pytest_asyncio',) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/models/test_edit_image.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/models/test_edit_image.py new file mode 100644 index 0000000000000000000000000000000000000000..1c2ba68af263dd6ea54796bab39bc848394837c2 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/models/test_edit_image.py @@ -0,0 +1,67 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for edit_image.""" + +import os + +from .... import types +from ... import pytest_helper + +CAPABILITY_MODEL_NAME = 'imagen-3.0-capability-001' + +IMAGE_FILE_PATH = os.path.abspath( + os.path.join(os.path.dirname(__file__), '../../data/google.png') +) + +MASK_FILE_PATH = os.path.abspath( + os.path.join(os.path.dirname(__file__), '../../data/checkerboard.png') +) + +raw_ref_image = types.RawReferenceImage( + reference_id=1, + reference_image=types.Image.from_file(location=IMAGE_FILE_PATH), +) + +mask_ref_image = types.MaskReferenceImage( + reference_id=2, + config=types.MaskReferenceConfig( + mask_mode='MASK_MODE_BACKGROUND', + mask_dilation=0.06, + ), +) + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_edit_mask_inpaint_insert', + exception_if_mldev='only supported in the Vertex AI client', + parameters=types._EditImageParameters( + model=CAPABILITY_MODEL_NAME, + prompt='Sunlight and clear weather', + reference_images=[raw_ref_image, mask_ref_image], + config=types.EditImageConfig( + edit_mode=types.EditMode.EDIT_MODE_INPAINT_INSERTION, + ), + ), + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='models.edit_image', + test_table=test_table, +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/models/test_embed.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/models/test_embed.py new file mode 100644 index 0000000000000000000000000000000000000000..910cb65f7012fffd9e7a55ffd0d5825e3c99cd6e --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/models/test_embed.py @@ -0,0 +1,53 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for models.embed().""" + +from .... import types as genai_types +from ... import pytest_helper + + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_embed', + parameters=genai_types.EmbedContentParameters( + model='gemini-embedding-001', + contents='Hello world!', + config={ + 'output_dimensionality': 10, + }, + ), + ), + pytest_helper.TestTableItem( + name='test_embed_gemini_embedding_2', + parameters=genai_types.EmbedContentParameters( + model='gemini-embedding-2-preview', + contents='Hello world!', + config={ + 'output_dimensionality': 10, + }, + ), + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='models.embed_content', + test_table=test_table, +) + +pytest_plugins = ('pytest_asyncio',) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/models/test_generate_content.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/models/test_generate_content.py new file mode 100644 index 0000000000000000000000000000000000000000..9a7f746355fcd264ae193ad000618ad8d3ad245f --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/models/test_generate_content.py @@ -0,0 +1,57 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +"""Tests for models.generate_content().""" + +from .... import types as genai_types +from ... import pytest_helper + + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_generate_content', + parameters=genai_types._GenerateContentParameters( + model='gemini-2.5-flash', + contents='The quick brown fox jumps over the lazy dog.', + ), + ), + pytest_helper.TestTableItem( + name='test_generate_content_with_config_schema', + parameters=genai_types._GenerateContentParameters( + model='gemini-2.5-flash', + contents='Return a summary of the passage.', + config={'response_mime_type': 'application/json', 'response_schema': {'type': 'OBJECT', 'properties': {'summary': {'type': 'STRING'}}}}, + ), + ignore_keys=['parsed'], + ), + pytest_helper.TestTableItem( + name='test_generate_content_with_config_json_schema', + parameters=genai_types._GenerateContentParameters( + model='gemini-2.5-flash', + contents='Return a JSON summary.', + config={'response_mime_type': 'application/json', 'response_json_schema': {'type': 'object', 'properties': {'summary': {'type': 'string'}}}}, + ), + ignore_keys=['parsed'], + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='models.generate_content', + test_table=test_table, +) + +pytest_plugins = ('pytest_asyncio',) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/models/test_generate_content_stream.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/models/test_generate_content_stream.py new file mode 100644 index 0000000000000000000000000000000000000000..c79cacfc273fe4b61757dbb257670ff62703e7f2 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/models/test_generate_content_stream.py @@ -0,0 +1,54 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +"""Tests for models.generate_content_stream().""" + +from .... import types as genai_types +from ... import pytest_helper +from pydantic import BaseModel + + +class _GenerateContentStreamParameters(BaseModel): + model: str + contents: str + + +def generate_content_stream(client, parameters): + response = client.models.generate_content_stream( + model=parameters.model, + contents=parameters.contents, + ) + for _ in response: + pass + + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_generate_content_stream', + parameters=_GenerateContentStreamParameters( + model='gemini-2.5-flash', + contents='The quick brown fox jumps over the lazy dog.', + ), + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='generate_content_stream', + test_table=test_table, +) + +pytest_plugins = ('pytest_asyncio',) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/models/test_generate_images.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/models/test_generate_images.py new file mode 100644 index 0000000000000000000000000000000000000000..cea305b9c2eccfc4a60a07929219cdcdd222ec4c --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/models/test_generate_images.py @@ -0,0 +1,40 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# +"""Tests for generate_images.""" + +from .... import types +from ... import pytest_helper + +IMAGEN_MODEL_LATEST = 'imagen-4.0-generate-001' + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_simple_prompt', + parameters=types._GenerateImagesParameters( + model=IMAGEN_MODEL_LATEST, + prompt='Red skateboard', + config=types.GenerateImagesConfig( + number_of_images=1, + output_mime_type='image/jpeg', + ), + ), + ), +] +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='models.generate_images', + test_table=test_table, +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/models/test_generate_videos.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/models/test_generate_videos.py new file mode 100644 index 0000000000000000000000000000000000000000..4de70cae1a3e408225c432c701271f6892876653 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/models/test_generate_videos.py @@ -0,0 +1,38 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# +"""Tests for generate_videos.""" + +import os +from .... import types +from ... import pytest_helper + +VEO_MODEL_LATEST = "veo-2.0-generate-001" + + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name="test_simple_prompt", + parameters=types._GenerateVideosParameters( + model=VEO_MODEL_LATEST, + prompt="Man with a dog", + ), + ), +] +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method="models.generate_videos", + test_table=test_table, +) \ No newline at end of file diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/models/test_list.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/models/test_list.py new file mode 100644 index 0000000000000000000000000000000000000000..5c96240a9d88f42489ee1c860effe6a64521c3f0 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/models/test_list.py @@ -0,0 +1,37 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for models.list.""" + + +from .... import types +from ... import pytest_helper + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_list', + parameters=types._ListModelsParameters( + config=types.ListModelsConfig(page_size=1) + ), + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='models.list', + test_table=test_table, +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/models/test_recontext_image.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/models/test_recontext_image.py new file mode 100644 index 0000000000000000000000000000000000000000..aee8865a627c20a5a471b9e0f90463a22c6c6950 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/models/test_recontext_image.py @@ -0,0 +1,56 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for recontext_image.""" + +from .... import types +from ... import pytest_helper + +VIRTUAL_TRY_ON_IMAGE_MODEL_LATEST = 'virtual-try-on-001' + +PERSON_IMAGE = types.Image( + gcs_uri='gs://genai-sdk-tests/inputs/images/man.jpg', +) + +PANTS = types.Image( + gcs_uri='gs://genai-sdk-tests/inputs/images/pants.jpg', +) + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_virtual_try_on', + exception_if_mldev='only supported in the Vertex AI client', + parameters=types._RecontextImageParameters( + model=VIRTUAL_TRY_ON_IMAGE_MODEL_LATEST, + source=types.RecontextImageSource( + person_image=PERSON_IMAGE, + product_images=[ + types.ProductImage(product_image=PANTS) + ], + ), + config=types.RecontextImageConfig( + number_of_images=1, + output_mime_type='image/jpeg', + ), + ), + ), +] +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='models.recontext_image', + test_table=test_table, +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/models/test_segment_image.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/models/test_segment_image.py new file mode 100644 index 0000000000000000000000000000000000000000..95d67a4c1df387a13b5e00589f12573881dadb3f --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/models/test_segment_image.py @@ -0,0 +1,52 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for segment_image.""" + +import os + +from .... import types +from ... import pytest_helper + +SEGMENT_IMAGE_MODEL_LATEST = 'image-segmentation-001' + +SOURCE_IMAGE_FILE_PATH1 = os.path.abspath( + os.path.join(os.path.dirname(__file__), '../../data/google.png') +) + +SOURCE_IMAGE1 = types.Image.from_file(location=SOURCE_IMAGE_FILE_PATH1) + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_segment_background', + exception_if_mldev='only supported in the Vertex AI client', + parameters=types._SegmentImageParameters( + model=SEGMENT_IMAGE_MODEL_LATEST, + source=types.SegmentImageSource( + image=SOURCE_IMAGE1, + ), + config=types.SegmentImageConfig( + mode=types.SegmentMode.BACKGROUND, + ), + ), + ), +] +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='models.segment_image', + test_table=test_table, +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/models/test_upscale_image.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/models/test_upscale_image.py new file mode 100644 index 0000000000000000000000000000000000000000..9922e1af564475b7a3c4921788e5da3d48469162 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/models/test_upscale_image.py @@ -0,0 +1,52 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +"""Tests for upscale_image.""" + +import os + +from .... import types +from ... import pytest_helper + +IMAGEN_MODEL_LATEST = 'imagen-4.0-upscale-preview' + +IMAGE_FILE_PATH = os.path.abspath( + os.path.join(os.path.dirname(__file__), '../../data/bridge1.png') +) + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_upscale', + exception_if_mldev='only supported in the Vertex AI client', + parameters=types.UpscaleImageParameters( + model=IMAGEN_MODEL_LATEST, + image=types.Image.from_file(location=IMAGE_FILE_PATH), + upscale_factor='x2', + config=types.UpscaleImageConfig( + include_rai_reason=True, + output_mime_type='image/jpeg', + output_compression_quality=80, + enhance_input_image=True, + image_preservation_factor=0.6, + ), + ), + ), +] +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='models.upscale_image', + test_table=test_table, +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/tunings/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/tunings/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..66e21cef88ff3772d37f5b8d6eac646a5963c406 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/tunings/__init__.py @@ -0,0 +1,16 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/tunings/test_create.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/tunings/test_create.py new file mode 100644 index 0000000000000000000000000000000000000000..15ff32c2c5971fdc6f6fffef9f618333d8dac272 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/tunings/test_create.py @@ -0,0 +1,46 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for tunings.tune().""" + +from .... import types as genai_types +from ... import pytest_helper + + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_tune', + parameters=genai_types.CreateTuningJobParameters( + base_model='gemini-2.5-flash', + training_dataset=genai_types.TuningDataset( + gcs_uri='gs://cloud-samples-data/ai-platform/generative_ai/gemini-2_0/text/sft_train_data.jsonl', + ), + config=genai_types.CreateTuningJobConfig( + epoch_count=1, + ), + ), + exception_if_mldev='not supported in Gemini API.', + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='tunings.tune', + test_table=test_table, +) + +pytest_plugins = ('pytest_asyncio',) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/tunings/test_create_get_cancel.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/tunings/test_create_get_cancel.py new file mode 100644 index 0000000000000000000000000000000000000000..7915505fe2944c28943b19bf5694927960d77265 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/tunings/test_create_get_cancel.py @@ -0,0 +1,56 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests tunings.tune(), tunings.get(), tunings.cancel().""" + +from .... import types as genai_types +from ... import pytest_helper + + +def create_get_cancel(client, parameters): + tuning_job = client.tunings.tune( + base_model=parameters.base_model, + training_dataset=parameters.training_dataset, + config=parameters.config, + ) + tuning_job = client.tunings.get(name=tuning_job.name) + client.tunings.cancel(name=tuning_job.name) + + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name="test_create_get_cancel", + parameters=genai_types.CreateTuningJobParameters( + base_model="gemini-2.5-flash", + training_dataset=genai_types.TuningDataset( + gcs_uri="gs://cloud-samples-data/ai-platform/generative_ai/gemini-2_0/text/sft_train_data.jsonl", + ), + config=genai_types.CreateTuningJobConfig( + epoch_count=1, + ), + ), + exception_if_mldev="not supported in Gemini API.", + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method="create_get_cancel", + test_table=test_table, +) + +pytest_plugins = ("pytest_asyncio",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/tunings/test_list.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/tunings/test_list.py new file mode 100644 index 0000000000000000000000000000000000000000..3ab10a27319d0a4d86eaaaed05249d7e8df70040 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/shared/tunings/test_list.py @@ -0,0 +1,39 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for tunings.list().""" + +from .... import types as genai_types +from ... import pytest_helper + + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_default', + parameters=genai_types._ListTuningJobsParameters( + config=genai_types.ListTuningJobsConfig(page_size=1) + ), + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='tunings.list', + test_table=test_table, +) + +pytest_plugins = ('pytest_asyncio',) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/tokens/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/tokens/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..66e21cef88ff3772d37f5b8d6eac646a5963c406 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/tokens/__init__.py @@ -0,0 +1,16 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/tokens/test_create.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/tokens/test_create.py new file mode 100644 index 0000000000000000000000000000000000000000..4b7abca27e3004fdc36f6bd3051cadce05809b0e --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/tokens/test_create.py @@ -0,0 +1,154 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for tokens.create().""" + +import pytest + +from ... import types +from .. import pytest_helper + + +_MODEL = 'models/gemini-live-2.5-flash-preview' + + +# All tests will be run for both Vertex and MLDev. +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_create_no_lock', + parameters=types.CreateAuthTokenParameters( + # remove v1alpha after v1beta is available. + config={'http_options': {'api_version': 'v1alpha'}}, + ), + exception_if_vertex='only supported in the Gemini Developer client', + ), + pytest_helper.TestTableItem( + name='test_create_global_lock', + parameters=types.CreateAuthTokenParameters( + # remove v1alpha after v1beta is available. + config={ + 'http_options': {'api_version': 'v1alpha'}, + 'uses': 2, + 'live_connect_constraints': { + 'model': _MODEL, + 'config': { + 'response_modalities': ['TEXT'], + 'temperature': 0.7, + }, + }, + }, + ), + exception_if_vertex='only supported in the Gemini Developer client', + ), + pytest_helper.TestTableItem( + name='test_create_lock_non_null_fields', + parameters=types.CreateAuthTokenParameters( + # remove v1alpha after v1beta is available. + config={ + 'http_options': {'api_version': 'v1alpha'}, + 'uses': 2, + 'live_connect_constraints': { + 'model': _MODEL, + 'config': { + 'response_modalities': ['TEXT'], + 'temperature': 0.7, + }, + }, + 'lock_additional_fields': [], + }, + ), + exception_if_vertex='only supported in the Gemini Developer client', + ), + pytest_helper.TestTableItem( + name='test_create_lock_unset_fields_as_default', + parameters=types.CreateAuthTokenParameters( + # remove v1alpha after v1beta is available. + config={ + 'http_options': {'api_version': 'v1alpha'}, + 'uses': 2, + 'live_connect_constraints': { + 'model': _MODEL, + 'config': { + 'response_modalities': ['TEXT'], + 'temperature': 0.7, + }, + }, + 'lock_additional_fields': ['output_audio_transcription'], + }, + ), + exception_if_vertex='only supported in the Gemini Developer client', + ), + pytest_helper.TestTableItem( + name='test_create_lock_additional_fields', + parameters=types.CreateAuthTokenParameters( + # remove v1alpha after v1beta is available. + config={ + 'http_options': {'api_version': 'v1alpha'}, + 'uses': 2, + 'live_connect_constraints': { + 'model': _MODEL, + 'config': { + 'response_modalities': ['TEXT'], + 'temperature': 0.7, + }, + }, + 'lock_additional_fields': ['top_k'], + }, + ), + exception_if_vertex='only supported in the Gemini Developer client', + ), + pytest_helper.TestTableItem( + name='test_create_lock_with_no_params', + parameters=types.CreateAuthTokenParameters( + # remove v1alpha after v1beta is available. + config={ + 'http_options': {'api_version': 'v1alpha'}, + 'lock_additional_fields': ['output_audio_transcription'], + }, + ), + exception_if_vertex='only supported in the Gemini Developer client', + ), + pytest_helper.TestTableItem( + name='test_create_lock_with_empty_params', + parameters=types.CreateAuthTokenParameters( + # remove v1alpha after v1beta is available. + config={ + 'http_options': {'api_version': 'v1alpha'}, + 'lock_additional_fields': ['output_audio_transcription'], + 'live_connect_constraints': {}, + }, + ), + exception_if_vertex='only supported in the Gemini Developer client', + ), +] + +pytestmark = [ + pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='auth_tokens.create', + test_table=test_table, + ), +] + + +@pytest.mark.asyncio +async def test_async_create_no_lock(client): + with pytest_helper.exception_if_vertex(client, ValueError): + config = types.CreateAuthTokenConfig( + http_options=types.HttpOptions(api_version='v1alpha') + ) + token = await client.aio.auth_tokens.create(config=config) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/transformers/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/transformers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d93f5cf64cad6c79ab18f0bbd76dc1a7c3b78e70 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/transformers/__init__.py @@ -0,0 +1,17 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for the Google GenAI SDK's _transformers module.""" \ No newline at end of file diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/transformers/test_blobs.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/transformers/test_blobs.py new file mode 100644 index 0000000000000000000000000000000000000000..735475d61962089552ccb29e08dd1cba260ffb13 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/transformers/test_blobs.py @@ -0,0 +1,84 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests t_bytes methods in the _transformers module.""" + +import os + +import PIL.Image +import pytest + +from ... import _transformers as t +from ... import types + + +def test_blob_dict(): + blob = t.t_blob({ + 'data': bytes([0, 0, 0, 0, 0, 0]), + 'mime_type': 'audio/pcm', + }) + assert blob.data == bytes([0, 0, 0, 0, 0, 0]) + assert blob.mime_type == 'audio/pcm' + + +def test_blob(): + blob = t.t_blob( + types.Blob(data=bytes([0, 0, 0, 0, 0, 0]), mime_type='audio/pcm') + ) + assert blob.data == bytes([0, 0, 0, 0, 0, 0]) + assert blob.mime_type == 'audio/pcm' + + +def test_image(image_jpeg): + blob = t.t_blob(image_jpeg) + assert blob.data[6:10] == b'JFIF' + assert blob.mime_type == 'image/jpeg' + + round_trip_image = blob.as_image()._pil_image + assert round_trip_image is not None + assert round_trip_image.size == image_jpeg.size + assert round_trip_image.mode == image_jpeg.mode + assert round_trip_image.format == image_jpeg.format + + +def test_not_image(): + blob = types.Blob(data=bytes([0, 0, 0, 0, 0, 0]), mime_type='audio/pcm') + assert blob.as_image() is None + + +def test_part_image(image_jpeg): + part = t.t_part(image_jpeg) + assert part.inline_data.data[6:10] == b'JFIF' + assert part.inline_data.mime_type == 'image/jpeg' + + round_trip_image = part.as_image()._pil_image + assert round_trip_image is not None + assert round_trip_image.size == image_jpeg.size + assert round_trip_image.mode == image_jpeg.mode + assert round_trip_image.format == image_jpeg.format + + +def test_part_not_image(): + part = t.t_part('hello world') + assert part.as_image() is None + + +def test_pil_to_blob_with_memory_pil_image(): + img = PIL.Image.new('RGB', (1, 1), color='red') + blob = t.pil_to_blob(img) + assert blob.mime_type == 'image/png' + assert blob.data and len(blob.data) == 69 + assert blob.data[0:4] == b'\x89PNG' diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/transformers/test_bytes.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/transformers/test_bytes.py new file mode 100644 index 0000000000000000000000000000000000000000..369452b579588f043006fb28e4eab25f6ead7157 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/transformers/test_bytes.py @@ -0,0 +1,15 @@ +"""Tests t_bytes methods in the _transformers module.""" + +import base64 + +from ... import _base_transformers as t + +_RAW_BYTES = ( + b'\xfb\xf6\x9bq\xd7\x9f\x82\x18\xa3\x92Y\xa7\xa2\x9a\xab\xb2\xdb\xaf\xc3\x1c\xb3\x00\x10\x83\x10Q\x87' + b' \x92\x8b0\xd3\x8fA\x14\x93QU\x97a\x9d5\xdb~9\xeb\xbf=' +) + + +def test_t_bytes(): + assert t.t_bytes(_RAW_BYTES) == base64.b64encode(_RAW_BYTES).decode('ascii') + assert t.t_bytes('string') == 'string' diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/transformers/test_function_responses.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/transformers/test_function_responses.py new file mode 100644 index 0000000000000000000000000000000000000000..8fa088d6bd2d2a55308df927f2fd0cada3b3c8a1 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/transformers/test_function_responses.py @@ -0,0 +1,72 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for live.py.""" +from ... import types +from ... import _transformers as t + +def test_function_response_dict(): + input = { + 'name': 'get_current_weather', + 'response': {'temperature': 14.5, 'unit': 'C'}, + 'id': 'some-id', + } + + function_responses = t.t_function_responses(input) + + assert len(function_responses) == 1 + assert function_responses[0].name == 'get_current_weather' + assert function_responses[0].response['temperature'] == 14.5 + assert function_responses[0].response['unit'] == 'C' + + +def test_send_function_response(): + input = types.FunctionResponse( + name='get_current_weather', + response={'temperature': 14.5, 'unit': 'C'}, + id='some-id', + ) + + function_responses = t.t_function_responses(input) + + assert len(function_responses) == 1 + assert function_responses[0].name == 'get_current_weather' + assert function_responses[0].response['temperature'] == 14.5 + assert function_responses[0].response['unit'] == 'C' + + +def test_send_function_response_list(): + + input1 = { + 'name': 'get_current_weather', + 'response': {'temperature': 14.5, 'unit': 'C'}, + 'id': '1', + } + input2 = { + 'name': 'get_current_weather', + 'response': {'temperature': 99.9, 'unit': 'C'}, + 'id': '2', + } + + function_responses = t.t_function_responses([input1, input2]) + + assert len(function_responses) == 2 + assert function_responses[0].name == 'get_current_weather' + assert function_responses[0].response['temperature'] == 14.5 + assert function_responses[0].response['unit'] == 'C' + assert function_responses[1].name == 'get_current_weather' + assert function_responses[1].response['temperature'] == 99.9 + assert function_responses[1].response['unit'] == 'C' diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/transformers/test_schema.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/transformers/test_schema.py new file mode 100644 index 0000000000000000000000000000000000000000..8655a01cc0e0483d1b65205e4cf2757cc7c8e781 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/transformers/test_schema.py @@ -0,0 +1,695 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests schema processing methods in the _transformers module.""" + +import copy +from typing import Union + +import pydantic +import pytest + +from ... import _transformers +from ... import client as google_genai_client_module +from ... import types + + +class CurrencyInfo(pydantic.BaseModel): + name: str + code: str + symbol: str + + +currency_info_fields = CurrencyInfo.model_fields + + +class CountryInfo(pydantic.BaseModel): + name: str + population: int + capital: str + continent: str + gdp: int + official_language: str + total_area_sq_mi: int + + +country_info_fields = CountryInfo.model_fields + + +class CountryInfoWithCurrency(pydantic.BaseModel): + name: str + population: int + capital: str + continent: str + gdp: int + official_language: str + total_area_sq_mi: int + currency: CurrencyInfo + + +nested_country_info_fields = CountryInfoWithCurrency.model_fields + + +class CountryInfoWithNullFields(pydantic.BaseModel): + name: str + population: Union[int, None] = None + + +class CountryInfoWithDefaultValue(pydantic.BaseModel): + name: str + population: int = 0 + + +class CountryInfoWithAnyOf(pydantic.BaseModel): + name: str + restaurants_per_capita: Union[int, float] + + +@pytest.fixture +def client(use_vertex): + if use_vertex: + yield google_genai_client_module.Client( + vertexai=use_vertex, project='test-project', location='test-location' + ) + else: + yield google_genai_client_module.Client( + vertexai=use_vertex, api_key='test-api-key' + ) + + +@pytest.mark.parametrize('use_vertex', [True, False]) +def test_build_schema_for_list_of_pydantic_schema(client): + """Tests _build_schema() when list[pydantic.BaseModel] is provided to response_schema.""" + + list_schema = _transformers.t_schema(client, CountryInfo).model_dump() + + assert isinstance(list_schema, dict) + + for field_name in list_schema['properties']: + assert 'title' in list_schema['properties'][field_name] + assert 'type' in list_schema['properties'][field_name] + assert field_name in country_info_fields + field_type_str = country_info_fields[field_name].annotation.__name__ + assert ( + list_schema['properties'][field_name]['type'] + .lower() + .startswith(field_type_str.lower()) + ) + assert 'required' in list_schema + assert list_schema['required'] == list(country_info_fields.keys()) + + +@pytest.mark.parametrize('use_vertex', [True, False]) +def test_build_schema_for_list_of_nested_pydantic_schema(client): + """Tests _build_schema() when list[pydantic.BaseModel] is provided to response_schema and the pydantic.BaseModel has nested pydantic fields.""" + list_schema = _transformers.t_schema( + client, CountryInfoWithCurrency + ).model_dump() + + assert isinstance(list_schema, dict) + + for field_name in list_schema['properties']: + assert 'title' in list_schema['properties'][field_name] + assert 'type' in list_schema['properties'][field_name] + assert field_name in nested_country_info_fields + + # Tested nested schema was created + assert 'properties' in list_schema['properties']['currency'] + + for field_name in list_schema['properties']['currency']['properties']: + assert field_name in currency_info_fields + + +@pytest.mark.parametrize('use_vertex', [True, False]) +def test_t_schema_for_pydantic_schema(client): + """Tests t_schema when pydantic.BaseModel is passed to response_schema.""" + transformed_schema = _transformers.t_schema(client, CountryInfo) + assert isinstance(transformed_schema, types.Schema) + for schema_property in transformed_schema.properties: + assert schema_property in country_info_fields + assert isinstance( + transformed_schema.properties[schema_property], types.Schema + ) + + +@pytest.mark.parametrize('use_vertex', [True, False]) +def test_t_schema_for_list_of_pydantic_schema(client): + """Tests t_schema when list[pydantic.BaseModel] is passed to response_schema.""" + transformed_schema = _transformers.t_schema(client, list[CountryInfo]) + assert isinstance(transformed_schema, types.Schema) + assert isinstance(transformed_schema.items, types.Schema) + + for schema_property in transformed_schema.items.properties: + assert schema_property in country_info_fields + assert isinstance( + transformed_schema.items.properties[schema_property], types.Schema + ) + + +@pytest.mark.parametrize('use_vertex', [True, False]) +def test_t_schema_for_null_fields(client): + """Tests t_schema when null fields are present.""" + transformed_schema = _transformers.t_schema(client, CountryInfoWithNullFields) + assert isinstance(transformed_schema, types.Schema) + assert transformed_schema.properties['population'].nullable + + +#@pytest.mark.parametrize('use_vertex', [True, False]) +def test_schema_with_no_null_fields_is_unchanged(): + """Tests handle_null_fields() doesn't change anything when no null fields are present.""" + test_properties = { + 'name': {'title': 'Name', 'type': 'string'}, + 'total_area_sq_mi': { + 'anyOf': [{'type': 'integer'}, {'type': 'float'}], + 'default': 'null', + 'title': 'Total Area Sq Mi', + }, + } + + for _, schema in test_properties.items(): + schema_before = copy.deepcopy(schema) + _transformers.handle_null_fields(schema) + assert schema_before == schema + + +@pytest.mark.parametrize('use_vertex', [True, False]) +def test_schema_with_default_value(client): + + transformed_schema = _transformers.t_schema( + client._api_client, CountryInfoWithDefaultValue + ) + expected_schema = types.Schema( + properties={ + 'name': types.Schema( + type='STRING', + title='Name', + ), + 'population': types.Schema( + type='INTEGER', + default=0, + title='Population', + ), + }, + type='OBJECT', + required=['name'], + title='CountryInfoWithDefaultValue', + property_ordering=['name', 'population'], + ) + + assert transformed_schema == expected_schema + + +@pytest.mark.parametrize('use_vertex', [True, False]) +def test_schema_with_any_of(client): + transformed_schema = _transformers.t_schema(client, CountryInfoWithAnyOf) + expected_schema = types.Schema( + properties={ + 'name': types.Schema( + type='STRING', + title='Name', + ), + 'restaurants_per_capita': types.Schema( + any_of=[ + types.Schema(type='INTEGER'), + types.Schema(type='NUMBER'), + ], + title='Restaurants Per Capita', + ), + }, + type='OBJECT', + required=['name', 'restaurants_per_capita'], + title='CountryInfoWithAnyOf', + property_ordering=['name', 'restaurants_per_capita'], + ) + + assert transformed_schema == expected_schema + + +@pytest.mark.parametrize('use_vertex', [True, False]) +def test_complex_dict_schema_with_anyof_is_unchanged(client): + """When a dict schema is passed to process_schema, the only change should be camel-casing anyOf.""" + if client.vertexai: + dict_schema = { + 'type': 'OBJECT', + 'title': 'Fruit Basket', + 'description': 'A structured representation of a fruit basket', + 'required': ['fruit'], + 'properties': { + 'fruit': { + 'type': 'ARRAY', + 'description': 'An ordered list of the fruit in the basket', + 'items': { + 'description': 'A piece of fruit', + 'anyOf': [ + { + 'title': 'Apple', + 'description': 'Describes an apple', + 'type': 'OBJECT', + 'properties': { + 'type': { + 'type': 'STRING', + 'description': "Always 'apple'", + }, + 'color': { + 'type': 'STRING', + 'description': ( + "The color of the apple (e.g., 'red')" + ), + }, + }, + 'propertyOrdering': ['type', 'color'], + 'required': ['type', 'color'], + }, + { + 'title': 'Orange', + 'description': 'Describes an orange', + 'type': 'OBJECT', + 'properties': { + 'type': { + 'type': 'STRING', + 'description': "Always 'orange'", + }, + 'size': { + 'type': 'STRING', + 'description': ( + 'The size of the orange (e.g.,' + " 'medium')" + ), + }, + }, + 'propertyOrdering': ['type', 'size'], + 'required': ['type', 'size'], + }, + ], + }, + } + }, + } + + schema_before = copy.deepcopy(dict_schema) + _transformers.process_schema(dict_schema, client) + + assert schema_before == dict_schema + + +@pytest.mark.parametrize('use_vertex', [True, False]) +def test_process_schema_converts_const_to_enum(client): + """The 'const' field should be converted to a singleton 'enum'.""" + schema = { + 'type': 'STRING', + 'const': 'FOO', + } + expected_schema = { + 'type': 'STRING', + 'enum': ['FOO'], + } + + _transformers.process_schema(schema, client) + + assert schema == expected_schema + + +@pytest.mark.parametrize('use_vertex', [True, False]) +def test_process_schema_forbids_non_string_const(client): + """The 'const' field only works for strings.""" + schema = { + 'type': 'INTEGER', + 'const': 123, + } + + with pytest.raises(ValueError, match='.*Literal values must be strings.*'): + _transformers.process_schema(schema, client) + + +@pytest.mark.parametrize( + 'use_vertex,order_properties', + [(False, False), (False, True), (True, False), (True, True)], +) +def test_process_schema_order_properties_propagates_into_defs( + client, order_properties +): + """The `order_properties` setting should apply to '$defs'.""" + schema = { + '$ref': '#/$defs/Foo', + '$defs': { + 'Foo': { + 'type': 'OBJECT', + 'properties': { + 'foo': {'type': 'STRING'}, + 'bar': {'type': 'STRING'}, + }, + }, + }, + } + schema_without_property_ordering = { + 'type': 'OBJECT', + 'properties': { + 'foo': {'type': 'STRING'}, + 'bar': {'type': 'STRING'}, + }, + } + schema_with_property_ordering = { + 'type': 'OBJECT', + 'properties': { + 'foo': {'type': 'STRING'}, + 'bar': {'type': 'STRING'}, + }, + 'property_ordering': ['foo', 'bar'], + } + + _transformers.process_schema( + schema, client, order_properties=order_properties + ) + + if order_properties: + assert schema == schema_with_property_ordering + else: + assert schema == schema_without_property_ordering + + +@pytest.mark.parametrize( + 'use_vertex,order_properties', + [(False, False), (False, True), (True, False), (True, True)], +) +def test_process_schema_order_properties_propagates_into_items( + client, order_properties +): + """The `order_properties` setting should apply to 'items'.""" + schema = { + 'type': 'ARRAY', + 'items': { + 'type': 'OBJECT', + 'properties': { + 'foo': {'type': 'STRING'}, + 'bar': {'type': 'STRING'}, + }, + }, + } + schema_without_property_ordering = copy.deepcopy(schema) + schema_with_property_ordering = { + 'type': 'ARRAY', + 'items': { + 'type': 'OBJECT', + 'properties': { + 'foo': {'type': 'STRING'}, + 'bar': {'type': 'STRING'}, + }, + 'property_ordering': ['foo', 'bar'], + }, + } + + _transformers.process_schema( + schema, client, order_properties=order_properties + ) + + if order_properties: + assert schema == schema_with_property_ordering + else: + assert schema == schema_without_property_ordering + + +@pytest.mark.parametrize( + 'use_vertex,order_properties', + [(False, False), (False, True), (True, False), (True, True)], +) +def test_process_schema_order_properties_propagates_into_prefix_items( + client, order_properties +): + """The `order_properties` setting should apply to 'prefixItems'.""" + schema = { + 'type': 'ARRAY', + 'prefixItems': [ + { + 'type': 'OBJECT', + 'properties': { + 'foo': {'type': 'STRING'}, + 'bar': {'type': 'STRING'}, + }, + }, + ], + } + schema_without_property_ordering = copy.deepcopy(schema) + schema_with_property_ordering = { + 'type': 'ARRAY', + 'prefixItems': [ + { + 'type': 'OBJECT', + 'properties': { + 'foo': {'type': 'STRING'}, + 'bar': {'type': 'STRING'}, + }, + 'property_ordering': ['foo', 'bar'], + }, + ], + } + + _transformers.process_schema( + schema, client, order_properties=order_properties + ) + + if order_properties: + assert schema == schema_with_property_ordering + else: + assert schema == schema_without_property_ordering + + +@pytest.mark.parametrize( + 'use_vertex,order_properties', + [(False, False), (False, True), (True, False), (True, True)], +) +def test_process_schema_order_properties_propagates_into_properties( + client, order_properties +): + """The `order_properties` setting should apply to 'properties'.""" + schema = { + 'type': 'OBJECT', + 'properties': { + 'xyz': { + 'type': 'OBJECT', + 'properties': { + 'foo': {'type': 'STRING'}, + 'bar': {'type': 'STRING'}, + }, + }, + 'abc': {'type': 'STRING'}, + }, + } + schema_without_property_ordering = copy.deepcopy(schema) + schema_with_property_ordering = { + 'type': 'OBJECT', + 'properties': { + 'xyz': { + 'type': 'OBJECT', + 'properties': { + 'foo': {'type': 'STRING'}, + 'bar': {'type': 'STRING'}, + }, + 'property_ordering': ['foo', 'bar'], + }, + 'abc': {'type': 'STRING'}, + }, + 'property_ordering': ['xyz', 'abc'], + } + + _transformers.process_schema( + schema, client, order_properties=order_properties + ) + + if order_properties: + assert schema == schema_with_property_ordering + else: + assert schema == schema_without_property_ordering + + +@pytest.mark.parametrize( + 'use_vertex,order_properties', + [(False, False), (False, True), (True, False), (True, True)], +) +def test_process_schema_order_properties_propagates_into_additional_properties( + client, order_properties +): + """The `order_properties` setting should apply to 'additionalProperties'.""" + schema = { + 'type': 'OBJECT', + 'additionalProperties': { + 'type': 'OBJECT', + 'properties': { + 'foo': {'type': 'STRING'}, + 'bar': {'type': 'STRING'}, + }, + }, + } + schema_without_property_ordering = copy.deepcopy(schema) + schema_with_property_ordering = { + 'type': 'OBJECT', + 'additionalProperties': { + 'type': 'OBJECT', + 'properties': { + 'foo': {'type': 'STRING'}, + 'bar': {'type': 'STRING'}, + }, + 'property_ordering': ['foo', 'bar'], + }, + } + + if client.vertexai: + _transformers.process_schema( + schema, client, order_properties=order_properties + ) + + if order_properties: + assert schema == schema_with_property_ordering + else: + assert schema == schema_without_property_ordering + else: + with pytest.raises(ValueError) as e: + _transformers.process_schema( + schema, client, order_properties=order_properties + ) + assert 'additionalProperties is not supported in the Gemini API.' in str(e) + + +@pytest.mark.parametrize( + 'use_vertex,order_properties', + [(False, False), (False, True), (True, False), (True, True)], +) +def test_process_schema_order_properties_propagates_into_any_of( + client, order_properties +): + """The `order_properties` setting should apply to 'anyOf'.""" + schema = { + 'anyOf': [ + { + 'type': 'OBJECT', + 'properties': { + 'foo': {'type': 'STRING'}, + 'bar': {'type': 'STRING'}, + }, + }, + {'type': 'STRING'}, + ] + } + schema_without_property_ordering = copy.deepcopy(schema) + schema_with_property_ordering = { + 'anyOf': [ + { + 'type': 'OBJECT', + 'properties': { + 'foo': {'type': 'STRING'}, + 'bar': {'type': 'STRING'}, + }, + 'property_ordering': ['foo', 'bar'], + }, + {'type': 'STRING'}, + ] + } + + _transformers.process_schema( + schema, client, order_properties=order_properties + ) + + if order_properties: + assert schema == schema_with_property_ordering + else: + assert schema == schema_without_property_ordering + + +@pytest.mark.parametrize('use_vertex', [True, False]) +def test_process_schema_with_cycle(client): + schema = { + 'type': 'OBJECT', + 'properties': { + 'recursive': {'$ref': '#/$defs/RecursiveObject'}, + }, + '$defs': { + 'RecursiveObject': { + 'type': 'OBJECT', + 'properties': { + 'self': {'$ref': '#/$defs/RecursiveObject'}, + } + } + } + } + + _transformers.process_schema(schema, client) + + expected = { + 'type': 'OBJECT', + 'properties': { + 'recursive': { + 'type': 'OBJECT', + 'properties': { + 'self': {} + } + } + } + } + assert schema == expected + + +@pytest.mark.parametrize('use_vertex', [True, False]) +def test_t_schema_does_not_change_property_ordering_if_set(client): + """Tests t_schema doesn't overwrite the property_ordering field if already set.""" + + schema = CountryInfo.model_json_schema() + custom_property_ordering = ['code', 'symbol', 'name'] + schema['property_ordering'] = custom_property_ordering.copy() + + transformed_schema = _transformers.t_schema(client, schema) + assert transformed_schema.property_ordering == custom_property_ordering + + +@pytest.mark.parametrize('use_vertex', [True, False]) +def test_t_schema_sets_property_ordering_for_json_schema(client): + """Tests t_schema sets the property_ordering field for json schemas.""" + + schema = CountryInfo.model_json_schema() + + transformed_schema = _transformers.t_schema(client, schema) + assert transformed_schema.property_ordering == [ + 'name', + 'population', + 'capital', + 'continent', + 'gdp', + 'official_language', + 'total_area_sq_mi', + ] + + +@pytest.mark.parametrize('use_vertex', [True, False]) +def test_t_schema_sets_property_ordering_for_schema_type(client): + """Tests t_schema sets the property_ordering field for Schema types.""" + + schema = types.Schema( + properties={ + 'name': types.Schema( + type='STRING', + title='Name', + ), + 'population': types.Schema( + type='INTEGER', + default=0, + title='Population', + ), + }, + type='OBJECT', + required=['name'], + title='CountryInfoWithDefaultValue', + ) + + transformed_schema = _transformers.t_schema(client, schema) + assert transformed_schema.property_ordering == ['name', 'population'] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/transformers/test_t_batch.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/transformers/test_t_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..f355690ee6a2ead4eb282effa07cb86361abaa83 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/transformers/test_t_batch.py @@ -0,0 +1,286 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +"""Tests for t_batch.""" + +import pytest +from ... import _transformers as t +from ... import client as google_genai_client_module +from ... import types + + +@pytest.fixture +def vertex_client(): + yield google_genai_client_module.Client( + vertexai=True, project='test-project', location='test-location' + ) + + +@pytest.fixture +def mldev_client(): + yield google_genai_client_module.Client( + vertexai=False, api_key='test-api-key' + ) + + +@pytest.mark.usefixtures('vertex_client', 'mldev_client') +class TestBatchJobSource: + + # Test cases for src as str + @pytest.mark.parametrize( + 'src_str, expected_gcs_uri, expected_bigquery_uri, expected_file_name,' + ' expected_format', + [ + ( + 'gs://bucket/path/to/data.jsonl', + ['gs://bucket/path/to/data.jsonl'], + None, + None, + 'jsonl', + ), + ( + 'bq://project.dataset.table', + None, + 'bq://project.dataset.table', + None, + 'bigquery', + ), + ('files/data.csv', None, None, 'files/data.csv', None), + ], + ) + def test_batch_job_source_str( + self, + mldev_client, + src_str, + expected_gcs_uri, + expected_bigquery_uri, + expected_file_name, + expected_format, + ): + result = t.t_batch_job_source(mldev_client, src_str) + expected = types.BatchJobSource( + gcs_uri=expected_gcs_uri, + bigquery_uri=expected_bigquery_uri, + file_name=expected_file_name, + format=expected_format, + ) + assert result == expected + + def test_batch_job_source_str_unsupported(self, mldev_client): + with pytest.raises(ValueError, match='Unsupported source'): + t.t_batch_job_source(mldev_client, 'http://example.com/data') + with pytest.raises(ValueError, match='Unsupported source'): + t.t_batch_job_source(mldev_client, 'invalid-path') + + # Test cases for src as list + def test_batch_job_source_list_empty(self, mldev_client): + result = t.t_batch_job_source(mldev_client, []) + expected = types.BatchJobSource(inlined_requests=[]) + assert result == expected + + def test_batch_job_source_list_with_items(self, mldev_client): + inlined_data = [ + types.InlinedRequest( + contents=[types.Content(parts=[types.Part(text='item1')])] + ), + types.InlinedRequest( + contents=[types.Content(parts=[types.Part(text='item2')])] + ), + ] + result = t.t_batch_job_source(mldev_client, inlined_data) + expected = types.BatchJobSource(inlined_requests=inlined_data) + assert result == expected + + # Test cases for src as dict + def test_batch_job_source_dict(self, vertex_client, mldev_client): + src_dict = {'gcs_uri': ['gs://test/file.jsonl'], 'format': 'jsonl'} + result = t.t_batch_job_source(vertex_client, src_dict) + expected = types.BatchJobSource( + gcs_uri=['gs://test/file.jsonl'], format='jsonl' + ) + assert result == expected + + src_dict_inlined = { + 'inlined_requests': [{ + 'contents': [{ + 'parts': [{ + 'text': 'Hello!', + }], + 'role': 'user', + }], + }] + } + result_inlined = t.t_batch_job_source(mldev_client, src_dict_inlined) + expected_inlined = types.BatchJobSource(inlined_requests=[{ + 'contents': [{ + 'parts': [{ + 'text': 'Hello!', + }], + 'role': 'user', + }], + }]) + assert result_inlined == expected_inlined + + # Test cases for src as types.BatchJobSource (mocked MockBatchJobSource) + + def test_batch_job_source_mldev_valid_file_name(self, mldev_client): + src_obj = types.BatchJobSource(file_name='files/my_data.csv') + result = t.t_batch_job_source(mldev_client, src_obj) + assert result is src_obj + + def test_batch_job_source_mldev_invalid_both_set(self, mldev_client): + src_obj = types.BatchJobSource( + inlined_requests=[types.InlinedRequest()], + file_name='files/data.csv', + ) + with pytest.raises( + ValueError, + match='`inlined_requests`, `file_name`,', + ): + t.t_batch_job_source(mldev_client, src_obj) + + def test_batch_job_source_mldev_invalid_neither_set(self, mldev_client): + src_obj = types.BatchJobSource( + gcs_uri=['gs://temp'] + ) + with pytest.raises( + ValueError, + match='`inlined_requests`, `file_name`,', + ): + t.t_batch_job_source(mldev_client, src_obj) + + # client.vertexai = True (Vertex AI) + def test_batch_job_source_vertexai_valid_gcs(self, vertex_client): + src_obj = types.BatchJobSource(gcs_uri=['gs://vertex-bucket/data.jsonl']) + result = t.t_batch_job_source(vertex_client, src_obj) + assert result is src_obj + + def test_batch_job_source_vertexai_valid_bigquery(self, vertex_client): + src_obj = types.BatchJobSource(bigquery_uri='bq://project.dataset.table') + result = t.t_batch_job_source(vertex_client, src_obj) + assert result is src_obj + + def test_batch_job_source_vertexai_valid_both(self, vertex_client): + src_obj = types.BatchJobSource( + gcs_uri=['gs://vertex-bucket/data.jsonl'], + bigquery_uri='bq://project.dataset.table', + ) + with pytest.raises(ValueError, match='`gcs_uri` or `bigquery_uri`'): + t.t_batch_job_source(vertex_client, src_obj) + + def test_batch_job_source_vertexai_invalid_neither_set(self, vertex_client): + src_obj = types.BatchJobSource( + file_name='files/data.csv' + ) + with pytest.raises(ValueError, match='`gcs_uri` or `bigquery_uri`'): + t.t_batch_job_source(vertex_client, src_obj) + + +class TestBatchJobDestination: + + @pytest.mark.parametrize( + 'dest_str, expected_gcs_uri, expected_bigquery_uri, expected_format', + [ + ( + 'gs://bucket/path/to/output', + 'gs://bucket/path/to/output', + None, + 'jsonl', + ), + ( + 'bq://project.dataset.output_table', + None, + 'bq://project.dataset.output_table', + 'bigquery', + ), + ], + ) + def test_valid_destinations( + self, dest_str, expected_gcs_uri, expected_bigquery_uri, expected_format + ): + result = t.t_batch_job_destination(dest_str) + expected = types.BatchJobDestination( + gcs_uri=expected_gcs_uri, + bigquery_uri=expected_bigquery_uri, + format=expected_format, + ) + assert result == expected + + def test_unsupported_destination(self): + with pytest.raises(ValueError, match='Unsupported destination'): + t.t_batch_job_destination('local/path/output.jsonl') + with pytest.raises(ValueError, match='Unsupported destination'): + t.t_batch_job_destination('http://some.url') + + +class TestBatchJobName: + + def test_mldev_valid_name(self, mldev_client): + name = 'batches/my-job-123' + assert t.t_batch_job_name(mldev_client, name) == 'my-job-123' + + @pytest.mark.parametrize( + 'invalid_name', + [ + 'my-job-123', + 'batches/my-job/suffix', + 'batches/', + 'batches/my-job-123/', + ], + ) + def test_mldev_invalid_name(self, mldev_client, invalid_name): + with pytest.raises(ValueError, match='Invalid batch job name'): + t.t_batch_job_name(mldev_client, invalid_name) + + def test_vertexai_valid_full_path(self, vertex_client): + name = 'projects/123/locations/us-central1/batchPredictionJobs/my-vertex-job-456' + assert t.t_batch_job_name(vertex_client, name) == 'my-vertex-job-456' + + def test_vertexai_valid_digit_name(self, vertex_client): + name = '9876543210' + assert t.t_batch_job_name(vertex_client, name) == '9876543210' + + @pytest.mark.parametrize( + 'invalid_name', + [ + 'my-vertex-job-456', + 'projects/123/locations/us-central1/job/my-vertex-job-456', + 'projects/123/locations/us-central1/batchPredictionJobs/', + 'not-a-number-or-path', + 'batchPredictionJobs/my-job', + ], + ) + def test_vertexai_invalid_name(self, vertex_client, invalid_name): + with pytest.raises(ValueError, match='Invalid batch job name'): + t.t_batch_job_name(vertex_client, invalid_name) + + +class TestJobState: + + @pytest.mark.parametrize( + 'input_state, expected_output_state', + [ + ('BATCH_STATE_UNSPECIFIED', 'JOB_STATE_UNSPECIFIED'), + ('BATCH_STATE_PENDING', 'JOB_STATE_PENDING'), + ('BATCH_STATE_SUCCEEDED', 'JOB_STATE_SUCCEEDED'), + ('BATCH_STATE_FAILED', 'JOB_STATE_FAILED'), + ('BATCH_STATE_CANCELLED', 'JOB_STATE_CANCELLED'), + ('BATCH_STATE_EXPIRED', 'JOB_STATE_EXPIRED'), + ('BATCH_STATE_RUNNING', 'JOB_STATE_RUNNING'), + ('BATCH_STATE_FOOBAR', 'BATCH_STATE_FOOBAR'), + ], + ) + def test_job_state_mapping(self, input_state, expected_output_state): + assert t.t_job_state(input_state) == expected_output_state diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/transformers/test_t_content.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/transformers/test_t_content.py new file mode 100644 index 0000000000000000000000000000000000000000..bfa8f3bb1903eb808bf6cc4b7c564c5a19760881 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/transformers/test_t_content.py @@ -0,0 +1,160 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +"""Tests for t_content.""" + +import pytest +import pydantic + +from ... import _transformers as t +from ... import types + + +def test_none(): + with pytest.raises(ValueError): + t.t_content( None) + + +def test_content(): + assert t.t_content( + types.Content(parts=[types.Part(text='test')]) + ) == types.Content(parts=[types.Part(text='test')]) + + +def test_content_dict(): + assert t.t_content( + {'role': 'user', 'parts': [{'text': 'test'}]} + ) == types.Content(parts=[types.Part(text='test')], role='user') + + +def test_content_dict_invalid(): + with pytest.raises(pydantic.ValidationError): + t.t_content({'invalid_key': 'test'}) + + +def test_text_part_dict(): + assert t.t_content({'text': 'test'}) == types.UserContent( + parts=[types.Part(text='test')] + ) + + +def test_function_call_part_dict(): + assert t.t_content( + {'function_call': {'name': 'test_func', 'args': {'arg1': 'value1'}}} + ) == ( + types.ModelContent( + parts=[ + types.Part( + function_call=types.FunctionCall( + name='test_func', args={'arg1': 'value1'} + ) + ) + ] + ) + ) + + +def test_text_part(): + assert t.t_content(types.Part(text='test')) == types.UserContent( + parts=[types.Part(text='test')] + ) + + +def test_function_call_part(): + assert t.t_content( + types.Part( + function_call=types.FunctionCall( + name='test_func', args={'arg1': 'value1'} + ) + ), + ) == ( + types.ModelContent( + parts=[ + types.Part( + function_call=types.FunctionCall( + name='test_func', args={'arg1': 'value1'} + ) + ) + ] + ) + ) + + +def test_string(): + assert t.t_content('test') == types.UserContent( + parts=[types.Part(text='test')] + ) + + +def test_file(): + assert t.t_content( + types.File(uri='gs://test', mime_type='image/png') + ) == types.UserContent( + parts=[ + types.Part( + file_data=types.FileData( + file_uri='gs://test', mime_type='image/png' + ) + ) + ] + ) + + +def test_file_no_uri(): + with pytest.raises(ValueError): + t.t_content(types.File(mime_type='image/png')) + + +def test_file_no_mime_type(): + with pytest.raises(ValueError): + t.t_content(types.File(uri='gs://test')) + + +def test_file_dict(): + assert t.t_content({'file_uri': 'gs://test', 'mime_type': 'image/png'}) == types.UserContent( + parts=[ + types.Part( + file_data=types.FileData( + file_uri='gs://test', mime_type='image/png' + ) + ) + ] + ) + +def test_int(): + try: + t.t_content(1) + except ValueError as e: + assert 'Unsupported content part type: ' in str(e) + + +@pytest.mark.parametrize( + 'contents', + [ + types.Content(parts=[types.Part(inline_data=types.Blob(data=b'test'))]), + {'parts': [{'inline_data': {'data': b'test'}}]}, + [ + types.Content( + parts=[types.Part(inline_data=types.Blob(data=b'test'))] + ) + ], + [{'parts': [{'inline_data': {'data': b'test'}}]}], + ], +) +def test_t_contents_strict_content(contents): + result = t.t_contents_strict(contents) + assert result == [ + types.Content(parts=[types.Part(inline_data=types.Blob(data=b'test'))]) + ] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/transformers/test_t_contents.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/transformers/test_t_contents.py new file mode 100644 index 0000000000000000000000000000000000000000..26b03c0d4393f4d8f1d44a06be11967755a6cf10 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/transformers/test_t_contents.py @@ -0,0 +1,398 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +"""Tests for t_contents.""" + +import pytest +import pydantic + +from ... import _transformers as t +from ... import types + + +def test_none(): + with pytest.raises(ValueError): + t.t_contents(None) + + +def test_empty_list(): + with pytest.raises(ValueError): + t.t_contents([]) + + +def test_content(): + assert t.t_contents( + [types.Content(parts=[types.Part(text='test')])] + ) == [types.Content(parts=[types.Part(text='test')])] + + +def test_content_dict(): + assert t.t_contents( + [{'role': 'user', 'parts': [{'text': 'test'}]}] + ) == [types.Content(parts=[types.Part(text='test')], role='user')] + + +def test_empty_dict(): + assert t.t_contents({}) == [types.Content()] + + +def test_invalid_dict(): + with pytest.raises(pydantic.ValidationError): + t.t_contents({'invalid_key': 'test'}) + + +def test_text_part(): + assert t.t_contents([types.Part(text='test')]) == [ + types.UserContent(parts=[types.Part(text='test')]) + ] + + +def test_function_call_part(): + function_call = types.FunctionCall(name='test_func', args={'arg1': 'value1'}) + assert t.t_contents( + [types.Part(function_call=function_call)] + ) == [ + types.ModelContent( + parts=[ + types.Part(function_call=function_call) + ] + ) + ] + + +def test_text_part_dict(): + assert t.t_contents([{'text': 'test'}]) == [ + types.UserContent(parts=[types.Part(text='test')]) + ] + + +def test_function_call_part_dict(): + assert t.t_contents( + [{'function_call': {'name': 'test_func', 'args': {'arg1': 'value1'}}}] + ) == [ + types.ModelContent( + parts=[ + types.Part( + function_call=types.FunctionCall( + name='test_func', args={'arg1': 'value1'} + ) + ) + ] + ) + ] + + +def test_empty_string(): + assert t.t_contents('') == [ + types.UserContent(parts=[types.Part(text='')]) + ] + + +def test_string(): + assert t.t_contents('test') == [ + types.UserContent(parts=[types.Part(text='test')]) + ] + + +def test_file(): + assert t.t_contents( + types.File(uri='gs://test', mime_type='image/png') + ) == [ + types.UserContent( + parts=[ + types.Part( + file_data=types.FileData( + file_uri='gs://test', mime_type='image/png' + ) + ) + ] + ) + ] + + +def test_file_dict(): + assert t.t_contents({'file_uri': 'gs://test', 'mime_type': 'image/png'}) == [ + types.UserContent( + parts=[ + types.Part( + file_data=types.FileData( + file_uri='gs://test', mime_type='image/png' + ) + ) + ] + ) + ] + +def test_file_dict_list(): + assert t.t_contents([{'file_uri': 'gs://test', 'mime_type': 'image/png'}]) == [ + types.UserContent( + parts=[ + types.Part( + file_data=types.FileData( + file_uri='gs://test', mime_type='image/png' + ) + ) + ] + ) + ] + +def test_file_no_uri(): + with pytest.raises(ValueError): + t.t_contents(types.File(mime_type='image/png')) + + +def test_file_no_mime_type(): + with pytest.raises(ValueError): + t.t_contents(types.File(uri='gs://test')) + + +def test_string_list(): + assert t.t_contents(['test1', 'test2']) == [ + types.UserContent(parts=[ + types.Part(text='test1'), + types.Part(text='test2'), + ]) + ] + + +def test_file_list(): + assert t.t_contents( + [ + types.File(uri='gs://test1', mime_type='image/png'), + types.File(uri='gs://test2', mime_type='image/png'), + ], + ) == [ + types.UserContent( + parts=[ + types.Part( + file_data=types.FileData( + file_uri='gs://test1', mime_type='image/png' + ) + ), + types.Part( + file_data=types.FileData( + file_uri='gs://test2', mime_type='image/png' + ) + ), + ] + ) + ] + + +def test_string_file_list(): + assert t.t_contents( + ['test1', types.File(uri='gs://test2', mime_type='image/png')], + ) == [ + types.UserContent( + parts=[ + types.Part(text='test1'), + types.Part( + file_data=types.FileData( + file_uri='gs://test2', mime_type='image/png' + ) + ), + ] + ) + ] + + +def test_function_call_list(): + function_call1 = types.FunctionCall( + name='test_func1', args={'arg1': 'value1'} + ) + function_call2 = types.FunctionCall( + name='test_func2', args={'arg2': 'value2'} + ) + + assert t.t_contents( + [ + types.Part(function_call=function_call1), + types.Part(function_call=function_call2), + ], + ) == [ + types.ModelContent( + parts=[ + types.Part(function_call=function_call1), + types.Part(function_call=function_call2), + ] + ) + ] + + +def test_function_call_function_response_list(): + question1 = 'question1' + question2 = 'question2' + function_call1 = types.FunctionCall( + name='test_func1', args={'arg1': 'value1'} + ) + function_call2 = types.FunctionCall( + name='test_func2', args={'arg2': 'value2'} + ) + function_response1 = types.FunctionResponse( + name='test_func1', + response={ + 'answer': 'answer1', + }, + ) + function_response2 = types.FunctionResponse( + name='test_func2', + response={ + 'answer': 'answer2', + }, + ) + + assert t.t_contents( + [ + question1, + question2, + types.Part(function_call=function_call1), + {'function_call': function_call2}, + {'function_response': function_response1}, + types.Part(function_response=function_response2), + ], + ) == [ + types.UserContent( + parts=[ + types.Part(text=question1), + types.Part(text=question2), + ] + ), + types.ModelContent( + parts=[ + types.Part(function_call=function_call1), + types.Part(function_call=function_call2), + ] + ), + types.UserContent( + parts=[ + types.Part(function_response=function_response1), + types.Part(function_response=function_response2), + ] + ), + ] + + +def test_content_list(): + assert t.t_contents( + [ + types.Content(parts=[types.Part(text='test1')]), + types.Content(parts=[types.Part(text='test2')]), + ], + ) == [ + types.Content(parts=[types.Part(text='test1')]), + types.Content(parts=[types.Part(text='test2')]), + ] + + +def test_content_text_part_list(): + assert t.t_contents( + [ + types.Part(text='test1'), + types.Part(text='test2'), + types.Content(parts=[types.Part(text='test3')]), + types.Part(text='test4'), + ], + ) == [ + types.UserContent( + parts=[ + types.Part(text='test1'), + types.Part(text='test2'), + ] + ), + types.Content(parts=[types.Part(text='test3')]), + types.UserContent(parts=[types.Part(text='test4')]), + ] + + +def test_list_of_text_part_list(): + contents = [ + 'question1', + {'function_call': {'name': 'test_func1', 'args': {'arg1': 'value1'}}}, + types.Part( + function_response=types.FunctionResponse( + name='test_func1', + response={ + 'answer': 'answer1', + }, + ) + ), + ['context2_1', 'context2_2', types.Part(text='context2_3')], + 'question2', + types.Part( + function_call={'name': 'test_func2', 'args': {'arg2': 'value2'}} + ), + { + 'function_response': types.FunctionResponse( + name='test_func2', + response={ + 'answer': 'answer2', + }, + ) + }, + ] + + assert t.t_contents(contents) == [ + types.UserContent(parts='question1'), + types.ModelContent( + parts=[ + types.Part( + function_call=types.FunctionCall( + name='test_func1', args={'arg1': 'value1'} + ) + ) + ] + ), + types.UserContent( + parts=[ + types.Part( + function_response=types.FunctionResponse( + name='test_func1', + response={ + 'answer': 'answer1', + }, + ) + ) + ] + ), + types.UserContent( + parts=[ + types.Part(text='context2_1'), + types.Part(text='context2_2'), + types.Part(text='context2_3'), + ] + ), + types.UserContent(parts=[types.Part(text='question2')]), + types.ModelContent( + parts=[ + types.Part( + function_call=types.FunctionCall( + name='test_func2', args={'arg2': 'value2'} + ) + ) + ] + ), + types.UserContent( + parts=[ + types.Part( + function_response=types.FunctionResponse( + name='test_func2', + response={ + 'answer': 'answer2', + }, + ) + ) + ] + ), + ] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/transformers/test_t_part.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/transformers/test_t_part.py new file mode 100644 index 0000000000000000000000000000000000000000..34b7e3cf6f8b213d094ff3f3ab75418901ac03a0 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/transformers/test_t_part.py @@ -0,0 +1,85 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +"""Tests for t_part.""" + +import pytest +import pydantic + +from ... import _transformers as t +from ... import types + + +def test_none(): + with pytest.raises(ValueError): + t.t_part(None) + + +def test_empty_string(): + assert t.t_part('') == types.Part(text='') + + +def test_string(): + assert t.t_part('test') == types.Part(text='test') + + +def test_file(): + assert t.t_part( + types.File(uri='gs://test', mime_type='image/png') + ) == types.Part( + file_data=types.FileData(file_uri='gs://test', mime_type='image/png') + ) + + +def test_file_dict(): + assert t.t_part( + {'file_uri': 'gs://test', 'mime_type': 'image/png'} + ) == types.Part( + file_data=types.FileData(file_uri='gs://test', mime_type='image/png') + ) + + +def test_file_no_uri(): + with pytest.raises(ValueError): + t.t_part(types.File(mime_type='image/png')) + + +def test_file_no_mime_type(): + with pytest.raises(ValueError): + t.t_part(types.File(uri='gs://test')) + + +def test_empty_dict(): + assert t.t_part({}) == types.Part() + + +def test_dict(): + assert t.t_part({'text': 'test'}) == types.Part(text='test') + + +def test_invalid_dict(): + with pytest.raises(pydantic.ValidationError): + t.t_part({'invalid_key': 'test'}) + + +def test_part(): + assert t.t_part(types.Part(text='test')) == types.Part(text='test') + + +def test_int(): + try: + t.t_part(1) + except ValueError as e: + assert 'Unsupported content part type: ' in str(e) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/transformers/test_t_parts.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/transformers/test_t_parts.py new file mode 100644 index 0000000000000000000000000000000000000000..27f03abdbb6beb0270235b7d89771a437b2c8a63 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/transformers/test_t_parts.py @@ -0,0 +1,87 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +"""Tests for t_parts.""" + +import pytest +import pydantic + +from ... import _transformers as t +from ... import types + + +def test_none(): + with pytest.raises(ValueError): + t.t_parts(None) + + +def test_empty_list(): + with pytest.raises(ValueError): + t.t_parts([]) + + +def test_list(): + assert t.t_parts(['test1', 'test2']) == [ + types.Part(text='test1'), + types.Part(text='test2'), + ] + + +def test_empty_dict(): + assert t.t_parts({}) == [types.Part()] + + +def test_dict(): + assert t.t_parts({'text': 'test'}) == [types.Part(text='test')] + + +def test_invalid_dict(): + with pytest.raises(pydantic.ValidationError): + t.t_parts({'invalid_key': 'test'}) + + +def test_string(): + assert t.t_parts('test') == [types.Part(text='test')] + + +def test_file(): + assert t.t_parts( + types.File(uri='gs://test', mime_type='image/png') + ) == [ + types.Part( + file_data=types.FileData(file_uri='gs://test', mime_type='image/png') + ) + ] + + +def test_file_no_uri(): + with pytest.raises(ValueError): + t.t_parts(types.File(mime_type='image/png')) + + +def test_file_no_mime_type(): + with pytest.raises(ValueError): + t.t_parts(types.File(uri='gs://test')) + + +def test_part(): + assert t.t_parts(types.Part(text='test')) == [types.Part(text='test')] + + +def test_int(): + try: + t.t_parts(1) + except ValueError as e: + assert 'Unsupported content part type: ' in str(e) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/transformers/test_t_tool.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/transformers/test_t_tool.py new file mode 100644 index 0000000000000000000000000000000000000000..32d86221babc11beaac7b4943a495b750f97c48d --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/transformers/test_t_tool.py @@ -0,0 +1,157 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +"""Tests for t_tool.""" + +import typing +from typing import Any +import pytest +from ... import _transformers as t +from ... import client as google_genai_client_module +from ... import types + +_is_mcp_imported = False +if typing.TYPE_CHECKING: + from mcp import types as mcp_types + + _is_mcp_imported = True +else: + try: + from mcp import types as mcp_types + + _is_mcp_imported = True + except ImportError: + _is_mcp_imported = False + + +@pytest.fixture +def client(use_vertex): + if use_vertex: + yield google_genai_client_module.Client( + vertexai=use_vertex, project='test-project', location='test-location' + ) + else: + yield google_genai_client_module.Client( + vertexai=use_vertex, api_key='test-api-key' + ) + + +@pytest.mark.usefixtures('client') +def test_none(client): + assert t.t_tool(client, None) == None + + +@pytest.mark.usefixtures('client') +def test_function(client): + def test_func(arg1: str, arg2: int): + pass + + assert t.t_tool(client, test_func) == types.Tool( + function_declarations=[ + types.FunctionDeclaration( + name='test_func', + parameters=types.Schema( + type='OBJECT', + properties={ + 'arg1': types.Schema(type='STRING'), + 'arg2': types.Schema(type='INTEGER'), + }, + required=['arg1', 'arg2'], + ), + ) + ] + ) + + +@pytest.mark.usefixtures('client') +def test_dictionary(client): + assert t.t_tool( + client, + { + 'function_declarations': [{ + 'name': 'tool', + 'description': 'tool-description', + 'parameters': {'type': 'OBJECT', 'properties': {}}, + }] + }, + ) == types.Tool( + function_declarations=[ + types.FunctionDeclaration( + name='tool', + description='tool-description', + parameters=types.Schema( + type='OBJECT', + properties={}, + ), + ) + ] + ) + + +@pytest.mark.usefixtures('client') +def test_mcp_tool(client): + if not _is_mcp_imported: + return + + mcp_tool = mcp_types.Tool( + name='tool', + description='tool-description', + inputSchema={ + 'type': 'object', + 'properties': { + 'key1': { + 'type': 'string', + }, + 'key2': { + 'type': 'number', + }, + }, + }, + ) + assert t.t_tool(client, mcp_tool) == types.Tool( + function_declarations=[ + types.FunctionDeclaration( + name='tool', + description='tool-description', + parameters=types.Schema( + type='OBJECT', + properties={ + 'key1': types.Schema(type='STRING'), + 'key2': types.Schema(type='NUMBER'), + }, + ), + ) + ] + ) + + +@pytest.mark.usefixtures('client') +def test_tool(client): + tool = types.Tool( + function_declarations=[ + types.FunctionDeclaration( + name='tool', + description='tool-description', + parameters=types.Schema( + type='OBJECT', + properties={ + 'key1': types.Schema(type='STRING'), + 'key2': types.Schema(type='NUMBER'), + }, + ), + ) + ] + ) + assert t.t_tool(client, tool) == tool diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/transformers/test_t_tools.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/transformers/test_t_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..05d8ce263689517f4bb8e07b564243292ec2b922 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/transformers/test_t_tools.py @@ -0,0 +1,195 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +"""Tests for t_tools.""" + +import typing +from typing import Any +import pytest +from ... import _transformers as t +from ... import client as google_genai_client_module +from ... import types + +_is_mcp_imported = False +if typing.TYPE_CHECKING: + from mcp import ClientSession as McpClientSession + from mcp import types as mcp_types + + _is_mcp_imported = True +else: + try: + from mcp import ClientSession as McpClientSession + from mcp import types as mcp_types + + _is_mcp_imported = True + except ImportError: + _is_mcp_imported = False + + +@pytest.fixture +def client(use_vertex): + if use_vertex: + yield google_genai_client_module.Client( + vertexai=use_vertex, project='test-project', location='test-location' + ) + else: + yield google_genai_client_module.Client( + vertexai=use_vertex, api_key='test-api-key' + ) + + +@pytest.mark.usefixtures('client') +def test_empty(client): + assert t.t_tools(client, []) == [] + + +@pytest.mark.usefixtures('client') +def test_function(client): + def test_func(arg1: str, arg2: int): + pass + + assert t.t_tools(client, [test_func]) == [ + types.Tool( + function_declarations=[ + types.FunctionDeclaration( + name='test_func', + parameters=types.Schema( + type='OBJECT', + properties={ + 'arg1': types.Schema(type='STRING'), + 'arg2': types.Schema(type='INTEGER'), + }, + required=['arg1', 'arg2'], + ), + ) + ] + ) + ] + + +@pytest.mark.usefixtures('client') +def test_tool(client): + tool = types.Tool( + function_declarations=[ + types.FunctionDeclaration( + name='tool', + description='tool-description', + parameters=types.Schema( + type='OBJECT', + properties={ + 'key1': types.Schema(type='STRING'), + 'key2': types.Schema(type='NUMBER'), + }, + ), + ) + ] + ) + assert t.t_tools(client, [tool]) == [tool] + + +@pytest.mark.usefixtures('client') +def test_mcp_tool(client): + if not _is_mcp_imported: + return + + mcp_tool = mcp_types.Tool( + name='tool', + description='tool-description', + inputSchema={ + 'type': 'object', + 'properties': { + 'key1': { + 'type': 'string', + }, + 'key2': { + 'type': 'number', + }, + }, + }, + ) + assert t.t_tools(client, [mcp_tool]) == [ + types.Tool( + function_declarations=[ + types.FunctionDeclaration( + name='tool', + description='tool-description', + parameters=types.Schema( + type='OBJECT', + properties={ + 'key1': types.Schema(type='STRING'), + 'key2': types.Schema(type='NUMBER'), + }, + ), + ) + ] + ) + ] + + +@pytest.mark.usefixtures('client') +def test_multiple_tools(client): + if not _is_mcp_imported: + return + + mcp_tool1 = mcp_types.Tool( + name='tool1', + description='tool1-description', + inputSchema={ + 'type': 'object', + 'properties': { + 'key1': { + 'type': 'string', + }, + }, + }, + ) + mcp_tool2 = mcp_types.Tool( + name='tool2', + description='tool2-description', + inputSchema={ + 'type': 'object', + 'properties': { + 'key1': { + 'type': 'number', + }, + }, + }, + ) + assert t.t_tools(client, [mcp_tool1, mcp_tool2]) == [ + types.Tool( + function_declarations=[ + types.FunctionDeclaration( + name='tool1', + description='tool1-description', + parameters=types.Schema( + type='OBJECT', + properties={ + 'key1': types.Schema(type='STRING'), + }, + ), + ), + types.FunctionDeclaration( + name='tool2', + description='tool2-description', + parameters=types.Schema( + type='OBJECT', + properties={ + 'key1': types.Schema(type='NUMBER'), + }, + ), + ), + ] + ), + ] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/tunings/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/tunings/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..66e21cef88ff3772d37f5b8d6eac646a5963c406 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/tunings/__init__.py @@ -0,0 +1,16 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/tunings/test_cancel.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/tunings/test_cancel.py new file mode 100644 index 0000000000000000000000000000000000000000..f62c085b3783b75738a0636a14fcb79712a7ff03 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/tunings/test_cancel.py @@ -0,0 +1,39 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for tunings.cancel().""" + +from ... import types as genai_types +from .. import pytest_helper + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name="test_cancel_vertex", + parameters=genai_types._CancelTuningJobParameters( + name="projects/801452371447/locations/us-central1/tuningJobs/2470687341547618304" + ), + exception_if_mldev="Not Found", + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method="tunings.cancel", + test_table=test_table, +) + +pytest_plugins = ("pytest_asyncio",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/tunings/test_end_to_end.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/tunings/test_end_to_end.py new file mode 100644 index 0000000000000000000000000000000000000000..a8fea1bf8bae1ec1ec614b70401cd36f38bbd1ad --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/tunings/test_end_to_end.py @@ -0,0 +1,106 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for tunings.tune().""" + +import time +from ... import _replay_api_client +from ... import types as genai_types +from .. import pytest_helper + + +test_table: list[pytest_helper.TestTableItem] = [] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method="tunings.tune", + test_table=test_table, +) + +pytest_plugins = ("pytest_asyncio",) + + +def test_tune_until_success(client): + if client._api_client.vertexai: + job = client.tunings.tune( + base_model="gemini-2.5-flash-lite", + training_dataset=genai_types.TuningDataset( + gcs_uri="gs://cloud-samples-data/ai-platform/generative_ai/gemini-2_0/text/sft_train_data.jsonl", + ), + config=genai_types.CreateTuningJobConfig( + epoch_count=1, + ), + ) + else: + # Remove GenAI SDK test since it is deprecated: + # https://ai.google.dev/gemini-api/docs/model-tuning + return + + while not job.has_ended: + # Skipping the sleep for when in replay mode. + if client._api_client._mode not in ("replay", "auto"): + time.sleep(300) + job = client.tunings.get(name=job.name) + + assert job.has_ended + assert job.has_succeeded + + +def test_continuous_tuning(client): + if not client._api_client.vertexai: + return + + job = client.tunings.tune( + base_model="gemini-2.5-flash", + training_dataset=genai_types.TuningDataset( + gcs_uri="gs://cloud-samples-data/ai-platform/generative_ai/gemini-2_0/text/sft_train_data.jsonl", + ), + config=genai_types.CreateTuningJobConfig( + epoch_count=1, + ), + ) + + while not job.has_ended: + # Skipping the sleep for when in replay mode. + if client._api_client._mode not in ("replay", "auto"): + time.sleep(300) + job = client.tunings.get(name=job.name) + + assert job.has_ended + assert job.has_succeeded + + continuous_job = client.tunings.tune( + base_model=job.tuned_model.model, + training_dataset=genai_types.TuningDataset( + gcs_uri="gs://cloud-samples-data/ai-platform/generative_ai/gemini-2_0/text/sft_train_data.jsonl", + ), + config=genai_types.CreateTuningJobConfig( + tuned_model_display_name="continuous tuning job", + epoch_count=1, + ) + ) + + while not continuous_job.has_ended: + # Skipping the sleep for when in replay mode. + if client._api_client._mode not in ("replay", "auto"): + time.sleep(300) + continuous_job = client.tunings.get(name=continuous_job.name) + + assert continuous_job.has_ended + assert continuous_job.has_succeeded + + diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/tunings/test_get.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/tunings/test_get.py new file mode 100644 index 0000000000000000000000000000000000000000..3dc5a851b0476953c667af653d021b9732b4f2f6 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/tunings/test_get.py @@ -0,0 +1,67 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for tunings.get().""" + +from ... import types as genai_types +from .. import pytest_helper + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name="test_vertexai", + parameters=genai_types._GetTuningJobParameters( + name="projects/801452371447/locations/us-central1/tuningJobs/4303478340632707072" + ), + exception_if_mldev="Not Found", + ), + pytest_helper.TestTableItem( + name="test_vertexai_with_pretuned_model", + parameters=genai_types._GetTuningJobParameters( + name="projects/801452371447/locations/us-central1/tuningJobs/8520221517529743360", + ), + exception_if_mldev="Not Found", + ), + pytest_helper.TestTableItem( + name="test_mldev", + parameters=genai_types._GetTuningJobParameters( + name="tunedModels/generate-num-1896" + ), + exception_if_vertex="Not Found", + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method="tunings.get", + test_table=test_table, +) + +pytest_plugins = ("pytest_asyncio",) + + +def test_helper_properties(client): + if client._api_client.vertexai: + job = client.tunings.get( + name="projects/801452371447/locations/us-central1/tuningJobs/4303478340632707072", + ) + else: + job = client.tunings.get( + name="tunedModels/testdatasetexamples-model-j0fpgpaksvri" + ) + + assert job.has_ended + assert job.has_succeeded diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/tunings/test_list.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/tunings/test_list.py new file mode 100644 index 0000000000000000000000000000000000000000..cabc273a636e0bfb92d0776f377f7ce65886aaa5 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/tunings/test_list.py @@ -0,0 +1,75 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for tunings.list().""" + +import pytest + +from ... import types as genai_types +from .. import pytest_helper + + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name='test_default', + parameters=genai_types._ListTuningJobsParameters(), + ), + pytest_helper.TestTableItem( + name='test_with_config', + parameters=genai_types._ListTuningJobsParameters( + config=genai_types.ListTuningJobsConfig(page_size=2) + ), + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method='tunings.list', + test_table=test_table, +) + +pytest_plugins = ('pytest_asyncio',) + + +def test_pager(client): + tuning_jobs = client.tunings.list(config={'page_size': 2}) + assert 'content-type' in tuning_jobs.sdk_http_response.headers + assert tuning_jobs.name == 'tuning_jobs' + assert tuning_jobs.page_size == 2 + assert len(tuning_jobs) <= 2 + + # Iterate through all the pages. Then next_page() should raise an exception. + for _ in tuning_jobs: + pass + with pytest.raises(IndexError, match='No more pages to fetch.'): + tuning_jobs.next_page() + + +@pytest.mark.asyncio +async def test_async_pager(client): + tuning_jobs = await client.aio.tunings.list(config={'page_size': 2}) + + assert 'Content-Type' in tuning_jobs.sdk_http_response.headers + assert tuning_jobs.name == 'tuning_jobs' + assert tuning_jobs.page_size == 2 + assert len(tuning_jobs) <= 2 + + # Iterate through all the pages. Then next_page() should raise an exception. + async for _ in tuning_jobs: + pass + with pytest.raises(IndexError, match='No more pages to fetch.'): + await tuning_jobs.next_page() diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/tunings/test_tune.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/tunings/test_tune.py new file mode 100644 index 0000000000000000000000000000000000000000..bede409862b8ea1f934be22de29a62c39ecd93a9 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/tunings/test_tune.py @@ -0,0 +1,501 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +"""Tests for tunings.tune().""" + +from ... import types as genai_types +from .. import pytest_helper +import pytest + + +VERTEX_HTTP_OPTIONS = { + 'api_version': 'v1beta1', + 'base_url': 'https://us-central1-autopush-aiplatform.sandbox.googleapis.com/', +} + +evaluation_config=genai_types.EvaluationConfig( + metrics=[ + genai_types.Metric(name="bleu", prompt_template="test prompt template") + ], + output_config=genai_types.OutputConfig( + gcs_destination=genai_types.GcsDestination( + output_uri_prefix="gs://sararob_test/" + ) + ), +) + +test_table: list[pytest_helper.TestTableItem] = [ + pytest_helper.TestTableItem( + name="test_dataset_gcs_uri", + parameters=genai_types.CreateTuningJobParameters( + base_model="gemini-2.5-flash", + training_dataset=genai_types.TuningDataset( + gcs_uri="gs://cloud-samples-data/ai-platform/generative_ai/gemini-1_5/text/sft_train_data.jsonl", + ), + ), + exception_if_mldev="gcs_uri parameter is not supported in Gemini API.", + ), + pytest_helper.TestTableItem( + name="test_tune_pretuned_model", + parameters=genai_types.CreateTuningJobParameters( + base_model="projects/801452371447/locations/us-central1/models/9030969596621881344", + training_dataset=genai_types.TuningDataset( + gcs_uri="gs://cloud-samples-data/ai-platform/generative_ai/gemini-2_0/text/sft_train_data.jsonl", + ), + ), + exception_if_mldev="is not supported in Gemini API", + ), + pytest_helper.TestTableItem( + name="test_tune_pretuned_model_with_checkpoint_id", + parameters=genai_types.CreateTuningJobParameters( + base_model="projects/801452371447/locations/us-central1/models/9030969596621881344", + training_dataset=genai_types.TuningDataset( + gcs_uri="gs://cloud-samples-data/ai-platform/generative_ai/gemini-2_0/text/sft_train_data.jsonl", + ), + config=genai_types.CreateTuningJobConfig( + pre_tuned_model_checkpoint_id="3", + ), + ), + exception_if_mldev="is not supported in Gemini API", + ), + pytest_helper.TestTableItem( + name="test_tune_simple_dpo", + parameters=genai_types.CreateTuningJobParameters( + base_model="gemini-2.5-flash", + training_dataset=genai_types.TuningDataset( + gcs_uri="gs://cloud-samples-data/ai-platform/generative_ai/gemini-1_5/text/sft_train_data.jsonl", + ), + config=genai_types.CreateTuningJobConfig( + tuned_model_display_name="Model display name", + epoch_count=1, + method="PREFERENCE_TUNING", + ), + ), + exception_if_mldev="parameter is not supported in Gemini API.", + ), + pytest_helper.TestTableItem( + name="test_tune_dpo_with_beta", + parameters=genai_types.CreateTuningJobParameters( + base_model="gemini-2.5-flash", + training_dataset=genai_types.TuningDataset( + gcs_uri="gs://cloud-samples-data/ai-platform/generative_ai/gemini-1_5/text/sft_train_data.jsonl", + ), + config=genai_types.CreateTuningJobConfig( + tuned_model_display_name="Model display name", + epoch_count=1, + method=genai_types.TuningMethod.PREFERENCE_TUNING, + beta=0.5, + ), + ), + exception_if_mldev="parameter is not supported in Gemini API.", + ), + pytest_helper.TestTableItem( + name="test_non_pretuned_model_with_checkpoint_id", + parameters=genai_types.CreateTuningJobParameters( + base_model="gemini-2.5-flash", + training_dataset=genai_types.TuningDataset( + gcs_uri="gs://cloud-samples-data/ai-platform/generative_ai/gemini-1_5/text/sft_train_data.jsonl", + ), + config=genai_types.CreateTuningJobConfig( + pre_tuned_model_checkpoint_id="3", + ), + ), + exception_if_mldev="is not supported in Gemini API.", + ), + pytest_helper.TestTableItem( + name="test_dataset_gcs_uri_all_parameters", + parameters=genai_types.CreateTuningJobParameters( + base_model="gemini-2.5-flash", + training_dataset=genai_types.TuningDataset( + gcs_uri="gs://cloud-samples-data/ai-platform/generative_ai/gemini-1_5/text/sft_train_data.jsonl", + ), + config=genai_types.CreateTuningJobConfig( + tuned_model_display_name="Model display name", + epoch_count=1, + learning_rate_multiplier=1.0, + adapter_size="ADAPTER_SIZE_ONE", + validation_dataset=genai_types.TuningValidationDataset( + gcs_uri="gs://cloud-samples-data/ai-platform/generative_ai/gemini-1_5/text/sft_validation_data.jsonl", + ), + ), + ), + exception_if_mldev="gcs_uri parameter is not supported in Gemini API.", + ), + pytest_helper.TestTableItem( + name="test_dataset_vertex_dataset_resource", + parameters=genai_types.CreateTuningJobParameters( + base_model="gemini-2.5-flash", + training_dataset=genai_types.TuningDataset( + vertex_dataset_resource="projects/801452371447/locations/us-central1/datasets/5779918772206829568", + ), + ), + exception_if_mldev="vertex_dataset_resource parameter is not supported in Gemini API.", + ), + pytest_helper.TestTableItem( + name="test_dataset_dataset_resource_all_parameters", + parameters=genai_types.CreateTuningJobParameters( + base_model="gemini-2.5-flash", + training_dataset=genai_types.TuningDataset( + vertex_dataset_resource="projects/801452371447/locations/us-central1/datasets/5779918772206829568", + ), + config=genai_types.CreateTuningJobConfig( + tuned_model_display_name="Model display name", + epoch_count=1, + learning_rate_multiplier=1.0, + adapter_size="ADAPTER_SIZE_ONE", + validation_dataset=genai_types.TuningValidationDataset( + vertex_dataset_resource="projects/801452371447/locations/us-central1/datasets/1168232753779441664", + ), + labels={"testlabelkey": "testlabelvalue"}, + ), + ), + exception_if_mldev="vertex_dataset_resource parameter is not supported in Gemini API.", + ), + pytest_helper.TestTableItem( + name="test_tune_distillation", + parameters=genai_types.CreateTuningJobParameters( + base_model="meta/llama3_1@llama-3.1-8b-instruct", + training_dataset=genai_types.TuningDataset( + gcs_uri="gs://nathreya-oss-tuning-sdk-test/distillation-openai-opposites.jsonl", + ), + config=genai_types.CreateTuningJobConfig( + method="DISTILLATION", + base_teacher_model="deepseek-ai/deepseek-v3.1-maas", + epoch_count=20, + validation_dataset=genai_types.TuningValidationDataset( + gcs_uri="gs://nathreya-oss-tuning-sdk-test/distillation-val-openai-opposites.jsonl", + ), + output_uri="gs://nathreya-oss-tuning-sdk-test/ayushagra-distillation-test-folder", + http_options=VERTEX_HTTP_OPTIONS, + ), + ), + exception_if_mldev="parameter is not supported in Gemini API.", + ), + pytest_helper.TestTableItem( + name="test_tune_oss_sft", + parameters=genai_types.CreateTuningJobParameters( + base_model="meta/llama3_1@llama-3.1-8b-instruct", + training_dataset=genai_types.TuningDataset( + gcs_uri="gs://nathreya-oss-tuning-sdk-test/distillation-openai-opposites.jsonl", + ), + config=genai_types.CreateTuningJobConfig( + epoch_count=20, + validation_dataset=genai_types.TuningValidationDataset( + gcs_uri="gs://nathreya-oss-tuning-sdk-test/distillation-val-openai-opposites.jsonl", + ), + custom_base_model="gs://nathreya-oss-tuning-sdk-test/ayushagra-distillation-test-folder/postprocess/node-0/checkpoints/final", + output_uri="gs://nathreya-oss-tuning-sdk-test/ayushagra-distillation-test", + http_options=VERTEX_HTTP_OPTIONS, + ), + ), + exception_if_mldev="not supported in Gemini API", + ), + pytest_helper.TestTableItem( + name="test_tune_oss_sft_hyperparams", + parameters=genai_types.CreateTuningJobParameters( + base_model="meta/llama3_1@llama-3.1-8b-instruct", + training_dataset=genai_types.TuningDataset( + gcs_uri="gs://nathreya-oss-tuning-sdk-test/distillation-openai-opposites.jsonl", + ), + config=genai_types.CreateTuningJobConfig( + epoch_count=20, + validation_dataset=genai_types.TuningValidationDataset( + gcs_uri="gs://nathreya-oss-tuning-sdk-test/distillation-val-openai-opposites.jsonl", + ), + learning_rate=2.5e-4, + tuning_mode="TUNING_MODE_FULL", + custom_base_model="gs://nathreya-oss-tuning-sdk-test/ayushagra-distillation-test-folder/postprocess/node-0/checkpoints/final", + output_uri="gs://nathreya-oss-tuning-sdk-test/ayushagra-distillation-test", + http_options=VERTEX_HTTP_OPTIONS, + ), + ), + exception_if_mldev="not supported in Gemini API", + ), + pytest_helper.TestTableItem( + name="test_tune_oss_distillation", + parameters=genai_types.CreateTuningJobParameters( + base_model="meta/llama3_1@llama-3.1-8b-instruct", + training_dataset=genai_types.TuningDataset( + gcs_uri="gs://nathreya-oss-tuning-sdk-test/distillation-openai-opposites.jsonl", + ), + config=genai_types.CreateTuningJobConfig( + method="DISTILLATION", + base_teacher_model="deepseek-ai/deepseek-v3.1-maas", + epoch_count=20, + validation_dataset=genai_types.TuningValidationDataset( + gcs_uri="gs://nathreya-oss-tuning-sdk-test/distillation-val-openai-opposites.jsonl", + ), + custom_base_model="gs://nathreya-oss-tuning-sdk-test/ayushagra-distillation-test-folder/postprocess/node-0/checkpoints/final", + output_uri="gs://nathreya-oss-tuning-sdk-test/ayushagra-distillation-test", + http_options=VERTEX_HTTP_OPTIONS, + ), + ), + exception_if_mldev="not supported in Gemini API", + ), + pytest_helper.TestTableItem( + name="test_tune_oss_distillation_hyperparams", + parameters=genai_types.CreateTuningJobParameters( + base_model="qwen/qwen3@qwen3-4b", + training_dataset=genai_types.TuningDataset( + gcs_uri="gs://nathreya-oss-tuning-sdk-test/distillation-openai-opposites.jsonl", + ), + config=genai_types.CreateTuningJobConfig( + method="DISTILLATION", + base_teacher_model="deepseek-ai/deepseek-r1-0528-maas", + learning_rate=1e-4, + batch_size=4, + output_uri="gs://nathreya-oss-tuning-sdk-test/ayushagra-distillation-test", + tuning_mode="TUNING_MODE_FULL", + http_options=VERTEX_HTTP_OPTIONS, + ), + ), + exception_if_mldev="not supported in Gemini API", + ), + pytest_helper.TestTableItem( + name="test_tune_encryption_spec", + parameters=genai_types.CreateTuningJobParameters( + base_model="gemini-2.5-flash", + training_dataset=genai_types.TuningDataset( + gcs_uri="gs://cloud-samples-data/ai-platform/generative_ai/gemini-1_5/text/sft_train_data.jsonl", + ), + config=genai_types.CreateTuningJobConfig( + encryption_spec=genai_types.EncryptionSpec( + kms_key_name="projects/vertex-sdk-dev/locations/us-central1/keyRings/ayush-test-key/cryptoKeys/ayush-key", + ), + ), + ), + exception_if_mldev="not supported in Gemini API", + ), +] + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), + test_method="tunings.tune", + test_table=test_table, +) + +pytest_plugins = ("pytest_asyncio",) + + +@pytest.mark.skipif( + "config.getoption('--private')", + reason="Skipping in pre-public tests" +) +def test_eval_config(client): + """Tests tuning with eval config.""" + + if client._api_client.vertexai: + tuning_job = client.tunings.tune( + base_model="gemini-2.5-flash", + training_dataset=genai_types.TuningDataset(gcs_uri="gs://cloud-samples-data/ai-platform/generative_ai/gemini-2_0/text/sft_train_data.jsonl"), + config=genai_types.CreateTuningJobConfig( + tuned_model_display_name="tuning job with eval config", + epoch_count=1, + learning_rate_multiplier=1.0, + adapter_size="ADAPTER_SIZE_ONE", + validation_dataset=genai_types.TuningValidationDataset( + gcs_uri="gs://cloud-samples-data/ai-platform/generative_ai/gemini-2_0/text/sft_validation_data.jsonl" + ), + evaluation_config=evaluation_config, + ), + ) + + assert tuning_job.state == genai_types.JobState.JOB_STATE_PENDING + assert tuning_job.evaluation_config == evaluation_config + + +@pytest.mark.skipif( + "config.getoption('--private')", + reason="Skipping in pre-public tests" +) +def test_eval_config_with_metrics(client): + """Tests tuning with eval config metrics.""" + if client._api_client.vertexai: + evaluation_config=genai_types.EvaluationConfig( + metrics=[ + genai_types.Metric( + name="prompt-relevance", + prompt_template="How well does the response address the prompt?: PROMPT: {request}\n RESPONSE: {response}\n", + return_raw_output=True, + judge_model_system_instruction="You are a cat. Make all evaluations from this perspective.", + ), + genai_types.Metric(name='bleu'), + genai_types.Metric(name='rouge_1'), + ], + output_config=genai_types.OutputConfig( + gcs_destination=genai_types.GcsDestination( + output_uri_prefix="gs://sararob_test/" + ) + ), + autorater_config=genai_types.AutoraterConfig( + sampling_count=1, + autorater_model="test-model", + ), + ) + tuning_job = client.tunings.tune( + base_model="gemini-2.5-flash", + training_dataset=genai_types.TuningDataset(gcs_uri="gs://cloud-samples-data/ai-platform/generative_ai/gemini-2_0/text/sft_train_data.jsonl"), + config=genai_types.CreateTuningJobConfig( + tuned_model_display_name="tuning job with eval config", + epoch_count=1, + learning_rate_multiplier=1.0, + adapter_size="ADAPTER_SIZE_ONE", + validation_dataset=genai_types.TuningValidationDataset( + gcs_uri="gs://cloud-samples-data/ai-platform/generative_ai/gemini-2_0/text/sft_validation_data.jsonl" + ), + evaluation_config=evaluation_config, + ), + ) + assert tuning_job.state == genai_types.JobState.JOB_STATE_PENDING + + +@pytest.mark.skipif( + "config.getoption('--private')", + reason="Skipping in pre-public tests" +) +def test_eval_config_with_unified_metrics(client): + """Tests tuning with eval config metrics.""" + if client._api_client.vertexai: + evaluation_config=genai_types.EvaluationConfig( + metrics=[ + genai_types.UnifiedMetric( + pointwise_metric_spec=genai_types.PointwiseMetricSpec( + metric_prompt_template=( + "How well does the response address the prompt?: " + "PROMPT: {request}\n RESPONSE: {response}\n" + ), + system_instruction=( + "You are a cat. Make all evaluations from this perspective." + ), + custom_output_format_config=genai_types.CustomOutputFormatConfig( + return_raw_output=True + ), + ) + ), + genai_types.UnifiedMetric( + bleu_spec=genai_types.BleuSpec(use_effective_order=True) + ), + genai_types.UnifiedMetric( + rouge_spec=genai_types.RougeSpec(rouge_type="rouge1") + ), + ], + output_config=genai_types.OutputConfig( + gcs_destination=genai_types.GcsDestination( + output_uri_prefix="gs://sararob_test/" + ) + ), + autorater_config=genai_types.AutoraterConfig( + sampling_count=1, + autorater_model="test-model", + ), + inference_generation_config=genai_types.GenerationConfig( + temperature=0.5, + max_output_tokens=1024, + ), + ) + tuning_job = client.tunings.tune( + base_model="gemini-2.5-flash", + training_dataset=genai_types.TuningDataset(gcs_uri="gs://cloud-samples-data/ai-platform/generative_ai/gemini-2_0/text/sft_train_data.jsonl"), + config=genai_types.CreateTuningJobConfig( + tuned_model_display_name="tuning job with eval config", + epoch_count=1, + learning_rate_multiplier=1.0, + adapter_size="ADAPTER_SIZE_ONE", + validation_dataset=genai_types.TuningValidationDataset( + gcs_uri="gs://cloud-samples-data/ai-platform/generative_ai/gemini-2_0/text/sft_validation_data.jsonl" + ), + evaluation_config=evaluation_config, + ), + ) + assert tuning_job.state == genai_types.JobState.JOB_STATE_PENDING + + +@pytest.mark.skipif( + "config.getoption('--private')", + reason="Skipping in pre-public tests" +) +def test_eval_config_with_metrics_dict(client): + """Tests tuning with eval config metrics.""" + if client._api_client.vertexai: + evaluation_config=genai_types.EvaluationConfig( + metrics = [ + { + "name": "prompt-relevance", + "prompt_template": "How well does the response address the prompt?: PROMPT: {request}\n RESPONSE: {response}\n", + "return_raw_output": True, + "judge_model_system_instruction": "You are a cat. Make all evaluations from this perspective.", + }, + {"name": "bleu"}, + {"name": "rouge_1"}, + { + "bleu_spec": { + "use_effective_order": True + } + }, + ], + output_config=genai_types.OutputConfig( + gcs_destination=genai_types.GcsDestination( + output_uri_prefix="gs://sararob_test/" + ) + ), + autorater_config=genai_types.AutoraterConfig( + sampling_count=1, + autorater_model="test-model", + ), + ) + tuning_job = client.tunings.tune( + base_model="gemini-2.5-flash", + training_dataset=genai_types.TuningDataset(gcs_uri="gs://cloud-samples-data/ai-platform/generative_ai/gemini-2_0/text/sft_train_data.jsonl"), + config=genai_types.CreateTuningJobConfig( + tuned_model_display_name="tuning job with eval config", + epoch_count=1, + learning_rate_multiplier=1.0, + adapter_size="ADAPTER_SIZE_ONE", + validation_dataset=genai_types.TuningValidationDataset( + gcs_uri="gs://cloud-samples-data/ai-platform/generative_ai/gemini-2_0/text/sft_validation_data.jsonl" + ), + evaluation_config=evaluation_config, + ), + ) + assert tuning_job.state == genai_types.JobState.JOB_STATE_PENDING + + + +@pytest.mark.skipif( + "config.getoption('--private')", + reason="Skipping in pre-public tests" +) +@pytest.mark.asyncio +async def test_eval_config_async(client): + """Tests tuning with eval config.""" + if client._api_client.vertexai: + tuning_job = await client.aio.tunings.tune( + base_model="gemini-2.5-flash", + training_dataset=genai_types.TuningDataset(gcs_uri="gs://cloud-samples-data/ai-platform/generative_ai/gemini-2_0/text/sft_train_data.jsonl"), + config=genai_types.CreateTuningJobConfig( + tuned_model_display_name="tuning job with eval config", + epoch_count=1, + learning_rate_multiplier=1.0, + adapter_size="ADAPTER_SIZE_ONE", + validation_dataset=genai_types.TuningValidationDataset( + gcs_uri="gs://cloud-samples-data/ai-platform/generative_ai/gemini-2_0/text/sft_validation_data.jsonl" + ), + evaluation_config=evaluation_config, + ), + ) + + assert tuning_job.state == genai_types.JobState.JOB_STATE_PENDING diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/types/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/types/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..66e21cef88ff3772d37f5b8d6eac646a5963c406 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/types/__init__.py @@ -0,0 +1,16 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/types/test_bytes_internal.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/types/test_bytes_internal.py new file mode 100644 index 0000000000000000000000000000000000000000..e6efc8e890c02b6295e00cbb34f86fa9a621863f --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/types/test_bytes_internal.py @@ -0,0 +1,271 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +import base64 +import json +from unittest import mock + +import pytest + +from .. import pytest_helper + +from ... import _api_client as google_genai_api_client_module +from ... import _common as common_module +from ... import client as google_genai_client_module +from ... import types + + +# 64 chars in url safe base64. +_BASE64_URL_SAFE = ( + '-_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' +) +_RAW_BYTES = ( + b'\xfb\xf6\x9bq\xd7\x9f\x82\x18\xa3\x92Y\xa7\xa2\x9a\xab\xb2\xdb\xaf\xc3\x1c\xb3\x00\x10\x83\x10Q\x87' + b' \x92\x8b0\xd3\x8fA\x14\x93QU\x97a\x9d5\xdb~9\xeb\xbf=' +) +# 64 chars in normal base64 is invalid format for pydantic `val_json_bytes`. +_BASE64_NOT_URL_SAFE = ( + '+/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789===' +) +assert base64.b64decode(_BASE64_NOT_URL_SAFE) == _RAW_BYTES + + +@pytest.fixture +def client(use_vertex): + if use_vertex: + yield google_genai_client_module.Client( + vertexai=use_vertex, project='test-project', location='test-location' + ) + else: + yield google_genai_client_module.Client( + vertexai=use_vertex, api_key='test-api-key' + ) + +@pytest.fixture +def encode_unserializable_types_method(): + with mock.patch.object(common_module, 'encode_unserializable_types', wraps=common_module.encode_unserializable_types) as method: + yield method + + +pytestmark = [pytest.mark.parametrize('use_vertex', [True, False])] + + +@pytest.fixture +def mock_request_method(): + with mock.patch.object( + google_genai_api_client_module.BaseApiClient, 'request' + ) as request_method: + yield request_method + + +# This test checks if user pass in valid base64 string(url safe base64) +# via pydantic type, then SDK will return the raw bytes in pydantic type. +@pytest.mark.usefixtures('client', 'mock_request_method', 'encode_unserializable_types_method') +@pytest.mark.parametrize('bytes_input', [_RAW_BYTES, _BASE64_URL_SAFE]) +def test_base64_pydantic_input_success( + client, mock_request_method, encode_unserializable_types_method, bytes_input +): + mock_request_method.return_value = types.HttpResponse( + headers={'header_key': 'header_value'}, + body=json.dumps({ + 'candidates': [ + {'content': {'parts': [{'text': 'Hello World'}], 'role': 'model'}} + ] + }), + ) + + response = client.models.generate_content( + model='gemini-2.5-flash-001', + contents=types.Content( + role='user', + parts=[ + types.Part( + inline_data=types.Blob( + mime_type='image/png', + data=bytes_input, + ) + ) + ], + ), + ) + + encode_unserializable_types_method.assert_called() + assert mock_request_method.call_count == 1 + assert ( + pytest_helper.get_value_ignore_key_case( + mock_request_method.call_args[0][2]['contents'][0]['parts'][0], + 'inlineData' + )['data'] + == _BASE64_URL_SAFE + ) + assert response.candidates[0].content == types.Content( + role='model', + parts=[types.Part(text='Hello World')], + ) + + +# This test checks if user pass in valid base64 string(url safe base64) +# via dict type, then SDK will return the raw bytes in pydantic type. +@pytest.mark.usefixtures('client', 'mock_request_method', 'encode_unserializable_types_method') +@pytest.mark.parametrize('bytes_input', [_RAW_BYTES, _BASE64_URL_SAFE]) +def test_base64_dict_input_success(client, mock_request_method, encode_unserializable_types_method, bytes_input): + mock_request_method.return_value = types.HttpResponse( + headers={'header_key': 'header_value'}, + body = json.dumps({ + 'candidates': [ + {'content': {'parts': [{'text': 'Hello World'}], 'role': 'model'}} + ] + }), + ) + + response = client.models.generate_content( + model='gemini-2.5-flash-001', + contents={ + 'role': 'user', + 'parts': [ + { + 'inlineData': { + 'mimeType': 'image/png', + 'data': bytes_input, + } + } + ], + }, + ) + + encode_unserializable_types_method.assert_called() + assert mock_request_method.call_count == 1 + assert ( + pytest_helper.get_value_ignore_key_case( + mock_request_method.call_args[0][2]['contents'][0]['parts'][0], + 'inlineData' + )['data'] + == _BASE64_URL_SAFE + ) + assert response.candidates[0].content == types.Content( + role='model', + parts=[types.Part(text='Hello World')], + ) + + +# This test checks if user pass in invalid base64 string(normal base64 but not +# url safe) via pydantic type, then SDK will raise ValueError. +@pytest.mark.usefixtures('client', 'mock_request_method') +def test_base64_pydantic_input_failure(client): + with pytest.raises(ValueError, match='Data should be valid base64'): + client.models.generate_content( + model='gemini-2.5-flash-001', + contents=types.Content( + role='user', + parts=[ + types.Part( + inline_data=types.Blob( + mime_type='image/png', + data=_BASE64_NOT_URL_SAFE, + ) + ) + ], + ), + ) + + +# This test checks if user pass in invalid base64 string(normal base64 but not +# url safe) via dict type, then SDK will raise ValueError. +@pytest.mark.usefixtures('client', 'mock_request_method') +def test_base64_dict_input_failure(client): + with pytest.raises(ValueError, match='Data should be valid base64'): + client.models.generate_content( + model='gemini-2.5-flash-001', + contents={ + 'role': 'user', + 'parts': [{ + 'inlineData': { + 'mimeType': 'image/png', + 'data': _BASE64_NOT_URL_SAFE, + } + }], + }, + ) + + +# This test checks if server returns valid base64 string(url safe base64), +# then SDK will return the raw bytes in pydantic type. +@pytest.mark.usefixtures('client', 'mock_request_method',) +def test_base64_pydantic_output_success(client, mock_request_method): + mock_request_method.return_value = types.HttpResponse( + headers={'header_key': 'header_value'}, + body=json.dumps({ + 'candidates': [{ + 'content': { + 'parts': [{ + 'inlineData': { + 'data': _BASE64_URL_SAFE, + 'mimeType': 'image/png', + } + }], + 'role': 'model', + } + }] + }), + ) + + response = client.models.generate_content( + model='gemini-2.5-flash-001', + contents=types.Content( + role='user', + parts=[types.Part(text='Hello World')], + ), + ) + + assert response.candidates[0].content == types.Content( + role='model', + parts=[ + types.Part( + inline_data=types.Blob(data=_RAW_BYTES, mime_type='image/png') + ) + ], + ) + + +# This test checks if server returns invalid base64 string(normal base64 but +# not url safe), then SDK will raise ValueError. +@pytest.mark.usefixtures('client', 'mock_request_method') +def test_base64_pydantic_output_failure(client, mock_request_method): + mock_request_method.return_value = types.HttpResponse( + headers={'header_key': 'header_value'}, + body=json.dumps({ + 'candidates': [{ + 'content': { + 'parts': [{ + 'inlineData': { + 'data': _BASE64_NOT_URL_SAFE, + 'mimeType': 'image/png', + } + }], + 'role': 'model', + } + }] + }), + ) + + with pytest.raises(ValueError, match='Data should be valid base64'): + client.models.generate_content( + model='gemini-2.5-flash-001', + contents=types.Content( + role='user', + parts=[types.Part(text='Hello World')], + ), + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/types/test_bytes_type.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/types/test_bytes_type.py new file mode 100644 index 0000000000000000000000000000000000000000..1daddc0669a936affb9af3623658aa07f6690125 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/types/test_bytes_type.py @@ -0,0 +1,152 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +import base64 +from datetime import datetime +from typing import Any, Optional + +import pytest + +from ... import _common + +# 64 distinct chars in url safe base64. +_URL_SAFE_BASE64 = ( + '-_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' +) +_RAW_BYTES = ( + b'\xfb\xf6\x9bq\xd7\x9f\x82\x18\xa3\x92Y\xa7\xa2\x9a\xab\xb2\xdb\xaf\xc3\x1c\xb3\x00\x10\x83\x10Q\x87' + b' \x92\x8b0\xd3\x8fA\x14\x93QU\x97a\x9d5\xdb~9\xeb\xbf=' +) +# 64 distinct chars in normal base64. +_BASE64 = '+/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' +assert base64.b64decode(_BASE64) == _RAW_BYTES + + +class MyBytesModel(_common.BaseModel): + image_data: Optional[bytes] + + +# This test shows that if user pass in url safe base64 string to a bytes field, +# then SDK will return raw bytes in pydantic, model_dump() and __str__() +# and base64 string in to_json_dict() and model_dump(mode='json'). +def test_urlsafe_base64_input_success(): + my_data = MyBytesModel(image_data=_URL_SAFE_BASE64) + + # Check output is base64 string. + assert my_data.to_json_dict() == {'image_data': _URL_SAFE_BASE64} + assert my_data.model_dump(mode='json') == {'image_data': _URL_SAFE_BASE64} + assert isinstance(my_data.to_json_dict()['image_data'], str) + + # Check output is bytes. + assert my_data.model_dump() == {'image_data': _RAW_BYTES} + assert my_data.image_data == _RAW_BYTES + assert isinstance(my_data.image_data, bytes) + + # Check print(my_data) will output the bytes string, not the base64 string. + assert str(my_data) == 'image_data=' + str(_RAW_BYTES) + + +# This test shows that if user pass in raw bytes to a bytes field, +# then SDK will return raw bytes in pydantic, model_dump() and __str__() +# and base64 string in to_json_dict() and model_dump(mode='json'). +def test_raw_bytes_input_success(): + my_data = MyBytesModel(image_data=_RAW_BYTES) + + # Check output is base64 string. + assert my_data.to_json_dict() == {'image_data': _URL_SAFE_BASE64} + assert my_data.model_dump(mode='json') == {'image_data': _URL_SAFE_BASE64} + assert isinstance(my_data.to_json_dict()['image_data'], str) + + # Check output is bytes. + assert my_data.model_dump() == {'image_data': _RAW_BYTES} + assert my_data.image_data == _RAW_BYTES + assert isinstance(my_data.image_data, bytes) + + # Check print(my_data) will output the bytes string, not the base64 string. + assert str(my_data) == 'image_data=' + str(_RAW_BYTES) + + +# This test shows that if user pass in invalid base64 string(normal base64 but +# not url safe) to a bytes field, then SDK will raise ValueError. +def test_invalid_base64_pydantic_input_failure(): + with pytest.raises(ValueError, match='Data should be valid base64'): + MyBytesModel(image_data=_BASE64+'=') # invalid base64 + + +# This test shows that if user pass in invalid base64 string(normal base64 but +# not url safe) to a bytes field, then SDK will raise ValueError. +def test_invalid_base64_dict_input_failure(): + with pytest.raises(ValueError, match='Data should be valid base64'): + MyBytesModel.model_validate({'image_data': _BASE64+'='}) # invalid base64 + + +# This test shows that if user pass in normal base64 string( +# not url safe) to a bytes field, then Pydantic can correctly parse the normal +# base64 string to bytes. +def test_normal_base64_pydantic_input_success(): + data = MyBytesModel(image_data=_BASE64) + assert data.image_data == _RAW_BYTES + + +# This test shows that if user pass in normal base64 string via( +# not url safe) via dict input with model_validate(), then Pydantic can +# correctly parse the normal base64 string to bytes. +def test_normal_base64_dict_input_success(): + data = MyBytesModel.model_validate({'image_data': _BASE64}) + assert data.image_data == _RAW_BYTES + + +class MyAnyModel(_common.BaseModel): + data: Optional[Any] + + +# This test shows that if user pass in raw bytes to an Any type field, +# then SDK will return raw bytes in pydantic, model_dump() and __str__() +# and base64 string in to_json_dict() and model_dump(mode='json'). +def test_any_type_urlsafe_base64_input(): + my_data = MyAnyModel(data=_RAW_BYTES) + + # Check output is base64 string. + assert my_data.to_json_dict() == {'data': _URL_SAFE_BASE64} + assert my_data.model_dump(mode='json') == {'data': _URL_SAFE_BASE64} + assert isinstance(my_data.to_json_dict()['data'], str) + + # Check output is bytes. + assert my_data.model_dump() == {'data': _RAW_BYTES} + assert my_data.data == _RAW_BYTES + assert isinstance(my_data.data, bytes) + + # Check print(my_data) will output the bytes string, not the base64 string. + assert str(my_data) == 'data=' + str(_RAW_BYTES) + + +# This test shows if user pass in url safe base64 string to an Any type field, +# then SDK will always return the base64 string. +def test_any_type_urlsafe_base64_input(): + my_data = MyAnyModel(data=_URL_SAFE_BASE64) + + # Check output is base64 string. + assert my_data.to_json_dict() == {'data': _URL_SAFE_BASE64} + assert my_data.model_dump(mode='json') == {'data': _URL_SAFE_BASE64} + assert isinstance(my_data.to_json_dict()['data'], str) + + # Check output is bytes. + assert my_data.model_dump() == {'data': _URL_SAFE_BASE64} + assert my_data.data == _URL_SAFE_BASE64 + assert isinstance(my_data.data, str) + + # Check print(my_data) will output the bytes string, not the base64 string. + assert str(my_data) == "data='" + str(_URL_SAFE_BASE64) + "'" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/types/test_future.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/types/test_future.py new file mode 100644 index 0000000000000000000000000000000000000000..dc5eb597cb20305657f6b2a96dfd5eb7c968a4dc --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/types/test_future.py @@ -0,0 +1,101 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# !Please DO NOT combine the test in this file with other tests. This file is +# used to test the future annotation, which is the first line of import. +from __future__ import annotations + +import copy +import pydantic + +from ... import types + + +class ComplexType(pydantic.BaseModel): + param_x: str + param_y: int + + +class FakeClient: + + def __init__(self, vertexai=False) -> None: + self.vertexai = vertexai + + +mldev_client = FakeClient() +vertex_client = FakeClient(vertexai=True) + + +def test_future_annotation_simple_type(): + def func_under_test(param_1: str, param_2: int) -> str: + return '123' + + expected_schema_mldev = types.FunctionDeclaration( + name='func_under_test', + parameters=types.Schema( + type='OBJECT', + properties={ + 'param_1': types.Schema(type='STRING'), + 'param_2': types.Schema(type='INTEGER'), + }, + required=['param_1', 'param_2'], + ), + ) + expected_schema_vertex = copy.deepcopy(expected_schema_mldev) + expected_schema_vertex.response = types.Schema(type='STRING') + actual_schema_mldev = types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + actual_schema_vertex = types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + assert actual_schema_mldev == expected_schema_mldev + assert actual_schema_vertex == expected_schema_vertex + + +def test_future_annotation_complex_type(): + def func_under_test(param_1: ComplexType, param_2: int) -> str: + return '123' + + expected_schema_mldev = types.FunctionDeclaration( + name='func_under_test', + parameters=types.Schema( + type='OBJECT', + properties={ + 'param_1': types.Schema( + type='OBJECT', + properties={ + 'param_x': types.Schema(type='STRING'), + 'param_y': types.Schema(type='INTEGER'), + }, + required=['param_x', 'param_y'], + ), + 'param_2': types.Schema(type='INTEGER'), + }, + required=['param_1', 'param_2'], + ) + ) + expected_schema_vertex = copy.deepcopy(expected_schema_mldev) + expected_schema_vertex.response = types.Schema(type='STRING') + + actual_schema_mldev = types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + actual_schema_vertex = types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + + assert actual_schema_mldev == expected_schema_mldev + assert actual_schema_vertex == expected_schema_vertex diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/types/test_optional_types.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/types/test_optional_types.py new file mode 100644 index 0000000000000000000000000000000000000000..58f81f9fd6223a65515a7feacbd7f7e3f24fe145 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/types/test_optional_types.py @@ -0,0 +1,36 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +from unittest.mock import patch + + +@patch.dict('sys.modules', {'PIL': None, 'PIL.Image': None}) +def test_without_pil_installed_mocked(): + from ... import types + + type_names_in_union = [ + arg.__name__ if hasattr(arg, '__name__') else str(arg) + for arg in types.PartUnion.__args__] + assert 'Image' not in type_names_in_union + +def test_without_pil_installed_mocked(): + from ... import types + + type_names_in_union = [ + arg.__name__ if hasattr(arg, '__name__') else str(arg) + for arg in types.PartUnion.__args__] + + assert 'Image' in type_names_in_union \ No newline at end of file diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/types/test_part_type.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/types/test_part_type.py new file mode 100644 index 0000000000000000000000000000000000000000..a856b15deeb1fd7db43ccbd31c70844a8ccee2dc --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/types/test_part_type.py @@ -0,0 +1,618 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +import pytest +from ... import types + + +@pytest.fixture +def generate_content_response(): + return types.GenerateContentResponse() + + +def test_candidate_empty_text(): + response = types.GenerateContentResponse() + assert response.text is None + + +def test_first_candidate_empty_content_text(): + response = types.GenerateContentResponse(candidates=[]) + + # MUST assert None not implicit boolean False + assert response.text is None + + +def test_first_candidate_empty_parts_text(): + response = types.GenerateContentResponse(candidates=[types.Candidate()]) + + # MUST assert None not implicit boolean False + assert response.text is None + + +def test_content_empty_parts_text(): + response = types.GenerateContentResponse( + candidates=[types.Candidate(content=types.Content())] + ) + + # MUST assert None not implicit boolean False + assert response.text is None + + +def test_two_candidates_text(caplog, generate_content_response): + from ... import types as types_module + types_module._response_text_warning_logged = False + + generate_content_response.candidates = [ + types.Candidate( + content=types.Content( + parts=[ + types.Part(text='Hello1'), + types.Part(text='World1'), + ] + ) + ), + types.Candidate( + content=types.Content( + parts=[ + types.Part(text='Hello2'), + types.Part(text='World2'), + ] + ) + ), + ] + + assert generate_content_response.text == 'Hello1World1' + assert any( + record.levelname == 'WARNING' + and 'there are 2 candidates' in record.message + for record in caplog.records + ) + generate_content_response.candidates = None + + +def test_thought_signature_no_warning(caplog, generate_content_response): + generate_content_response.candidates = [ + types.Candidate( + content=types.Content( + parts=[ + types.Part(text='Hello'), + types.Part(thought_signature=b'thought'), + ] + ) + ), + ] + + assert generate_content_response.text == 'Hello' + assert not any( + record.levelname == 'WARNING' + and 'there are non-text parts in the response' in record.message + for record in caplog.records + ) + generate_content_response.candidates = None + + +def test_thought_signature_no_warning_in_text( + caplog, generate_content_response +): + generate_content_response.candidates = [ + types.Candidate( + content=types.Content( + parts=[ + types.Part(text='Hello', thought_signature=b'thought'), + ] + ) + ), + ] + + assert generate_content_response.text == 'Hello' + assert not any( + record.levelname == 'WARNING' + and 'there are non-text parts in the response' in record.message + for record in caplog.records + ) + generate_content_response.candidates = None + + +def test_1_candidate_text(): + response = types.GenerateContentResponse( + candidates=[ + types.Candidate( + content=types.Content( + parts=[ + types.Part(text='Hello1'), + types.Part(text='World1'), + ] + ) + ) + ] + ) + + assert response.text == 'Hello1World1' + + +def test_all_empty_text_in_parts(): + response = types.GenerateContentResponse( + candidates=[ + types.Candidate( + content=types.Content( + parts=[ + types.Part(text=''), + types.Part(text=''), + ] + ) + ), + types.Candidate( + content=types.Content( + parts=[ + types.Part(text='Hello2'), + types.Part(text='World2'), + ] + ) + ), + ] + ) + + # MUST assert empty string, not implicit boolean False + assert response.text == '' + + +def test_one_empty_text_in_parts(): + response = types.GenerateContentResponse( + candidates=[ + types.Candidate( + content=types.Content( + parts=[ + types.Part(text=''), + types.Part(text='World1'), + ] + ) + ), + types.Candidate( + content=types.Content( + parts=[ + types.Part(text='Hello2'), + types.Part(text='World2'), + ] + ) + ), + ] + ) + + assert response.text == 'World1' + + +def test_all_none_text(): + response = types.GenerateContentResponse( + candidates=[ + types.Candidate( + content=types.Content( + parts=[ + types.Part(), + types.Part(), + ] + ) + ), + types.Candidate( + content=types.Content( + parts=[ + types.Part(text='Hello2'), + types.Part(text='World2'), + ] + ) + ), + ] + ) + + # MUST assert None not implicit boolean False + assert response.text is None + + +def test_none_empty_text(): + response = types.GenerateContentResponse( + candidates=[ + types.Candidate( + content=types.Content( + parts=[ + types.Part(), + types.Part(text=''), + ] + ) + ), + types.Candidate( + content=types.Content( + parts=[ + types.Part(text='Hello2'), + types.Part(text='World2'), + ] + ) + ), + ] + ) + + # MUST assert empty string, not implicit boolean False + assert response.text == '' + + +def test_non_text_part_text(caplog, generate_content_response): + from ... import types as types_module + types_module._response_text_non_text_warning_logged = False + + generate_content_response.candidates = [ + types.Candidate( + content=types.Content( + parts=[ + types.Part(function_call=types.FunctionCall()), + ] + ) + ), + ] + assert generate_content_response.text is None + assert any( + record.levelname == 'WARNING' + and 'there are non-text parts in the response' in record.message + for record in caplog.records + ) + generate_content_response.candidates = None + + +def test_non_text_part_and_text_part_text(caplog, generate_content_response): + generate_content_response.candidates = [ + types.Candidate( + content=types.Content( + parts=[ + types.Part(function_call=types.FunctionCall()), + types.Part(text='World1'), + ] + ) + ), + ] + + assert generate_content_response.text == 'World1' + assert not any( + record.levelname == 'WARNING' + and 'there are no text parts in the response' in record.message + for record in caplog.records + ) + generate_content_response.candidates = None + + +def test_candidates_none_function_calls(): + response = types.GenerateContentResponse() + assert response.function_calls is None + + +def test_candidates_empty_function_calls(): + response = types.GenerateContentResponse(candidates=[]) + assert response.function_calls is None + + +def test_content_none_function_calls(): + response = types.GenerateContentResponse(candidates=[types.Candidate()]) + assert response.function_calls is None + + +def test_parts_none_function_calls(): + response = types.GenerateContentResponse( + candidates=[types.Candidate(content=types.Content())] + ) + assert response.function_calls is None + + +def test_parts_empty_function_calls(): + response = types.GenerateContentResponse( + candidates=[ + types.Candidate(content=types.Content(parts=[])), + ] + ) + assert response.function_calls is None + + +def test_multiple_candidates_function_calls(caplog, generate_content_response): + generate_content_response.candidates = [ + types.Candidate( + content=types.Content( + parts=[ + types.Part( + function_call=types.FunctionCall.model_validate({ + 'args': {'key1': 'value1'}, + 'name': 'funcCall1', + }) + ) + ] + ) + ), + types.Candidate( + content=types.Content( + parts=[ + types.Part( + function_call=types.FunctionCall.model_validate({ + 'args': {'key2': 'value2'}, + 'name': 'funcCall2', + }) + ) + ] + ) + ), + ] + assert generate_content_response.function_calls == [ + types.FunctionCall(name='funcCall1', args={'key1': 'value1'}) + ] + assert any( + record.levelname == 'WARNING' + and 'there are multiple candidates in the response' in record.message + for record in caplog.records + ) + generate_content_response.candidates = None + + +def test_multiple_function_calls(): + response = types.GenerateContentResponse( + candidates=[ + types.Candidate( + content=types.Content( + parts=[ + types.Part( + function_call=types.FunctionCall.model_validate({ + 'args': {'key1': 'value1'}, + 'name': 'funcCall1', + }) + ), + types.Part( + function_call=types.FunctionCall.model_validate({ + 'args': {'key2': 'value2'}, + 'name': 'funcCall2', + }) + ), + ] + ) + ), + ] + ) + assert response.function_calls == [ + types.FunctionCall(name='funcCall1', args={'key1': 'value1'}), + types.FunctionCall(name='funcCall2', args={'key2': 'value2'}), + ] + + +def test_no_function_calls(): + response = types.GenerateContentResponse( + candidates=[ + types.Candidate( + content=types.Content( + parts=[ + types.Part(text='Hello1'), + types.Part(text='World1'), + ] + ) + ), + ] + ) + assert response.function_calls is None + + +def test_executable_code_empty_candidates(): + response = types.GenerateContentResponse() + + assert response.executable_code is None + + +def test_executable_code_empty_content(): + response = types.GenerateContentResponse(candidates=[]) + + assert response.executable_code is None + + +def test_executable_code_empty_parts(): + response = types.GenerateContentResponse(candidates=[types.Candidate( + content=types.Content() + )]) + + assert response.executable_code is None + + +def test_executable_code_two_candidates(caplog, generate_content_response): + generate_content_response.candidates = [ + types.Candidate( + content=types.Content( + parts=[ + types.Part( + executable_code=types.ExecutableCode( + code='print("hello")', language='PYTHON' + ) + ) + ] + ) + ), + types.Candidate( + content=types.Content( + parts=[ + types.Part( + executable_code=types.ExecutableCode( + code='print("world")', language='PYTHON' + ) + ) + ] + ) + ), + ] + + assert generate_content_response.executable_code == 'print("hello")' + assert any( + record.levelname == 'WARNING' + and 'there are multiple candidates in the response' in record.message + for record in caplog.records + ) + generate_content_response.candidates = None + +def test_executable_code_one_candidate(): + response = types.GenerateContentResponse( + candidates=[ + types.Candidate( + content=types.Content( + parts=[ + types.Part( + executable_code=types.ExecutableCode( + code='print("hello")', language='PYTHON' + ) + ) + ] + ) + ) + ] + ) + + assert response.executable_code == 'print("hello")' + + +def test_code_execution_result_empty_candidates(): + response = types.GenerateContentResponse() + + assert response.code_execution_result is None, response.code_execution_result + + +def test_code_execution_result_empty_content(): + response = types.GenerateContentResponse(candidates=[]) + + assert response.code_execution_result is None + + +def test_code_execution_result_empty_parts(): + response = types.GenerateContentResponse( + candidates=[types.Candidate(content=types.Content())] + ) + + assert response.code_execution_result is None + + +def test_code_execution_result_two_candidates(caplog, generate_content_response): + generate_content_response.candidates = [ + types.Candidate( + content=types.Content( + parts=[ + types.Part( + code_execution_result=types.CodeExecutionResult( + outcome='OUTCOME_OK', output='"hello"' + ) + ) + ] + ) + ), + types.Candidate( + content=types.Content( + parts=[ + types.Part( + code_execution_result=types.CodeExecutionResult( + outcome='OUTCOME_ERROR', output='"world"' + ) + ) + ] + ) + ), + ] + + assert generate_content_response.code_execution_result == '"hello"' + assert any ( + record.levelname == 'WARNING' + and 'there are multiple candidates in the response' in record.message + for record in caplog.records + ) + generate_content_response.candidates = None + + +def test_code_execution_result_one_candidate(): + response = types.GenerateContentResponse( + candidates=[ + types.Candidate( + content=types.Content( + parts=[ + types.Part( + code_execution_result=types.CodeExecutionResult( + outcome='OUTCOME_OK', output='"hello"' + ) + ) + ] + ) + ) + ] + ) + + assert response.code_execution_result == '"hello"' + + +def test_from_file_media_resolution_str(): + file_uri = types.Part.from_uri( + file_uri='gs://test', + mime_type='image/png', + media_resolution='MEDIA_RESOLUTION_LOW', + ) + assert file_uri.file_data.file_uri == 'gs://test' + assert file_uri.file_data.mime_type == 'image/png' + assert file_uri.media_resolution.level == types.PartMediaResolutionLevel.MEDIA_RESOLUTION_LOW + + +def test_from_file_media_resolution_enum(): + file_uri = types.Part.from_uri( + file_uri='gs://test', + mime_type='image/png', + media_resolution=types.PartMediaResolutionLevel.MEDIA_RESOLUTION_LOW, + ) + assert file_uri.file_data.file_uri == 'gs://test' + assert file_uri.file_data.mime_type == 'image/png' + assert file_uri.media_resolution.level == types.PartMediaResolutionLevel.MEDIA_RESOLUTION_LOW + + +def test_from_file_media_resolution_object(): + file_uri = types.Part.from_uri( + file_uri='gs://test', + mime_type='image/png', + media_resolution=types.PartMediaResolution(level='MEDIA_RESOLUTION_LOW'), + ) + assert file_uri.file_data.file_uri == 'gs://test' + assert file_uri.file_data.mime_type == 'image/png' + assert file_uri.media_resolution.level == types.PartMediaResolutionLevel.MEDIA_RESOLUTION_LOW + + +def test_from_bytes_media_resolution_str(): + file_uri = types.Part.from_bytes( + data=b'1234', + mime_type='image/png', + media_resolution='MEDIA_RESOLUTION_LOW', + ) + assert file_uri.inline_data.data == b'1234' + assert file_uri.inline_data.mime_type == 'image/png' + assert file_uri.media_resolution.level == types.PartMediaResolutionLevel.MEDIA_RESOLUTION_LOW + + +def test_from_bytes_media_resolution_enum(): + file_uri = types.Part.from_bytes( + data=b'1234', + mime_type='image/png', + media_resolution=types.PartMediaResolutionLevel.MEDIA_RESOLUTION_LOW, + ) + assert file_uri.inline_data.data == b'1234' + assert file_uri.inline_data.mime_type == 'image/png' + assert file_uri.media_resolution.level == types.PartMediaResolutionLevel.MEDIA_RESOLUTION_LOW + + +def test_from_bytes_media_resolution_object(): + file_uri = types.Part.from_bytes( + data=b'1234', + mime_type='image/png', + media_resolution=types.PartMediaResolution(level='MEDIA_RESOLUTION_LOW'), + ) + assert file_uri.inline_data.data == b'1234' + assert file_uri.inline_data.mime_type == 'image/png' + assert file_uri.media_resolution.level == types.PartMediaResolutionLevel.MEDIA_RESOLUTION_LOW diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/types/test_schema_from_json_schema.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/types/test_schema_from_json_schema.py new file mode 100644 index 0000000000000000000000000000000000000000..04a72c45e2712ea6ed3ce4cacf6c8a1647330f18 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/types/test_schema_from_json_schema.py @@ -0,0 +1,417 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +import logging +import pydantic + +from ... import types + + +def _get_not_none_fields(model: pydantic.BaseModel) -> list[str]: + """Returns field names in a Pydantic model whose values are not None.""" + return [ + field for field, value in model.model_dump().items() if value is not None + ] + + +def test_empty_json_schema_conversion(): + """Test conversion of empty JSONSchema to Schema.""" + json_schema = types.JSONSchema() + gemini_api_schema = types.Schema.from_json_schema(json_schema=json_schema) + vertex_ai_schema = types.Schema.from_json_schema( + json_schema=json_schema, api_option='VERTEX_AI' + ) + + assert gemini_api_schema == types.Schema() + assert vertex_ai_schema == types.Schema() + + +def test_not_null_type_conversion(): + """Test conversion of JSONSchema.type to Schema.type""" + json_schema_types = [ + 'string', + 'number', + 'integer', + 'boolean', + 'array', + 'object', + ] + schema_types = [ + 'STRING', + 'NUMBER', + 'INTEGER', + 'BOOLEAN', + 'ARRAY', + 'OBJECT', + ] + for json_schema_type, expected_type in zip(json_schema_types, schema_types): + json_schema1 = types.JSONSchema(type=types.JSONSchemaType(json_schema_type)) + json_schema2 = types.JSONSchema(type=json_schema_type) + gemini_api_schema1 = types.Schema.from_json_schema(json_schema=json_schema1) + vertex_ai_schema1 = types.Schema.from_json_schema( + json_schema=json_schema1, api_option='VERTEX_AI' + ) + gemini_api_schema2 = types.Schema.from_json_schema(json_schema=json_schema2) + vertex_ai_schema2 = types.Schema.from_json_schema( + json_schema=json_schema2, api_option='VERTEX_AI' + ) + + gemini_api_not_none_field_name1 = _get_not_none_fields(gemini_api_schema1) + vertex_api_not_none_field_name1 = _get_not_none_fields(vertex_ai_schema1) + gemini_api_not_none_field_name2 = _get_not_none_fields(gemini_api_schema2) + vertex_ai_not_none_field_name2 = _get_not_none_fields(vertex_ai_schema2) + + assert gemini_api_schema1.type == expected_type + assert vertex_ai_schema1.type == expected_type + assert gemini_api_schema2.type == expected_type + assert vertex_ai_schema2.type == expected_type + assert gemini_api_not_none_field_name1 == ['type'] + assert vertex_api_not_none_field_name1 == ['type'] + assert gemini_api_not_none_field_name2 == ['type'] + assert vertex_ai_not_none_field_name2 == ['type'] + + +def test_nullable_conversion(): + """Test conversion of JSONSchema.nullable to Schema.nullable""" + json_schema1 = types.JSONSchema( + type=[types.JSONSchemaType('string'), types.JSONSchemaType('null')], + ) + json_schema2 = types.JSONSchema( + type=['string', 'null'], + ) + gemini_api_schema1 = types.Schema.from_json_schema(json_schema=json_schema1) + vertex_ai_schema1 = types.Schema.from_json_schema( + json_schema=json_schema1, api_option='VERTEX_AI' + ) + gemini_api_schema2 = types.Schema.from_json_schema(json_schema=json_schema2) + vertex_ai_schema2 = types.Schema.from_json_schema( + json_schema=json_schema2, api_option='VERTEX_AI' + ) + gemini_api_not_none_field_names1 = _get_not_none_fields(gemini_api_schema1) + vertex_ai_not_none_field_names1 = _get_not_none_fields(vertex_ai_schema1) + gemini_api_not_none_field_names2 = _get_not_none_fields(gemini_api_schema2) + vertex_ai_not_none_field_names2 = _get_not_none_fields(vertex_ai_schema2) + + assert gemini_api_schema1.nullable + assert vertex_ai_schema1.nullable + assert gemini_api_schema2.nullable + assert vertex_ai_schema2.nullable + assert set(gemini_api_not_none_field_names1) == set(['type', 'nullable']) + assert set(vertex_ai_not_none_field_names1) == set(['type', 'nullable']) + assert set(gemini_api_not_none_field_names2) == set(['type', 'nullable']) + assert set(vertex_ai_not_none_field_names2) == set(['type', 'nullable']) + + +def test_nullable_in_union_like_type_conversion(): + """Test conversion of JSONSchema.nullable to Schema.nullable""" + json_schema1 = types.JSONSchema( + type=[ + types.JSONSchemaType('string'), + types.JSONSchemaType('null'), + types.JSONSchemaType('object'), + types.JSONSchemaType('number'), + types.JSONSchemaType('array'), + types.JSONSchemaType('boolean'), + types.JSONSchemaType('integer'), + ], + ) + gemini_api_schema1 = types.Schema.from_json_schema(json_schema=json_schema1) + vertex_ai_schema1 = types.Schema.from_json_schema( + json_schema=json_schema1, api_option='VERTEX_AI' + ) + gemini_api_not_none_field_names1 = _get_not_none_fields(gemini_api_schema1) + vertex_ai_not_none_field_names1 = _get_not_none_fields(vertex_ai_schema1) + json_schema2 = types.JSONSchema( + type=[ + 'string', + 'null', + 'object', + 'number', + 'array', + 'boolean', + 'integer', + ] + ) + gemini_api_schema2 = types.Schema.from_json_schema(json_schema=json_schema2) + vertex_ai_schema2 = types.Schema.from_json_schema( + json_schema=json_schema2, api_option='VERTEX_AI' + ) + expected_schema = types.Schema( + nullable=True, + any_of=[ + types.Schema(type='STRING'), + types.Schema(type='OBJECT'), + types.Schema(type='NUMBER'), + types.Schema(type='ARRAY'), + types.Schema(type='BOOLEAN'), + types.Schema(type='INTEGER'), + ], + ) + + assert gemini_api_schema1 == expected_schema + assert vertex_ai_schema1 == expected_schema + assert gemini_api_schema2 == expected_schema + assert vertex_ai_schema2 == expected_schema + + +def test_union_like_type_conversion_suite1(): + """Test conversion of JSONSchema.type to Schema.any_of""" + json_schema = types.JSONSchema( + type=[ + types.JSONSchemaType('string'), + types.JSONSchemaType('object'), + types.JSONSchemaType('null'), + ], + description='description', + default='default', + max_length=10, + min_length=5, + enum=['value1', 'value2'], + format='format', + pattern='pattern', + title='title', + min_properties=1, + max_properties=2, + required=['field1', 'field2'], + properties={ + 'field1': types.JSONSchema(type='string'), + 'field2': types.JSONSchema(type='integer'), + }, + ) + actual_gemini_api_schema = types.Schema.from_json_schema( + json_schema=json_schema + ) + actual_vertex_ai_schema = types.Schema.from_json_schema( + json_schema=json_schema, api_option='VERTEX_AI' + ) + expected_schema = types.Schema( + nullable=True, + any_of=[ + types.Schema( + type='STRING', + description='description', + max_length=10, + min_length=5, + enum=['value1', 'value2'], + format='format', + pattern='pattern', + title='title', + ), + types.Schema( + type='OBJECT', + properties={ + 'field1': types.Schema(type='STRING'), + 'field2': types.Schema(type='INTEGER'), + }, + required=['field1', 'field2'], + min_properties=1, + max_properties=2, + title='title', + description='description', + ), + ], + ) + + assert actual_gemini_api_schema == expected_schema + assert actual_vertex_ai_schema == expected_schema + + +def test_union_like_type_conversion_suite2(): + """Test conversion of JSONSchema.type to Schema.any_of""" + json_schema = types.JSONSchema( + type=[ + types.JSONSchemaType('integer'), + types.JSONSchemaType('array'), + ], + description='description', + items=types.JSONSchema(type='integer', maximum=2, minimum=1), + min_items=1, + max_items=2, + title='title', + enum=['1', '2'], + maximum=2, + minimum=1, + ) + actual_gemini_api_schema = types.Schema.from_json_schema( + json_schema=json_schema + ) + actual_vertex_ai_schema = types.Schema.from_json_schema( + json_schema=json_schema, api_option='VERTEX_AI' + ) + expected_schema = types.Schema( + any_of=[ + types.Schema( + type='INTEGER', + description='description', + maximum=2, + minimum=1, + enum=['1', '2'], + title='title', + ), + types.Schema( + type='ARRAY', + items=types.Schema(type='INTEGER', maximum=2, minimum=1), + min_items=1, + max_items=2, + title='title', + description='description', + ), + ], + ) + + assert actual_gemini_api_schema == expected_schema + assert actual_vertex_ai_schema == expected_schema + + +def test_array_type_conversion(): + """Test conversion of JSONSchema.items to Schema.items""" + json_schema = types.JSONSchema( + type=types.JSONSchemaType('array'), + items=types.JSONSchema( + type='object', + properties={ + 'field1': types.JSONSchema(type='string'), + 'field2': types.JSONSchema(type='integer'), + }, + required=['field1', 'field2'], + min_properties=1, + max_properties=2, + title='title', + description='description', + ), + ) + gemini_api_schema = types.Schema.from_json_schema(json_schema=json_schema) + vertex_ai_schema = types.Schema.from_json_schema( + json_schema=json_schema, api_option='VERTEX_AI' + ) + expected_schema = types.Schema( + type='ARRAY', + items=types.Schema( + type='OBJECT', + properties={ + 'field1': types.Schema(type='STRING'), + 'field2': types.Schema(type='INTEGER'), + }, + required=['field1', 'field2'], + min_properties=1, + max_properties=2, + title='title', + description='description', + ), + ) + + assert gemini_api_schema == expected_schema + assert vertex_ai_schema == expected_schema + + +def test_complex_object_type_conversion(): + """Test conversion of JSONSchema.properties to Schema.properties""" + json_schema = types.JSONSchema( + type=types.JSONSchemaType('object'), + properties={ + 'field1': types.JSONSchema( + type=['string', 'array', 'null'], + description='description1', + max_length=20, + min_length=15, + enum=['value1', 'value2'], + format='format', + pattern='pattern', + title='title1', + items=types.JSONSchema(type='integer', maximum=2, minimum=1), + min_items=1, + max_items=2, + ), + 'field2': types.JSONSchema(type='integer'), + }, + required=['field1', 'field2'], + min_properties=1, + max_properties=2, + title='title', + description='description', + ) + gemini_api_schema = types.Schema.from_json_schema(json_schema=json_schema) + vertex_ai_schema = types.Schema.from_json_schema( + json_schema=json_schema, api_option='VERTEX_AI' + ) + expected_schema = types.Schema( + type='OBJECT', + properties={ + 'field1': types.Schema( + nullable=True, + any_of=[ + types.Schema( + type='STRING', + description='description1', + max_length=20, + min_length=15, + enum=['value1', 'value2'], + format='format', + pattern='pattern', + title='title1', + ), + types.Schema( + type='ARRAY', + items=types.Schema(type='INTEGER', maximum=2, minimum=1), + min_items=1, + max_items=2, + title='title1', + description='description1', + ), + ], + ), + 'field2': types.Schema(type='INTEGER'), + }, + required=['field1', 'field2'], + min_properties=1, + max_properties=2, + title='title', + description='description', + ) + + assert gemini_api_schema == expected_schema + assert vertex_ai_schema == expected_schema + + +def test_from_json_schema_logs_only_once(caplog): + """Test that the info message is logged only once across multiple from_json_schema calls.""" + from ... import types as types_module + + types_module._from_json_schema_warning_logged = False + + caplog.set_level(logging.INFO, logger='google_genai.types') + + json_schema1 = types_module.JSONSchema(type='string') + schema1 = types_module.Schema.from_json_schema(json_schema=json_schema1) + + assert len(caplog.records) == 1 + assert 'Json Schema is now supported natively' in caplog.text + assert 'response_json_schema' in caplog.text + + json_schema2 = types_module.JSONSchema(type='number') + schema2 = types_module.Schema.from_json_schema(json_schema=json_schema2) + + assert len(caplog.records) == 1 + + json_schema3 = types_module.JSONSchema(type='object') + schema3 = types_module.Schema.from_json_schema(json_schema=json_schema3) + + assert len(caplog.records) == 1 + + assert schema1.type == types_module.Type('STRING') + assert schema2.type == types_module.Type('NUMBER') + assert schema3.type == types.Type('OBJECT') + + types_module._from_json_schema_warning_logged = False diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/types/test_schema_json_schema.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/types/test_schema_json_schema.py new file mode 100644 index 0000000000000000000000000000000000000000..576c87ee21ffc6912826d0888d050ad2535bc356 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/types/test_schema_json_schema.py @@ -0,0 +1,468 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +import logging +import pydantic + +from ... import types + + +def _get_not_none_fields(model: pydantic.BaseModel) -> list[str]: + """Returns field names in a Pydantic model whose values are not None.""" + return [ + field for field, value in model.model_dump().items() if value is not None + ] + + +def test_empty_schema_conversion(): + """Test conversion of empty Schema to JSONSchema.""" + schema = types.Schema() + json_schema = schema.json_schema + not_none_field_names = _get_not_none_fields(json_schema) + + assert json_schema == types.JSONSchema() + assert not_none_field_names == [] + + +def test_not_null_type_conversion(): + """Test conversion of Schema.type to JSONSchema.type.""" + schema_types = [ + 'OBJECT', + 'ARRAY', + 'STRING', + 'NUMBER', + 'BOOLEAN', + 'INTEGER', + ] + json_schema_types = [ + 'object', + 'array', + 'string', + 'number', + 'boolean', + 'integer', + ] + for schema_type, expected_type in zip(schema_types, json_schema_types): + schema = types.Schema(type=schema_type) + json_schema = schema.json_schema + not_none_field_names = _get_not_none_fields(json_schema) + assert json_schema.type == types.JSONSchemaType(expected_type) + assert not_none_field_names == ['type'] + + +def test_unspecified_type_conversion(): + """Test conversion of Schema.type to JSONSchema.type.""" + schema = types.Schema(type='TYPE_UNSPECIFIED') + json_schema = schema.json_schema + not_none_field_names = _get_not_none_fields(json_schema) + + assert json_schema.type is None + assert not_none_field_names == [] + + +def test_nullable_conversion(): + """Test conversion of Schema.nullable to JSONSchema.type.""" + schema = types.Schema(type='STRING', nullable=True) + json_schema = schema.json_schema + not_none_field_names = _get_not_none_fields(json_schema) + + assert set(json_schema.type) == set([ + types.JSONSchemaType('null'), + types.JSONSchemaType('string') + ]) + assert not_none_field_names == ['type'] + + +def test_property_conversion(): + """Test conversion of Schema.properties to JSONSchema.properties.""" + schema = types.Schema( + type='OBJECT', + properties={ + 'key1': types.Schema(type='STRING'), + 'key2': types.Schema(type='NUMBER'), + }, + ) + json_schema = schema.json_schema + not_none_field_names = _get_not_none_fields(json_schema) + + assert json_schema.properties == { + 'key1': types.JSONSchema(type=types.JSONSchemaType('string')), + 'key2': types.JSONSchema(type=types.JSONSchemaType('number')), + } + assert json_schema.type == types.JSONSchemaType('object') + assert not_none_field_names == ['type', 'properties'] + + +def test_complex_property_conversion(): + """Test conversion of complex Schema.properties to JSONSchema.properties.""" + schema = types.Schema( + type='OBJECT', + properties={ + 'key1': types.Schema( + type='OBJECT', + properties={ + 'key2': types.Schema(type='STRING'), + 'key3': types.Schema(type='NUMBER'), + }, + ), + 'key2': types.Schema(type='ARRAY', items=types.Schema(type='STRING')), + }, + ) + json_schema = schema.json_schema + not_none_field_names = _get_not_none_fields(json_schema) + + assert json_schema.properties == { + 'key1': types.JSONSchema( + type=types.JSONSchemaType('object'), + properties={ + 'key2': types.JSONSchema(type=types.JSONSchemaType('string')), + 'key3': types.JSONSchema(type=types.JSONSchemaType('number')), + }, + ), + 'key2': types.JSONSchema( + type=types.JSONSchemaType('array'), + items=types.JSONSchema(type=types.JSONSchemaType('string')), + ), + } + assert json_schema.type == types.JSONSchemaType('object') + assert not_none_field_names == ['type', 'properties'] + + +def test_items_conversion(): + """Test conversion of Schema.items to JSONSchema.items.""" + schema = types.Schema( + type='ARRAY', + items=types.Schema(type='STRING'), + ) + json_schema = schema.json_schema + not_none_field_names = _get_not_none_fields(json_schema) + + assert json_schema.type == types.JSONSchemaType('array') + assert json_schema.items == types.JSONSchema( + type=types.JSONSchemaType('string') + ) + assert not_none_field_names == ['type', 'items'] + + +def test_complex_items_conversion(): + """Test conversion of complex Schema.items to JSONSchema.items.""" + schema = types.Schema( + type='ARRAY', + items=types.Schema( + type='OBJECT', + properties={ + 'key1': types.Schema(type='STRING'), + 'key2': types.Schema(type='NUMBER'), + }, + ), + ) + json_schema = schema.json_schema + not_none_field_names = _get_not_none_fields(json_schema) + + assert json_schema.type == types.JSONSchemaType('array') + assert json_schema.items == types.JSONSchema( + type=types.JSONSchemaType('object'), + properties={ + 'key1': types.JSONSchema(type=types.JSONSchemaType('string')), + 'key2': types.JSONSchema(type=types.JSONSchemaType('number')), + }, + ) + assert not_none_field_names == ['type', 'items'] + + +def test_any_of_conversion(): + """Test conversion of Schema.any_of to JSONSchema.any_of.""" + schema = types.Schema( + type='OBJECT', + any_of=[ + types.Schema(type='STRING'), + types.Schema(type='NUMBER'), + ], + ) + json_schema = schema.json_schema + not_none_field_names = _get_not_none_fields(json_schema) + + assert json_schema.type == types.JSONSchemaType('object') + assert json_schema.any_of == [ + types.JSONSchema(type=types.JSONSchemaType('string')), + types.JSONSchema(type=types.JSONSchemaType('number')), + ] + assert not_none_field_names == ['type', 'any_of'] + + +def test_complex_any_of_conversion(): + """Test conversion of complex Schema.any_of to JSONSchema.any_of.""" + schema = types.Schema( + type='OBJECT', + any_of=[ + types.Schema( + type='OBJECT', + properties={ + 'key1': types.Schema(type='STRING'), + 'key2': types.Schema(type='NUMBER'), + }, + ), + types.Schema(type='ARRAY', items=types.Schema(type='STRING')), + ], + ) + json_schema = schema.json_schema + not_none_field_names = _get_not_none_fields(json_schema) + + assert json_schema.type == types.JSONSchemaType('object') + assert json_schema.any_of == [ + types.JSONSchema( + type=types.JSONSchemaType('object'), + properties={ + 'key1': types.JSONSchema(type=types.JSONSchemaType('string')), + 'key2': types.JSONSchema(type=types.JSONSchemaType('number')), + }, + ), + types.JSONSchema( + type=types.JSONSchemaType('array'), + items=types.JSONSchema(type=types.JSONSchemaType('string')), + ), + ] + assert not_none_field_names == ['type', 'any_of'] + + +def test_example_conversion(): + """Test conversion of Schema.direct to JSONSchema.direct.""" + schema = types.Schema( + example='this is an example', + ) + json_schema = schema.json_schema + not_none_field_names = _get_not_none_fields(json_schema) + + assert not_none_field_names == [] + + +def test_property_ordering_conversion(): + """Test conversion of Schema.property_ordering to JSONSchema.property_ordering.""" + schema = types.Schema( + property_ordering=['a', 'b'], + ) + json_schema = schema.json_schema + not_none_field_names = _get_not_none_fields(json_schema) + + assert not_none_field_names == [] + + +def test_direct_conversion(): + """Test Schema fiedls that do not need to be converted.""" + schema = types.Schema( + pattern='^[a-z]+$', + default=1, + max_length=10, + title='title', + min_length=2, + min_properties=3, + max_properties=7, + description='description', + enum=['enum1', 'enum2'], + format='email', + max_items=199, + maximum=300, + min_items=6, + minimum=40, + required=['required1', 'required2'], + ) + json_schema = schema.json_schema + not_none_field_names = _get_not_none_fields(json_schema) + + assert json_schema.pattern == '^[a-z]+$' + assert json_schema.default == 1 + assert json_schema.max_length == 10 + assert json_schema.title == 'title' + assert json_schema.min_length == 2 + assert json_schema.min_properties == 3 + assert json_schema.max_properties == 7 + assert json_schema.description == 'description' + assert json_schema.enum == ['enum1', 'enum2'] + assert json_schema.format == 'email' + assert json_schema.max_items == 199 + assert json_schema.maximum == 300 + assert json_schema.min_items == 6 + assert json_schema.minimum == 40 + assert json_schema.required == ['required1', 'required2'] + assert not_none_field_names.sort() == [ + 'pattern', + 'default', + 'max_length', + 'title', + 'min_length', + 'min_properties', + 'max_properties', + 'description', + 'enum', + 'format', + 'max_items', + 'maximum', + 'min_items', + 'minimum', + 'required', + ].sort() + + +def test_complex_any_of_conversion(): + schema = types.Schema( + type=types.Type.OBJECT, + title='Fruit Basket', + description='A structured representation of a fruit basket', + properties={ + 'fruit': types.Schema( + type=types.Type.ARRAY, + description='An ordered list of the fruit in the basket', + items=types.Schema( + any_of=[ + types.Schema( + title='Apple', + description='Describes an apple', + type=types.Type.OBJECT, + properties={ + 'type': types.Schema( + type=types.Type.STRING, + description='Always "apple"', + ), + 'variety': types.Schema( + type=types.Type.STRING, + description=( + 'The variety of apple (e.g., "Granny' + ' Smith")' + ), + ), + }, + property_ordering=['type', 'variety'], + required=['type', 'variety'], + ), + types.Schema( + title='Orange', + description='Describes an orange', + type=types.Type.OBJECT, + properties={ + 'type': types.Schema( + type=types.Type.STRING, + description='Always "orange"', + ), + 'variety': types.Schema( + type=types.Type.STRING, + description=( + 'The variety of orange (e.g.,"Navel' + ' orange")' + ), + ), + }, + property_ordering=['type', 'variety'], + required=['type', 'variety'], + ), + ], + ), + ), + }, + required=['fruit'], + ) + json_schema = schema.json_schema + not_none_field_names = _get_not_none_fields(json_schema) + + assert json_schema.type == types.JSONSchemaType('object') + assert json_schema.title == 'Fruit Basket' + assert json_schema.description == 'A structured representation of a fruit basket' + assert json_schema.properties == { + 'fruit': types.JSONSchema( + type=types.JSONSchemaType('array'), + description='An ordered list of the fruit in the basket', + items=types.JSONSchema( + any_of=[ + types.JSONSchema( + title='Apple', + description='Describes an apple', + type=types.JSONSchemaType('object'), + properties={ + 'type': types.JSONSchema( + type=types.JSONSchemaType('string'), + description='Always "apple"', + ), + 'variety': types.JSONSchema( + type=types.JSONSchemaType('string'), + description=( + 'The variety of apple (e.g., "Granny' + ' Smith")' + ), + ), + }, + required=['type', 'variety'], + ), + types.JSONSchema( + title='Orange', + description='Describes an orange', + type=types.JSONSchemaType('object'), + properties={ + 'type': types.JSONSchema( + type=types.JSONSchemaType('string'), + description='Always "orange"', + ), + 'variety': types.JSONSchema( + type=types.JSONSchemaType('string'), + description=( + 'The variety of orange (e.g.,"Navel orange")' + ), + ), + }, + required=['type', 'variety'], + ), + ], + ), + ), + } + assert json_schema.required == ['fruit'] + assert not_none_field_names == [ + 'type', + 'title', + 'description', + 'properties', + 'required', + ] + + +def test_json_schema_logs_only_once(caplog): + """Test that the info message is logged only once across multiple json_schema calls.""" + from ... import types as types_module + + types_module._json_schema_warning_logged = False + + caplog.set_level(logging.INFO, logger='google_genai.types') + + schema1 = types_module.Schema(type='STRING') + json_schema1 = schema1.json_schema + + assert len(caplog.records) == 1 + assert 'Json Schema is now supported natively' in caplog.text + assert 'response_json_schema' in caplog.text + + schema2 = types_module.Schema(type='NUMBER') + json_schema2 = schema2.json_schema + + assert len(caplog.records) == 1 + + schema3 = types_module.Schema(type='OBJECT') + json_schema3 = schema3.json_schema + + assert len(caplog.records) == 1 + + assert json_schema1.type == types_module.JSONSchemaType('string') + assert json_schema2.type == types_module.JSONSchemaType('number') + assert json_schema3.type == types_module.JSONSchemaType('object') + + types_module._json_schema_warning_logged = False diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/types/test_types.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/types/test_types.py new file mode 100644 index 0000000000000000000000000000000000000000..099ff2a2dc2b52c9ffb592392cf59d7e1b4deb49 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tests/types/test_types.py @@ -0,0 +1,2927 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + + +import copy +import json +import sys +import typing +from typing import Optional, assert_never +import PIL.Image +import pydantic +import pytest +from ... import types + +_is_mcp_imported = False +if typing.TYPE_CHECKING: + from mcp import types as mcp_types + + _is_mcp_imported = True +else: + try: + from mcp import types as mcp_types + + _is_mcp_imported = True + except ImportError: + mcp_types = None + + +class SubPart(types.Part): + pass + + +class SubFunctionResponsePart(types.FunctionResponsePart): + pass + + +def test_factory_method_from_uri_part(): + + my_part = SubPart.from_uri( + file_uri='gs://generativeai-downloads/images/scones.jpg', + mime_type='image/jpeg', + ) + assert ( + my_part.file_data.file_uri + == 'gs://generativeai-downloads/images/scones.jpg' + ) + assert my_part.file_data.mime_type == 'image/jpeg' + assert isinstance(my_part, SubPart) + + +def test_factory_method_from_uri_inferred_mime_type_part(): + + my_part = SubPart.from_uri( + file_uri='gs://generativeai-downloads/images/scones.jpg', + ) + assert ( + my_part.file_data.file_uri + == 'gs://generativeai-downloads/images/scones.jpg' + ) + assert my_part.file_data.mime_type == 'image/jpeg' + assert isinstance(my_part, SubPart) + + +def test_factory_method_from_text_part(): + my_part = SubPart.from_text(text='What is your name?') + assert my_part.text == 'What is your name?' + assert isinstance(my_part, SubPart) + + +def test_factory_method_from_bytes_part(): + my_part = SubPart.from_bytes(data=b'123', mime_type='text/plain') + assert my_part.inline_data.data == b'123' + assert my_part.inline_data.mime_type == 'text/plain' + assert isinstance(my_part, SubPart) + + +def test_factory_method_from_function_call_part(): + my_part = SubPart.from_function_call(name='func', args={'arg': 'value'}) + assert my_part.function_call.name == 'func' + assert my_part.function_call.args == {'arg': 'value'} + assert isinstance(my_part, SubPart) + + +def test_factory_method_from_function_response_part(): + my_part = SubPart.from_function_response( + name='func', response={'response': 'value'} + ) + assert my_part.function_response.name == 'func' + assert my_part.function_response.response == {'response': 'value'} + assert isinstance(my_part, SubPart) + + +def test_factory_method_part_from_function_response_with_multi_modal_parts(): + my_part = SubPart.from_function_response( + name='func', + response={'response': 'value'}, + parts=[{'inline_data': {'data': b'123', 'mime_type': 'image/png'}}], + ) + assert my_part.function_response.name == 'func' + assert my_part.function_response.response == {'response': 'value'} + assert my_part.function_response.parts[0].inline_data.data == b'123' + assert my_part.function_response.parts[0].inline_data.mime_type == 'image/png' + assert isinstance(my_part, SubPart) + + +def test_factory_method_function_response_part_from_bytes(): + my_part = SubFunctionResponsePart.from_bytes( + data=b'123', mime_type='image/png' + ) + assert my_part.inline_data.data == b'123' + assert my_part.inline_data.mime_type == 'image/png' + assert isinstance(my_part, SubFunctionResponsePart) + + +def test_factory_method_function_response_part_from_uri(): + my_part = SubFunctionResponsePart.from_uri( + file_uri='gs://generativeai-downloads/images/scones.jpg', + mime_type='image/jpeg', + ) + assert ( + my_part.file_data.file_uri + == 'gs://generativeai-downloads/images/scones.jpg' + ) + assert my_part.file_data.mime_type == 'image/jpeg' + assert isinstance(my_part, SubFunctionResponsePart) + + +def test_factory_method_from_executable_code_part(): + my_part = SubPart.from_executable_code( + code='print("hello")', language='PYTHON' + ) + assert my_part.executable_code.code == 'print("hello")' + assert my_part.executable_code.language == 'PYTHON' + assert isinstance(my_part, SubPart) + + +def test_factory_method_from_code_execution_result_part(): + my_part = SubPart.from_code_execution_result( + outcome='OUTCOME_OK', output='print("hello")' + ) + assert my_part.code_execution_result.outcome == 'OUTCOME_OK' + assert my_part.code_execution_result.output == 'print("hello")' + assert isinstance(my_part, SubPart) + + +def test_factory_method_from_mcp_call_tool_function_response_on_error(): + if not _is_mcp_imported: + return + + call_tool_result = mcp_types.CallToolResult( + content=[], + isError=True, + ) + my_function_response = types.FunctionResponse.from_mcp_response( + name='func_name', response=call_tool_result + ) + assert my_function_response.name == 'func_name' + assert my_function_response.response == {'error': 'MCP response is error.'} + assert isinstance(my_function_response, types.FunctionResponse) + + +def test_factory_method_from_mcp_call_tool_function_response_text(): + if not _is_mcp_imported: + return + + call_tool_result = mcp_types.CallToolResult( + content=[ + mcp_types.TextContent(type='text', text='hello'), + mcp_types.TextContent(type='text', text=' world'), + ], + ) + my_function_response = types.FunctionResponse.from_mcp_response( + name='func_name', response=call_tool_result + ) + assert my_function_response.name == 'func_name' + assert my_function_response.response == { + 'result': [ + mcp_types.TextContent(type='text', text='hello'), + mcp_types.TextContent(type='text', text=' world'), + ] + } + assert isinstance(my_function_response, types.FunctionResponse) + + +def test_factory_method_from_mcp_call_tool_function_response_inline_data(): + if not _is_mcp_imported: + return + + call_tool_result = mcp_types.CallToolResult( + content=[ + mcp_types.ImageContent( + type='image', + data='MTIz', + mimeType='text/plain', + ), + mcp_types.ImageContent( + type='image', + data='NDU2', + mimeType='text/plain', + ), + ], + ) + my_function_response = types.FunctionResponse.from_mcp_response( + name='func_name', response=call_tool_result + ) + assert my_function_response.name == 'func_name' + assert my_function_response.response == { + 'result': [ + mcp_types.ImageContent( + type='image', + data='MTIz', + mimeType='text/plain', + ), + mcp_types.ImageContent( + type='image', + data='NDU2', + mimeType='text/plain', + ), + ] + } + assert isinstance(my_function_response, types.FunctionResponse) + + +def test_factory_method_from_mcp_call_tool_function_response_combined_content(): + if not _is_mcp_imported: + return + + call_tool_result = mcp_types.CallToolResult( + content=[ + mcp_types.TextContent( + type='text', + text='Hello', + ), + mcp_types.ImageContent( + type='image', + data='NDU2', + mimeType='text/plain', + ), + ], + ) + my_function_response = types.FunctionResponse.from_mcp_response( + name='func_name', response=call_tool_result + ) + assert my_function_response.name == 'func_name' + assert my_function_response.response == { + 'result': [ + mcp_types.TextContent( + type='text', + text='Hello', + ), + mcp_types.ImageContent( + type='image', + data='NDU2', + mimeType='text/plain', + ), + ] + } + assert isinstance(my_function_response, types.FunctionResponse) + + +def test_factory_method_from_mcp_call_tool_function_response_embedded_resource(): + if not _is_mcp_imported: + return + + call_tool_result = mcp_types.CallToolResult( + content=[ + mcp_types.EmbeddedResource( + type='resource', + resource=mcp_types.TextResourceContents( + uri='https://generativelanguage.googleapis.com/v1beta/files/ansa0kyotrsw', + text='hello', + ), + ), + ], + ) + my_function_response = types.FunctionResponse.from_mcp_response( + name='func_name', response=call_tool_result + ) + assert my_function_response.name == 'func_name' + assert my_function_response.response == { + 'result': [ + mcp_types.EmbeddedResource( + type='resource', + resource=mcp_types.TextResourceContents( + uri='https://generativelanguage.googleapis.com/v1beta/files/ansa0kyotrsw', + text='hello', + ), + ), + ] + } + assert isinstance(my_function_response, types.FunctionResponse) + + +def test_part_constructor_with_string_value(): + part = types.Part('hello') + assert part.text == 'hello' + assert part.file_data is None + assert part.inline_data is None + + +def test_part_constructor_with_part_value(): + other_part = types.Part(text='hello from other part') + part = types.Part(other_part) + assert part.text == 'hello from other part' + + +def test_part_constructor_with_part_dict_value(): + part = types.Part({'text': 'hello from dict'}) + assert part.text == 'hello from dict' + + +def test_part_constructor_with_file_data_dict_value(): + part = types.Part( + {'file_uri': 'gs://my-bucket/file-data', 'mime_type': 'text/plain'} + ) + assert part.file_data.file_uri == 'gs://my-bucket/file-data' + assert part.file_data.mime_type == 'text/plain' + + +def test_part_constructor_with_kwargs_and_value_fails(): + with pytest.raises( + ValueError, match='Positional and keyword arguments can not be combined' + ): + types.Part('hello', text='world') + + +def test_part_constructor_with_file_value(): + f = types.File( + uri='gs://my-bucket/my-file', + mime_type='text/plain', + display_name='test file', + ) + part = types.Part(f) + assert part.file_data.file_uri == 'gs://my-bucket/my-file' + assert part.file_data.mime_type == 'text/plain' + assert part.file_data.display_name == 'test file' + + +def test_part_constructor_with_pil_image(): + img = PIL.Image.new('RGB', (1, 1), color='red') + part = types.Part(img) + assert part.inline_data.mime_type == 'image/jpeg' + assert isinstance(part.inline_data.data, bytes) + + +class FakeClient: + + def __init__(self, vertexai=False) -> None: + self.vertexai = vertexai + + +mldev_client = FakeClient() +vertex_client = FakeClient(vertexai=True) + + +def test_empty_function(): + def func_under_test(): + """test empty function.""" + pass + + expected_schema_mldev = types.FunctionDeclaration( + name='func_under_test', + description='test empty function.', + ) + expected_schema_vertex = copy.deepcopy(expected_schema_mldev) + + actual_schema_mldev = types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + actual_schema_vertex = types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + + assert actual_schema_mldev == expected_schema_mldev + assert actual_schema_vertex == expected_schema_vertex + + +def test_built_in_primitives_and_compounds(): + + def func_under_test( + a: int, + b: float, + c: bool, + d: str, + e: list, + f: dict, + ): + """test built in primitives and compounds.""" + pass + + expected_schema = types.FunctionDeclaration( + name='func_under_test', + parameters=types.Schema( + type='OBJECT', + properties={ + 'a': types.Schema(type='INTEGER'), + 'b': types.Schema(type='NUMBER'), + 'c': types.Schema(type='BOOLEAN'), + 'd': types.Schema(type='STRING'), + 'e': types.Schema(type='ARRAY'), + 'f': types.Schema(type='OBJECT'), + }, + required=['a', 'b', 'c', 'd', 'e', 'f'], + ), + description='test built in primitives and compounds.', + ) + + actual_schema_mldev = types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + actual_schema_vertex = types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + + assert actual_schema_mldev == expected_schema + assert actual_schema_vertex == expected_schema + + +def test_default_value_built_in_type(): + def func_under_test(a: str, b: int = '1', c: list = []): + """test default value not compatible built in type.""" + pass + + types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + + +def test_default_value_built_in_type(): + def func_under_test(a: str, b: int = 1, c: list = []): + """test default value.""" + pass + + expected_schema = types.FunctionDeclaration( + name='func_under_test', + parameters=types.Schema( + type='OBJECT', + properties={ + 'a': types.Schema(type='STRING'), + 'b': types.Schema(type='INTEGER', default=1), + 'c': types.Schema(type='ARRAY', default=[]), + }, + required=['a'], + ), + description='test default value.', + ) + + actual_schema_vertex = types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + actual_schema_mldev = types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + + assert actual_schema_vertex == expected_schema + assert actual_schema_mldev == expected_schema + + +@pytest.mark.skipif( + sys.version_info < (3, 10), + reason='| is only supported in Python 3.10 and above.', +) +def test_built_in_primitives_compounds(): + def func_under_test1(a: bytes): + pass + + def func_under_test2(a: set): + pass + + def func_under_test3(a: frozenset): + pass + + def func_under_test4(a: type(None)): + pass + + def func_under_test5(a: int | bytes): + pass + + def func_under_test6(a: int | set): + pass + + def func_under_test7(a: int | frozenset): + pass + + def func_under_test8(a: typing.Union[int, bytes]): + pass + + def func_under_test9(a: typing.Union[int, set]): + pass + + def func_under_test10(a: typing.Union[int, frozenset]): + pass + + all_func_under_test = [ + func_under_test1, + func_under_test2, + func_under_test3, + func_under_test4, + func_under_test5, + func_under_test6, + func_under_test7, + func_under_test8, + func_under_test9, + func_under_test10, + ] + for func_under_test in all_func_under_test: + types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + + +@pytest.mark.skipif( + sys.version_info < (3, 10), + reason='| is only supported in Python 3.10 and above.', +) +def test_built_in_union_type(): + + def func_under_test( + a: int | str | float | bool, + b: list | dict, + ): + """test built in union type.""" + pass + + expected_schema = types.FunctionDeclaration( + name='func_under_test', + parameters=types.Schema( + type='OBJECT', + properties={ + 'a': types.Schema( + type='OBJECT', + any_of=[ + types.Schema(type='INTEGER'), + types.Schema(type='STRING'), + types.Schema(type='NUMBER'), + types.Schema(type='BOOLEAN'), + ], + ), + 'b': types.Schema( + type='OBJECT', + any_of=[ + types.Schema(type='ARRAY'), + types.Schema(type='OBJECT'), + ], + ), + }, + required=['a', 'b'], + ), + description='test built in union type.', + ) + + actual_schema_mldev = types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + actual_schema_vertex = types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + + assert actual_schema_vertex == expected_schema + assert actual_schema_mldev == expected_schema + + +def test_built_in_union_type_all_py_versions(): + + def func_under_test( + a: typing.Union[int, str, float, bool], + b: typing.Union[list, dict], + ): + """test built in union type.""" + pass + + expected_schema = types.FunctionDeclaration( + name='func_under_test', + parameters=types.Schema( + type='OBJECT', + properties={ + 'a': types.Schema( + type='OBJECT', + any_of=[ + types.Schema(type='INTEGER'), + types.Schema(type='STRING'), + types.Schema(type='NUMBER'), + types.Schema(type='BOOLEAN'), + ], + ), + 'b': types.Schema( + type='OBJECT', + any_of=[ + types.Schema(type='ARRAY'), + types.Schema(type='OBJECT'), + ], + ), + }, + required=['a', 'b'], + ), + description='test built in union type.', + ) + + actual_schema_mldev = types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + actual_schema_vertex = types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + + assert actual_schema_vertex == expected_schema + assert actual_schema_mldev == expected_schema + + +@pytest.mark.skipif( + sys.version_info < (3, 10), + reason='| is only supported in Python 3.10 and above.', +) +def test_default_value_built_in_union_type(): + def func_under_test( + a: int | str = 1.1, + ): + """test default value not compatible built in union type.""" + pass + + types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + + +def test_default_value_built_in_union_type_all_py_versions(): + def func_under_test( + a: typing.Union[int, str] = 1.1, + ): + """test default value not compatible built in union type.""" + pass + + types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + + +@pytest.mark.skipif( + sys.version_info < (3, 10), + reason='| is only supported in Python 3.10 and above.', +) +def test_default_value_built_in_union_type(): + + def func_under_test( + a: int | str = '1', + b: list | dict = [], + c: list | dict = {}, + ): + """test default value built in union type.""" + pass + + expected_schema = types.FunctionDeclaration( + name='func_under_test', + parameters=types.Schema( + type='OBJECT', + properties={ + 'a': types.Schema( + type='OBJECT', + any_of=[ + types.Schema(type='INTEGER'), + types.Schema(type='STRING'), + ], + default='1', + ), + 'b': types.Schema( + type='OBJECT', + any_of=[ + types.Schema(type='ARRAY'), + types.Schema(type='OBJECT'), + ], + default=[], + ), + 'c': types.Schema( + type='OBJECT', + any_of=[ + types.Schema(type='ARRAY'), + types.Schema(type='OBJECT'), + ], + default={}, + ), + }, + required=[], + ), + description='test default value built in union type.', + ) + + actual_schema_vertex = types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + actual_schema_mldev = types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + + assert actual_schema_vertex == expected_schema + assert actual_schema_mldev == expected_schema + + +def test_default_value_built_in_union_type_all_py_versions(): + + def func_under_test( + a: typing.Union[int, str] = '1', + b: typing.Union[list, dict] = [], + c: typing.Union[list, dict] = {}, + ): + """test default value built in union type.""" + pass + + expected_schema = types.FunctionDeclaration( + name='func_under_test', + parameters=types.Schema( + type='OBJECT', + properties={ + 'a': types.Schema( + type='OBJECT', + any_of=[ + types.Schema(type='INTEGER'), + types.Schema(type='STRING'), + ], + default='1', + ), + 'b': types.Schema( + type='OBJECT', + any_of=[ + types.Schema(type='ARRAY'), + types.Schema(type='OBJECT'), + ], + default=[], + ), + 'c': types.Schema( + type='OBJECT', + any_of=[ + types.Schema(type='ARRAY'), + types.Schema(type='OBJECT'), + ], + default={}, + ), + }, + required=[], + ), + description='test default value built in union type.', + ) + + actual_schema_vertex = types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + actual_schema_mldev = types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + + assert actual_schema_vertex == expected_schema + assert actual_schema_mldev == expected_schema + + +def test_generic_alias_literal(): + + def func_under_test(a: typing.Literal['a', 'b', 'c']): + """test generic alias literal.""" + pass + + expected_schema = types.FunctionDeclaration( + name='func_under_test', + parameters=types.Schema( + type='OBJECT', + properties={ + 'a': types.Schema( + type='STRING', + enum=['a', 'b', 'c'], + ), + }, + required=['a'], + ), + description='test generic alias literal.', + ) + + actual_schema_mldev = types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + actual_schema_vertex = types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + + assert actual_schema_mldev == expected_schema + assert actual_schema_vertex == expected_schema + + +def test_default_value_generic_alias_literal(): + + def func_under_test(a: typing.Literal['1', '2', '3'] = '1'): + """test default value generic alias literal.""" + pass + + expected_schema = types.FunctionDeclaration( + name='func_under_test', + parameters=types.Schema( + type='OBJECT', + properties={ + 'a': types.Schema( + type='STRING', + enum=['1', '2', '3'], + default='1', + ), + }, + required=[], + ), + description='test default value generic alias literal.', + ) + + actual_schema_vertex = types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + actual_schema_mldev = types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + + assert actual_schema_vertex == expected_schema + assert actual_schema_mldev == expected_schema + + +def test_default_value_generic_alias_literal(): + def func_under_test(a: typing.Literal['1', '2', 3]): + """test default value generic alias literal not compatible.""" + pass + + types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + + +def test_default_value_generic_alias_literal_with_str_default(): + def func_under_test(a: typing.Literal['a', 'b', 'c'] = 'd'): + """test default value not compatible generic alias literal.""" + pass + + types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + + +def test_generic_alias_array(): + + def func_under_test( + a: typing.List[int], + ): + """test generic alias array.""" + pass + + expected_schema = types.FunctionDeclaration( + name='func_under_test', + parameters=types.Schema( + type='OBJECT', + properties={ + 'a': types.Schema( + type='ARRAY', items=types.Schema(type='INTEGER') + ), + }, + required=['a'], + ), + description='test generic alias array.', + ) + + actual_schema_mldev = types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + actual_schema_vertex = types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + + assert actual_schema_mldev == expected_schema + assert actual_schema_vertex == expected_schema + + +@pytest.mark.skipif( + sys.version_info < (3, 10), + reason='| is only supported in Python 3.10 and above.', +) +def test_generic_alias_complex_array(): + + def func_under_test( + a: typing.List[int | str | float | bool], + b: typing.List[list | dict], + ): + """test generic alias complex array.""" + pass + + expected_schema = types.FunctionDeclaration( + name='func_under_test', + parameters=types.Schema( + type='OBJECT', + properties={ + 'a': types.Schema( + type='ARRAY', + items=types.Schema( + type='OBJECT', + any_of=[ + types.Schema(type='INTEGER'), + types.Schema(type='STRING'), + types.Schema(type='NUMBER'), + types.Schema(type='BOOLEAN'), + ], + ), + ), + 'b': types.Schema( + type='ARRAY', + items=types.Schema( + type='OBJECT', + any_of=[ + types.Schema(type='ARRAY'), + types.Schema(type='OBJECT'), + ], + ), + ), + }, + required=['a', 'b'], + ), + description='test generic alias complex array.', + ) + + actual_schema_mldev = types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + actual_schema_vertex = types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + assert actual_schema_vertex == expected_schema + assert actual_schema_mldev == expected_schema + + +def test_generic_alias_complex_array_all_py_versions(): + + def func_under_test( + a: typing.List[typing.Union[int, str, float, bool]], + b: typing.List[typing.Union[list, dict]], + ): + """test generic alias complex array.""" + pass + + expected_schema = types.FunctionDeclaration( + name='func_under_test', + parameters=types.Schema( + type='OBJECT', + properties={ + 'a': types.Schema( + type='ARRAY', + items=types.Schema( + type='OBJECT', + any_of=[ + types.Schema(type='INTEGER'), + types.Schema(type='STRING'), + types.Schema(type='NUMBER'), + types.Schema(type='BOOLEAN'), + ], + ), + ), + 'b': types.Schema( + type='ARRAY', + items=types.Schema( + type='OBJECT', + any_of=[ + types.Schema(type='ARRAY'), + types.Schema(type='OBJECT'), + ], + ), + ), + }, + required=['a', 'b'], + ), + description='test generic alias complex array.', + ) + + actual_schema_mldev = types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + actual_schema_vertex = types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + assert actual_schema_vertex == expected_schema + assert actual_schema_mldev == expected_schema + + +@pytest.mark.skipif( + sys.version_info < (3, 10), + reason='| is only supported in Python 3.10 and above.', +) +def test_generic_alias_complex_array_with_default_value(): + + def func_under_test( + a: typing.List[int | str | float | bool] = [ + 1, + 'a', + 1.1, + True, + ], + b: list[int | str | float | bool] = [ + 11, + 'aa', + 1.11, + False, + ], + c: typing.List[typing.List[int] | int] = [[1], 2], + ): + """test generic alias complex array with default value.""" + pass + + expected_schema = types.FunctionDeclaration( + name='func_under_test', + parameters=types.Schema( + type='OBJECT', + properties={ + 'a': types.Schema( + type='ARRAY', + items=types.Schema( + type='OBJECT', + any_of=[ + types.Schema(type='INTEGER'), + types.Schema(type='STRING'), + types.Schema(type='NUMBER'), + types.Schema(type='BOOLEAN'), + ], + ), + default=[1, 'a', 1.1, True], + ), + 'b': types.Schema( + type='ARRAY', + items=types.Schema( + type='OBJECT', + any_of=[ + types.Schema(type='INTEGER'), + types.Schema(type='STRING'), + types.Schema(type='NUMBER'), + types.Schema(type='BOOLEAN'), + ], + ), + default=[11, 'aa', 1.11, False], + ), + 'c': types.Schema( + type='ARRAY', + items=types.Schema( + type='OBJECT', + any_of=[ + types.Schema( + type='ARRAY', + items=types.Schema(type='INTEGER'), + ), + types.Schema(type='INTEGER'), + ], + ), + default=[[1], 2], + ), + }, + required=[], + ), + description='test generic alias complex array with default value.', + ) + + actual_schema_vertex = types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + actual_schema_mldev = types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + + assert actual_schema_vertex == expected_schema + assert actual_schema_mldev == expected_schema + + +def test_generic_alias_complex_array_with_default_value_all_py_versions(): + + def func_under_test( + a: typing.List[typing.Union[int, str, float, bool]] = [ + 1, + 'a', + 1.1, + True, + ], + b: list[typing.Union[int, str, float, bool]] = [ + 11, + 'aa', + 1.11, + False, + ], + c: typing.List[typing.Union[typing.List[int], int]] = [[1], 2], + ): + """test generic alias complex array with default value.""" + pass + + expected_schema = types.FunctionDeclaration( + name='func_under_test', + parameters=types.Schema( + type='OBJECT', + properties={ + 'a': types.Schema( + type='ARRAY', + items=types.Schema( + type='OBJECT', + any_of=[ + types.Schema(type='INTEGER'), + types.Schema(type='STRING'), + types.Schema(type='NUMBER'), + types.Schema(type='BOOLEAN'), + ], + ), + default=[1, 'a', 1.1, True], + ), + 'b': types.Schema( + type='ARRAY', + items=types.Schema( + type='OBJECT', + any_of=[ + types.Schema(type='INTEGER'), + types.Schema(type='STRING'), + types.Schema(type='NUMBER'), + types.Schema(type='BOOLEAN'), + ], + ), + default=[11, 'aa', 1.11, False], + ), + 'c': types.Schema( + type='ARRAY', + items=types.Schema( + type='OBJECT', + any_of=[ + types.Schema( + type='ARRAY', + items=types.Schema(type='INTEGER'), + ), + types.Schema(type='INTEGER'), + ], + ), + default=[[1], 2], + ), + }, + required=[], + ), + description='test generic alias complex array with default value.', + ) + + actual_schema_vertex = types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + actual_schema_mldev = types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + + assert actual_schema_vertex == expected_schema + assert actual_schema_mldev == expected_schema + + +@pytest.mark.skipif( + sys.version_info < (3, 10), + reason='| is only supported in Python 3.10 and above.', +) +def test_generic_alias_complex_array_with_default_value_not_compatible(): + + def func_under_test1( + a: typing.List[int | str | float | bool] = [1, 'a', 1.1, True, []], + ): + """test generic alias complex array with default value not compatible.""" + pass + + def func_under_test2( + a: list[int | str | float | bool] = [1, 'a', 1.1, True, []], + ): + """test generic alias complex array with default value not compatible.""" + pass + + for func_under_test in [func_under_test1, func_under_test2]: + types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + + +def test_generic_alias_complex_array_with_default_value_not_compatible_all_py_versions(): + + def func_under_test1( + a: typing.List[typing.Union[int, str, float, bool]] = [ + 1, + 'a', + 1.1, + True, + [], + ], + ): + """test generic alias complex array with default value not compatible.""" + pass + + def func_under_test2( + a: list[typing.Union[int, str, float, bool]] = [1, 'a', 1.1, True, []], + ): + """test generic alias complex array with default value not compatible.""" + pass + + for func_under_test in [func_under_test1, func_under_test2]: + types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + + +def test_generic_alias_object(): + + def func_under_test( + a: typing.Dict[str, int], + ): + """test generic alias object.""" + pass + + expected_schema = types.FunctionDeclaration( + name='func_under_test', + parameters=types.Schema( + type='OBJECT', + properties={ + 'a': types.Schema(type='OBJECT'), + }, + required=['a'], + ), + description='test generic alias object.', + ) + + actual_schema_mldev = types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + actual_schema_vertex = types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + + assert actual_schema_mldev == expected_schema + assert actual_schema_vertex == expected_schema + + +def test_supported_uncommon_generic_alias_object(): + def func_under_test1(a: typing.OrderedDict[str, int]): + """test uncommon generic alias object.""" + pass + + def func_under_test2(a: typing.MutableMapping[str, int]): + """test uncommon generic alias object.""" + pass + + def func_under_test3(a: typing.MutableSequence[int]): + """test uncommon generic alias object.""" + pass + + def func_under_test4(a: typing.MutableSet[int]): + """test uncommon generic alias object.""" + pass + + def func_under_test5(a: typing.Counter[int]): + """test uncommon generic alias object.""" + pass + + def func_under_test6(a: typing.Iterable[int]): + """test uncommon generic alias object.""" + pass + + def func_under_test7(a: typing.DefaultDict[int, int]): + """test uncommon generic alias object.""" + pass + + all_func_under_test = [ + func_under_test1, + func_under_test2, + func_under_test3, + func_under_test4, + func_under_test5, + func_under_test6, + func_under_test7, + ] + + for func_under_test in all_func_under_test: + types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + + +def test_unsupported_uncommon_generic_alias_object(): + + def func_under_test1(a: typing.Collection[int]): + """test uncommon generic alias object.""" + pass + + def func_under_test2(a: typing.Iterator[int]): + """test uncommon generic alias object.""" + pass + + def func_under_test3(a: typing.Container[int]): + """test uncommon generic alias object.""" + pass + + def func_under_test4(a: typing.ChainMap[int, int]): + """test uncommon generic alias object.""" + pass + + all_func_under_test = [ + func_under_test1, + func_under_test2, + func_under_test3, + func_under_test4, + ] + + for func_under_test in all_func_under_test: + with pytest.raises(ValueError): + types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + with pytest.raises(ValueError): + types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + + +def test_generic_alias_object_with_default_value(): + def func_under_test(a: typing.Dict[str, int] = {'a': 1}): + """test generic alias object with default value.""" + pass + + expected_schema = types.FunctionDeclaration( + name='func_under_test', + parameters=types.Schema( + type='OBJECT', + properties={ + 'a': types.Schema( + type='OBJECT', + default={'a': 1}, + ), + }, + required=[], + ), + description='test generic alias object with default value.', + ) + + actual_schema_vertex = types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + actual_schema_mldev = types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + + assert actual_schema_vertex == expected_schema + assert actual_schema_mldev == expected_schema + + +def test_generic_alias_object_with_default_value_not_compatible(): + def func_under_test(a: typing.Dict[str, int] = 'a'): + """test generic alias object with default value not compatible.""" + pass + + types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + + +def test_pydantic_model(): + class MySimplePydanticModel(pydantic.BaseModel): + a_simple: int + b_simple: str + + class MyComplexPydanticModel(pydantic.BaseModel): + a_complex: MySimplePydanticModel + b_complex: list[MySimplePydanticModel] + + def func_under_test( + a: MySimplePydanticModel, + b: MyComplexPydanticModel, + ): + """test pydantic model.""" + pass + + expected_schema = types.FunctionDeclaration( + name='func_under_test', + parameters=types.Schema( + type='OBJECT', + properties={ + 'a': types.Schema( + type='OBJECT', + properties={ + 'a_simple': types.Schema(type='INTEGER'), + 'b_simple': types.Schema(type='STRING'), + }, + required=['a_simple', 'b_simple'], + ), + 'b': types.Schema( + type='OBJECT', + properties={ + 'a_complex': types.Schema( + type='OBJECT', + properties={ + 'a_simple': types.Schema(type='INTEGER'), + 'b_simple': types.Schema(type='STRING'), + }, + required=['a_simple', 'b_simple'], + ), + 'b_complex': types.Schema( + type='ARRAY', + items=types.Schema( + type='OBJECT', + properties={ + 'a_simple': types.Schema(type='INTEGER'), + 'b_simple': types.Schema(type='STRING'), + }, + required=['a_simple', 'b_simple'], + ), + ), + }, + required=['a_complex', 'b_complex'], + ), + }, + required=['a', 'b'], + ), + description='test pydantic model.', + ) + + actual_schema_mldev = types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + actual_schema_vertex = types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + + assert actual_schema_mldev == expected_schema + assert actual_schema_vertex == expected_schema + + +def test_pydantic_model_in_list_type(): + class MySimplePydanticModel(pydantic.BaseModel): + a_simple: int + b_simple: str + + def func_under_test( + a: list[MySimplePydanticModel], + ): + """test pydantic model in list type.""" + pass + + expected_schema = types.FunctionDeclaration( + name='func_under_test', + parameters=types.Schema( + type='OBJECT', + properties={ + 'a': types.Schema( + type='ARRAY', + items=types.Schema( + type='OBJECT', + properties={ + 'a_simple': types.Schema(type='INTEGER'), + 'b_simple': types.Schema(type='STRING'), + }, + required=['a_simple', 'b_simple'], + ), + ), + }, + required=['a'], + ), + description='test pydantic model in list type.', + ) + + actual_schema_mldev = types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + actual_schema_vertex = types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + + assert actual_schema_mldev == expected_schema + assert actual_schema_vertex == expected_schema + + +def test_pydantic_model_in_union_type(): + class CatInformationObject(pydantic.BaseModel): + name: str + age: int + like_purring: bool + + class DogInformationObject(pydantic.BaseModel): + name: str + age: int + like_barking: bool + + def func_under_test( + animal: typing.Union[CatInformationObject, DogInformationObject], + ): + """test pydantic model in union type.""" + pass + + expected_schema = types.FunctionDeclaration( + name='func_under_test', + parameters=types.Schema( + type='OBJECT', + properties={ + 'animal': types.Schema( + type='OBJECT', + any_of=[ + types.Schema( + type='OBJECT', + properties={ + 'name': types.Schema(type='STRING'), + 'age': types.Schema(type='INTEGER'), + 'like_purring': types.Schema(type='BOOLEAN'), + }, + ), + types.Schema( + type='OBJECT', + properties={ + 'name': types.Schema(type='STRING'), + 'age': types.Schema(type='INTEGER'), + 'like_barking': types.Schema(type='BOOLEAN'), + }, + ), + ], + ), + }, + required=['animal'], + ), + description='test pydantic model in union type.', + ) + expected_schema.parameters.properties['animal'].any_of[0].required = [ + 'name', + 'age', + 'like_purring', + ] + expected_schema.parameters.properties['animal'].any_of[1].required = [ + 'name', + 'age', + 'like_barking', + ] + + actual_schema_mldev = types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + actual_schema_vertex = types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + + assert actual_schema_vertex == expected_schema + assert actual_schema_mldev == expected_schema + + +def test_pydantic_model_with_default_value(): + class MySimplePydanticModel(pydantic.BaseModel): + a_simple: Optional[int] + b_simple: Optional[str] + + mySimplePydanticModel = MySimplePydanticModel(a_simple=1, b_simple='a') + + def func_under_test(a: MySimplePydanticModel = mySimplePydanticModel): + """test pydantic model with default value.""" + pass + + expected_schema = types.FunctionDeclaration( + description='test pydantic model with default value.', + name='func_under_test', + parameters=types.Schema( + type='OBJECT', + properties={ + 'a': types.Schema( + default=MySimplePydanticModel(a_simple=1, b_simple='a'), + type='OBJECT', + properties={ + 'a_simple': types.Schema( + nullable=True, + type='INTEGER', + ), + 'b_simple': types.Schema( + nullable=True, + type='STRING', + ), + }, + required=[], + ) + }, + required=[], + ), + ) + + actual_schema_vertex = types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + actual_schema_mldev = types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + + assert actual_schema_vertex == expected_schema + assert actual_schema_mldev == expected_schema + + +def test_custom_class(): + + class MyClass: + a: int + b: str + + def __init__(self, a: int): + self.a = a + self.b = str(a) + + def func_under_test(a: MyClass): + """test custom class.""" + pass + + with pytest.raises(ValueError): + types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + with pytest.raises(ValueError): + types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + + +@pytest.mark.skipif( + sys.version_info < (3, 10), + reason='| is only supported in Python 3.10 and above.', +) +def test_type_union(): + + def func_under_test( + a: typing.Union[int, str], + b: typing.Union[list, dict], + c: typing.Union[typing.List[typing.Union[int, float]], dict], + d: list | dict, + ): + """test type union.""" + pass + + expected_schema = types.FunctionDeclaration( + name='func_under_test', + parameters=types.Schema( + type='OBJECT', + properties={ + 'a': types.Schema( + type='OBJECT', + any_of=[ + types.Schema(type='INTEGER'), + types.Schema(type='STRING'), + ], + ), + 'b': types.Schema( + type='OBJECT', + any_of=[ + types.Schema(type='ARRAY'), + types.Schema(type='OBJECT'), + ], + ), + 'c': types.Schema( + type='OBJECT', + any_of=[ + types.Schema( + type='ARRAY', + items=types.Schema( + type='OBJECT', + any_of=[ + types.Schema(type='INTEGER'), + types.Schema(type='NUMBER'), + ], + ), + ), + types.Schema( + type='OBJECT', + ), + ], + ), + 'd': types.Schema( + type='OBJECT', + any_of=[ + types.Schema(type='ARRAY'), + types.Schema(type='OBJECT'), + ], + ), + }, + required=['a', 'b', 'c', 'd'], + ), + description='test type union.', + ) + + actual_schema_mldev = types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + actual_schema_vertex = types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + + assert actual_schema_vertex == expected_schema + assert actual_schema_mldev == expected_schema + + +def test_type_union_all_py_versions(): + + def func_under_test( + a: typing.Union[int, str], + b: typing.Union[list, dict], + c: typing.Union[typing.List[typing.Union[int, float]], dict], + ): + """test type union.""" + pass + + expected_schema = types.FunctionDeclaration( + name='func_under_test', + parameters=types.Schema( + type='OBJECT', + properties={ + 'a': types.Schema( + type='OBJECT', + any_of=[ + types.Schema(type='INTEGER'), + types.Schema(type='STRING'), + ], + ), + 'b': types.Schema( + type='OBJECT', + any_of=[ + types.Schema(type='ARRAY'), + types.Schema(type='OBJECT'), + ], + ), + 'c': types.Schema( + type='OBJECT', + any_of=[ + types.Schema( + type='ARRAY', + items=types.Schema( + type='OBJECT', + any_of=[ + types.Schema(type='INTEGER'), + types.Schema(type='NUMBER'), + ], + ), + ), + types.Schema( + type='OBJECT', + ), + ], + ), + }, + required=['a', 'b', 'c'], + ), + description='test type union.', + ) + + actual_schema_mldev = types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + actual_schema_vertex = types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + + assert actual_schema_vertex == expected_schema + assert actual_schema_mldev == expected_schema + + +def test_type_optional_with_list(): + + def func_under_test( + a: str, + b: typing.Optional[list[str]] = None, + ): + """test type optional with list.""" + pass + + expected_schema = types.FunctionDeclaration( + name='func_under_test', + parameters=types.Schema( + type='OBJECT', + properties={ + 'a': types.Schema(type='STRING'), + 'b': types.Schema( + nullable=True, type='ARRAY', items=types.Schema(type='STRING') + ), + }, + required=['a'], + ), + description='test type optional with list.', + ) + + actual_schema_mldev = types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + actual_schema_vertex = types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + + assert actual_schema_vertex == expected_schema + assert actual_schema_mldev == expected_schema + + +@pytest.mark.skipif( + sys.version_info < (3, 10), + reason='| is only supported in Python 3.10 and above.', +) +def test_type_union_with_default_value(): + + def func_under_test( + a: typing.Union[int, str] = 1, + b: typing.Union[list, dict] = [1], + c: typing.Union[typing.List[typing.Union[int, float]], dict] = {}, + d: list | dict = [1, 2, 3], + ): + """test type union with default value.""" + pass + + expected_schema = types.FunctionDeclaration( + name='func_under_test', + parameters=types.Schema( + type='OBJECT', + properties={ + 'a': types.Schema( + type='OBJECT', + any_of=[ + types.Schema(type='INTEGER'), + types.Schema(type='STRING'), + ], + default=1, + ), + 'b': types.Schema( + type='OBJECT', + any_of=[ + types.Schema(type='ARRAY'), + types.Schema(type='OBJECT'), + ], + default=[1], + ), + 'c': types.Schema( + type='OBJECT', + any_of=[ + types.Schema( + type='ARRAY', + items=types.Schema( + type='OBJECT', + any_of=[ + types.Schema(type='INTEGER'), + types.Schema(type='NUMBER'), + ], + ), + ), + types.Schema( + type='OBJECT', + ), + ], + default={}, + ), + 'd': types.Schema( + type='OBJECT', + any_of=[ + types.Schema(type='ARRAY'), + types.Schema(type='OBJECT'), + ], + default=[1, 2, 3], + ), + }, + required=[], + ), + description='test type union with default value.', + ) + + actual_schema_vertex = types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + actual_schema_mldev = types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + + assert actual_schema_vertex == expected_schema + assert actual_schema_mldev == expected_schema + + +def test_type_union_with_default_value_all_py_versions(): + + def func_under_test( + a: typing.Union[int, str] = 1, + b: typing.Union[list, dict] = [1], + c: typing.Union[typing.List[typing.Union[int, float]], dict] = {}, + ): + """test type union with default value.""" + pass + + expected_schema = types.FunctionDeclaration( + name='func_under_test', + parameters=types.Schema( + type='OBJECT', + properties={ + 'a': types.Schema( + type='OBJECT', + any_of=[ + types.Schema(type='INTEGER'), + types.Schema(type='STRING'), + ], + default=1, + ), + 'b': types.Schema( + type='OBJECT', + any_of=[ + types.Schema(type='ARRAY'), + types.Schema(type='OBJECT'), + ], + default=[1], + ), + 'c': types.Schema( + type='OBJECT', + any_of=[ + types.Schema( + type='ARRAY', + items=types.Schema( + type='OBJECT', + any_of=[ + types.Schema(type='INTEGER'), + types.Schema(type='NUMBER'), + ], + ), + ), + types.Schema( + type='OBJECT', + ), + ], + default={}, + ), + }, + required=[], + ), + description='test type union with default value.', + ) + + actual_schema_vertex = types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + actual_schema_mldev = types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + + assert actual_schema_vertex == expected_schema + assert actual_schema_mldev == expected_schema + + +@pytest.mark.skipif( + sys.version_info < (3, 10), + reason='| is only supported in Python 3.10 and above.', +) +def test_type_union_with_default_value(): + + def func_under_test1( + a: typing.Union[typing.List[typing.Union[int, float]], dict] = 1, + ): + """test type union with default value not compatible.""" + pass + + def func_under_test2( + a: list | dict = 1, + ): + """test type union with default value not compatible.""" + pass + + all_func_under_test = [func_under_test1, func_under_test2] + + for func_under_test in all_func_under_test: + types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + + +def test_type_union_with_default_value_not_compatible_all_py_versions(): + + def func_under_test1( + a: typing.Union[typing.List[typing.Union[int, float]], dict] = 1, + ): + """test type union with default value not compatible.""" + pass + + def func_under_test2( + a: typing.Union[list, dict] = 1, + ): + """test type union with default value not compatible.""" + pass + + all_func_under_test = [func_under_test1, func_under_test2] + + for func_under_test in all_func_under_test: + types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + + +@pytest.mark.skipif( + sys.version_info < (3, 10), + reason='| is not supported in Python 3.9', +) +def test_type_nullable(): + + def func_under_test( + a: int | float | None, + b: typing.Union[list, None], + c: typing.Union[list, dict, None], + d: typing.Optional[int] = None, + ): + """test type nullable.""" + pass + + expected_schema = types.FunctionDeclaration( + name='func_under_test', + parameters=types.Schema( + type='OBJECT', + properties={ + 'a': types.Schema( + type='OBJECT', + any_of=[ + types.Schema(type='INTEGER'), + types.Schema(type='NUMBER'), + ], + nullable=True, + ), + 'b': types.Schema( + type='ARRAY', + nullable=True, + ), + 'c': types.Schema( + type='OBJECT', + any_of=[ + types.Schema(type='ARRAY'), + types.Schema(type='OBJECT'), + ], + nullable=True, + ), + 'd': types.Schema( + type='INTEGER', + nullable=True, + default=None, + ), + }, + required=[], + ), + description='test type nullable.', + ) + + actual_schema_mldev = types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + actual_schema_vertex = types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + + assert actual_schema_vertex == expected_schema + assert actual_schema_mldev == expected_schema + + +def test_type_nullable_all_py_versions(): + + def func_under_test( + b: typing.Union[list, None], + c: typing.Union[list, dict, None], + d: typing.Optional[int] = None, + ): + """test type nullable.""" + pass + + expected_schema = types.FunctionDeclaration( + name='func_under_test', + parameters=types.Schema( + type='OBJECT', + properties={ + 'b': types.Schema( + type='ARRAY', + nullable=True, + ), + 'c': types.Schema( + type='OBJECT', + any_of=[ + types.Schema(type='ARRAY'), + types.Schema(type='OBJECT'), + ], + nullable=True, + ), + 'd': types.Schema( + type='INTEGER', + nullable=True, + default=None, + ), + }, + required=[], + ), + description='test type nullable.', + ) + + actual_schema_mldev = types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + actual_schema_vertex = types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + + assert actual_schema_vertex == expected_schema + assert actual_schema_mldev == expected_schema + + +def test_empty_function_with_return_type(): + def func_under_test() -> int: + """test empty function with return type.""" + return 1 + + expected_schema_mldev = types.FunctionDeclaration( + name='func_under_test', + description='test empty function with return type.', + ) + expected_schema_vertex = copy.deepcopy(expected_schema_mldev) + expected_schema_vertex.response = types.Schema(type='INTEGER') + + actual_schema_mldev = types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + actual_schema_vertex = types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + + assert actual_schema_mldev == expected_schema_mldev + assert actual_schema_vertex == expected_schema_vertex + + +def test_simple_function_with_return_type(): + def func_under_test(a: int) -> str: + """test return type.""" + return '' + + expected_schema_mldev = types.FunctionDeclaration( + name='func_under_test', + parameters=types.Schema( + type='OBJECT', + properties={ + 'a': types.Schema(type='INTEGER'), + }, + required=['a'], + ), + description='test return type.', + ) + expected_schema_vertex = copy.deepcopy(expected_schema_mldev) + expected_schema_vertex.response = types.Schema(type='STRING') + + actual_schema_mldev = types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + actual_schema_vertex = types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + + assert actual_schema_mldev == expected_schema_mldev + assert actual_schema_vertex == expected_schema_vertex + + +@pytest.mark.skipif( + sys.version_info < (3, 10), + reason='| is not supported in Python 3.9', +) +def test_builtin_union_return_type(): + + def func_under_test() -> int | str | float | bool | list | dict | None: + """test builtin union return type.""" + pass + + expected_schema_mldev = types.FunctionDeclaration( + name='func_under_test', + description='test builtin union return type.', + ) + expected_schema_vertex = copy.deepcopy(expected_schema_mldev) + expected_schema_vertex.response_json_schema = types.Schema( + type='OBJECT', + any_of=[ + types.Schema(type='INTEGER'), + types.Schema(type='STRING'), + types.Schema(type='NUMBER'), + types.Schema(type='BOOLEAN'), + types.Schema(type='ARRAY'), + types.Schema(type='OBJECT'), + ], + nullable=True, + ) + + actual_schema_mldev = types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + actual_schema_vertex = types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + + assert actual_schema_mldev == expected_schema_mldev + assert actual_schema_vertex == expected_schema_vertex + + +def test_builtin_union_return_type_all_py_versions(): + + def func_under_test() -> ( + typing.Union[int, str, float, bool, list, dict, None] + ): + """test builtin union return type.""" + pass + + expected_schema_mldev = types.FunctionDeclaration( + name='func_under_test', + description='test builtin union return type.', + ) + expected_schema_vertex = copy.deepcopy(expected_schema_mldev) + expected_schema_vertex.response_json_schema = types.Schema( + type='OBJECT', + any_of=[ + types.Schema(type='INTEGER'), + types.Schema(type='STRING'), + types.Schema(type='NUMBER'), + types.Schema(type='BOOLEAN'), + types.Schema(type='ARRAY'), + types.Schema(type='OBJECT'), + ], + nullable=True, + ) + + actual_schema_mldev = types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + actual_schema_vertex = types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + + assert actual_schema_mldev == expected_schema_mldev + assert actual_schema_vertex == expected_schema_vertex + + +def test_typing_union_return_type(): + + def func_under_test() -> ( + typing.Union[int, str, float, bool, list, dict, None] + ): + """test typing union return type.""" + pass + + expected_schema_mldev = types.FunctionDeclaration( + name='func_under_test', + description='test typing union return type.', + ) + expected_schema_vertex = copy.deepcopy(expected_schema_mldev) + expected_schema_vertex.response_json_schema = types.Schema( + type='OBJECT', + any_of=[ + types.Schema(type='INTEGER'), + types.Schema(type='STRING'), + types.Schema(type='NUMBER'), + types.Schema(type='BOOLEAN'), + types.Schema(type='ARRAY'), + types.Schema(type='OBJECT'), + ], + nullable=True, + ) + + actual_schema_mldev = types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + actual_schema_vertex = types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + + assert actual_schema_mldev == expected_schema_mldev + assert actual_schema_vertex == expected_schema_vertex + + +def test_return_type_optional(): + def func_under_test() -> typing.Optional[int]: + """test return type optional.""" + pass + + expected_schema_mldev = types.FunctionDeclaration( + name='func_under_test', + description='test return type optional.', + ) + expected_schema_vertex = copy.deepcopy(expected_schema_mldev) + expected_schema_vertex.response = types.Schema( + type='INTEGER', + nullable=True, + ) + + actual_schema_mldev = types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + actual_schema_vertex = types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + + assert actual_schema_mldev == expected_schema_mldev + assert actual_schema_vertex == expected_schema_vertex + + +def test_return_type_pydantic_model(): + class MySimplePydanticModel(pydantic.BaseModel): + a_simple: int + b_simple: str + + class MyComplexPydanticModel(pydantic.BaseModel): + a_complex: MySimplePydanticModel + b_complex: list[MySimplePydanticModel] + + def func_under_test() -> MyComplexPydanticModel: + """test return type pydantic model.""" + pass + + expected_schema_mldev = types.FunctionDeclaration( + name='func_under_test', + description='test return type pydantic model.', + ) + expected_schema_vertex = copy.deepcopy(expected_schema_mldev) + expected_schema_vertex.response = types.Schema( + type='OBJECT', + properties={ + 'a_complex': types.Schema( + type='OBJECT', + properties={ + 'a_simple': types.Schema(type='INTEGER'), + 'b_simple': types.Schema(type='STRING'), + }, + required=['a_simple', 'b_simple'], + ), + 'b_complex': types.Schema( + type='ARRAY', + items=types.Schema( + type='OBJECT', + properties={ + 'a_simple': types.Schema(type='INTEGER'), + 'b_simple': types.Schema(type='STRING'), + }, + required=['a_simple', 'b_simple'], + ), + ), + }, + required=['a_complex', 'b_complex'], + ) + + actual_schema_mldev = types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + actual_schema_vertex = types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + + assert actual_schema_mldev == expected_schema_mldev + assert actual_schema_vertex == expected_schema_vertex + + +def test_function_with_return_type(): + def func_under_test1() -> set: + pass + + def func_under_test2() -> frozenset[int]: + pass + + def func_under_test3() -> typing.Set[int]: + pass + + def func_under_test4() -> typing.FrozenSet[int]: + pass + + def func_under_test5() -> typing.Iterable[int]: + pass + + def func_under_test6() -> bytes: + pass + + def func_under_test7() -> typing.OrderedDict[str, int]: + pass + + def func_under_test8() -> typing.MutableMapping[str, int]: + pass + + def func_under_test9() -> typing.MutableSequence[int]: + pass + + def func_under_test10() -> typing.MutableSet[int]: + pass + + def func_under_test11() -> typing.Counter[int]: + pass + + all_func_under_test = [ + func_under_test1, + func_under_test2, + func_under_test3, + func_under_test4, + func_under_test5, + func_under_test6, + func_under_test7, + func_under_test8, + func_under_test9, + func_under_test10, + func_under_test11, + ] + for i, func_under_test in enumerate(all_func_under_test): + + expected_schema_mldev = types.FunctionDeclaration( + name=f'func_under_test{i+1}', + description=None, + ) + actual_schema_mldev = types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + assert actual_schema_mldev == expected_schema_mldev + + types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + + +def test_function_with_tuple_return_type(): + def func_under_test() -> tuple[int, str, str]: + pass + + expected_schema_mldev = types.FunctionDeclaration( + name=f'func_under_test', + description=None, + ) + actual_schema_mldev = types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + + expected_schema_vertex = types.FunctionDeclaration( + name=f'func_under_test', + description=None, + response_json_schema={ + 'maxItems': 3, + 'minItems': 3, + 'prefixItems': [ + {'type': 'integer'}, + {'type': 'string'}, + {'type': 'string'}, + ], + 'type': 'array', + 'unevaluatedItems': False, + }, + ) + actual_schema_vertex = types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + assert actual_schema_mldev == expected_schema_mldev + assert actual_schema_vertex == expected_schema_vertex + + +def test_function_with_return_type_not_supported(): + def func_under_test1() -> typing.Collection[int]: + pass + + def func_under_test2() -> typing.Iterator[int]: + pass + + def func_under_test3() -> typing.Container[int]: + pass + + class MyClass: + a: int + b: str + + def func_under_test4() -> MyClass: + pass + + all_func_under_test = [ + func_under_test1, + func_under_test2, + func_under_test3, + func_under_test4, + ] + for i, func_under_test in enumerate(all_func_under_test): + + expected_schema_mldev = types.FunctionDeclaration( + name=f'func_under_test{i+1}', + description=None, + ) + actual_schema_mldev = types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + assert actual_schema_mldev == expected_schema_mldev + with pytest.raises(ValueError): + types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + +def test_function_with_tuple_contains_unevaluated_items(): + def func_under_test(a: tuple[int, int]) -> str: + """test return type.""" + return '' + + expected_parameters_json_schema = { + 'a': { + 'maxItems': 2, + 'minItems': 2, + 'prefixItems': [{'type': 'integer'}, {'type': 'integer'}], + 'type': 'array', + 'unevaluatedItems': False, + } + } + + actual_schema_mldev = types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + actual_schema_vertex = types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + + assert actual_schema_mldev.parameters_json_schema == expected_parameters_json_schema + assert actual_schema_vertex.parameters_json_schema == expected_parameters_json_schema + + +def test_function_gemini_api(monkeypatch): + api_key = 'google_api_key' + monkeypatch.setenv('GOOGLE_API_KEY', api_key) + + def func_under_test(a: int) -> str: + """test return type.""" + return '' + + expected_schema_mldev = types.FunctionDeclaration( + name='func_under_test', + parameters=types.Schema( + type='OBJECT', + properties={ + 'a': types.Schema(type='INTEGER'), + }, + required=['a'], + ), + description='test return type.', + ) + + actual_schema_mldev = types.FunctionDeclaration.from_callable( + client=mldev_client, callable=func_under_test + ) + + assert actual_schema_mldev == expected_schema_mldev + + +def test_function_with_option_gemini_api(monkeypatch): + + def func_under_test(a: int) -> str: + """test return type.""" + return '' + + expected_schema_mldev = types.FunctionDeclaration( + name='func_under_test', + parameters=types.Schema( + type='OBJECT', + properties={ + 'a': types.Schema(type='INTEGER'), + }, + required=['a'], + ), + description='test return type.', + ) + + actual_schema_mldev = types.FunctionDeclaration.from_callable_with_api_option( + callable=func_under_test, api_option='GEMINI_API' + ) + + assert actual_schema_mldev == expected_schema_mldev + + +def test_function_with_option_unset(monkeypatch): + + def func_under_test(a: int) -> str: + """test return type.""" + return '' + + expected_schema_mldev = types.FunctionDeclaration( + name='func_under_test', + parameters=types.Schema( + type='OBJECT', + properties={ + 'a': types.Schema(type='INTEGER'), + }, + required=['a'], + ), + description='test return type.', + ) + + actual_schema_mldev = types.FunctionDeclaration.from_callable_with_api_option( + callable=func_under_test + ) + + assert actual_schema_mldev == expected_schema_mldev + + +def test_function_with_option_unsupported_api_option(): + + def func_under_test(a: int) -> str: + """test return type.""" + return '' + + with pytest.raises(ValueError): + types.FunctionDeclaration.from_callable_with_api_option( + callable=func_under_test, api_option='UNSUPPORTED_API_OPTION' + ) + + +def test_function_vertex(): + + def func_under_test(a: int) -> str: + """test return type.""" + return '' + + expected_schema = types.FunctionDeclaration( + name='func_under_test', + parameters=types.Schema( + type='OBJECT', + properties={ + 'a': types.Schema(type='INTEGER'), + }, + ), + description='test return type.', + ) + expected_schema_vertex = copy.deepcopy(expected_schema) + expected_schema_vertex.response = types.Schema(type='STRING') + expected_schema_vertex.parameters.required = ['a'] + + actual_schema_vertex = types.FunctionDeclaration.from_callable( + client=vertex_client, callable=func_under_test + ) + + assert actual_schema_vertex == expected_schema_vertex + + +def test_function_with_option_vertex(monkeypatch): + + def func_under_test(a: int) -> str: + """test return type.""" + return '' + + expected_schema = types.FunctionDeclaration( + name='func_under_test', + parameters=types.Schema( + type='OBJECT', + properties={ + 'a': types.Schema(type='INTEGER'), + }, + ), + description='test return type.', + ) + expected_schema_vertex = copy.deepcopy(expected_schema) + expected_schema_vertex.response = types.Schema(type='STRING') + expected_schema_vertex.parameters.required = ['a'] + + actual_schema_vertex = ( + types.FunctionDeclaration.from_callable_with_api_option( + callable=func_under_test, api_option='VERTEX_AI' + ) + ) + + assert actual_schema_vertex == expected_schema_vertex + + +def test_convert_json_schema_with_cycle(): + json_schema_dict = { + 'type': 'object', + 'properties': { + 'foo': {'$ref': '#/$defs/Foo'} + }, + '$defs': { + 'Foo': { + 'type': 'object', + 'properties': { + 'foo': {'$ref': '#/$defs/Foo'} + } + } + } + } + + json_schema = types.JSONSchema(**json_schema_dict) + schema = types.Schema.from_json_schema(json_schema=json_schema) + + assert schema.type == types.Type.OBJECT + assert schema.properties['foo'].type == types.Type.OBJECT + assert schema.properties['foo'].properties['foo'] == types.Schema() + + +def test_case_insensitive_enum(): + assert types.Type('STRING') == types.Type.STRING + assert types.Type('string') == types.Type.STRING + + +def test_case_insensitive_enum_with_pydantic_model(): + class TestModel(pydantic.BaseModel): + test_enum: types.Type + + assert TestModel(test_enum='STRING').test_enum == types.Type.STRING + assert TestModel(test_enum='string').test_enum == types.Type.STRING + + +def test_unknown_enum_value(): + with pytest.warns(Warning, match='is not a valid'): + enum_instance = types.Type('float') + assert enum_instance.name == 'float' + assert enum_instance.value == 'float' + + +def test_unknown_enum_value_in_nested_dict(): + schema = types.SafetyRating._from_response( + response={'category': 'NEW_CATEGORY'}, kwargs=None + ) + assert schema.category.name == 'NEW_CATEGORY' + assert schema.category.value == 'NEW_CATEGORY' + + +# Tests that TypedDict types from types.py are compatible with pydantic +# pydantic requires TypedDict from typing_extensions for Python <3.12 +def test_typed_dict_pydantic_field(): + from pydantic import BaseModel + + class MyConfig(BaseModel): + config: types.GenerationConfigDict + + +def test_model_content_list_part_from_uri(): + expected_model_content = types.Content( + role='model', + parts=[ + types.Part(text='what is this image about?'), + types.Part( + file_data=types.FileData( + file_uri='gs://generativeai-downloads/images/scones.jpg', + mime_type='image/jpeg', + ) + ), + ], + ) + + actual_model_content = types.ModelContent( + parts=[ + 'what is this image about?', + types.Part.from_uri( + file_uri='gs://generativeai-downloads/images/scones.jpg', + mime_type='image/jpeg', + ), + ] + ) + + assert expected_model_content.model_dump_json( + exclude_none=True + ) == actual_model_content.model_dump_json(exclude_none=True) + + +def test_model_content_part_from_uri(): + expected_model_content = types.Content( + role='model', + parts=[ + types.Part( + file_data=types.FileData( + file_uri='gs://generativeai-downloads/images/scones.jpg', + mime_type='image/jpeg', + ) + ) + ], + ) + + actual_model_content = types.ModelContent( + parts=types.Part.from_uri( + file_uri='gs://generativeai-downloads/images/scones.jpg', + mime_type='image/jpeg', + ) + ) + + assert expected_model_content.model_dump_json( + exclude_none=True + ) == actual_model_content.model_dump_json(exclude_none=True) + + +def test_model_content_from_string(): + expected_model_content = types.Content( + role='model', + parts=[types.Part(text='why is the sky blue?')], + ) + + actual_model_content = types.ModelContent('why is the sky blue?') + + assert expected_model_content.model_dump_json( + exclude_none=True + ) == actual_model_content.model_dump_json(exclude_none=True) + + +def test_model_content_unsupported_type(): + with pytest.raises(ValueError): + types.ModelContent(123) + + +def test_model_content_empty_list(): + with pytest.raises(ValueError): + types.ModelContent([]) + + +def test_model_content_unsupported_type_in_list(): + with pytest.raises(ValueError): + types.ModelContent(['hi', 123]) + + +def test_model_content_unsupported_role(): + with pytest.raises(TypeError): + types.ModelContent(role='user', parts=['hi']) + + +def test_model_content_modify_role(): + model_content = types.ModelContent(['hi']) + with pytest.raises(pydantic.ValidationError): + model_content.role = 'user' + + +def test_model_content_modify_parts(): + expected_model_content = types.Content( + role='model', + parts=[types.Part(text='hello')], + ) + model_content = types.ModelContent(['hi']) + model_content.parts = [types.Part(text='hello')] + + assert expected_model_content.model_dump_json( + exclude_none=True + ) == model_content.model_dump_json(exclude_none=True) + + +def test_user_content_unsupported_type(): + with pytest.raises(ValueError): + types.UserContent(123) + + +def test_user_content_modify_role(): + user_content = types.UserContent(['hi']) + with pytest.raises(pydantic.ValidationError): + user_content.role = 'model' + + +def test_user_content_modify_parts(): + expected_user_content = types.Content( + role='user', + parts=[types.Part(text='hello')], + ) + user_content = types.UserContent(['hi']) + user_content.parts = [types.Part(text='hello')] + + assert expected_user_content.model_dump_json( + exclude_none=True + ) == user_content.model_dump_json(exclude_none=True) + + +def test_user_content_empty_list(): + with pytest.raises(ValueError): + types.UserContent([]) + + +def test_user_content_unsupported_type_in_list(): + with pytest.raises(ValueError): + types.UserContent(['hi', 123]) + + +def test_user_content_unsupported_role(): + with pytest.raises(TypeError): + types.UserContent(role='model', parts=['hi']) + + +def test_instantiate_response_from_batch_json(): + test_batch_json = json.dumps({ + 'candidates': [{ + 'citationMetadata': { + 'citationSources': [{ + 'endIndex': 2009, + 'startIndex': 1880, + 'uri': 'http://someurl.com', + }] + }, + 'content': { + 'parts': [{ + 'text': ( + 'This recipe makes a moist and delicious banana bread!' + ) + }], + 'role': 'model', + }, + 'finishReason': 'STOP', + }], + 'modelVersion': 'gemini-1.5-flash-002@default', + }) + parsed = types.GenerateContentResponse.model_validate_json(test_batch_json) + assert isinstance(parsed, types.GenerateContentResponse) + assert isinstance(parsed.candidates[0].citation_metadata, types.CitationMetadata) + assert isinstance( + parsed.candidates[0].citation_metadata.citations[0], types.Citation + ) + assert( + parsed.candidates[0].citation_metadata.citations[0].uri + == 'http://someurl.com' + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tokens.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tokens.py new file mode 100644 index 0000000000000000000000000000000000000000..259fa2e3b5bf03dd16eaa77f2d42ee61d0b329f7 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tokens.py @@ -0,0 +1,362 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +"""[Experimental] Auth Tokens API client.""" + +import json +import logging +from typing import Any, Dict, List, Optional +from urllib.parse import urlencode +from . import _api_module +from . import _common +from . import _tokens_converters as tokens_converters +from . import types + +logger = logging.getLogger('google_genai.tokens') + + +def _get_field_masks(setup: _common.StringDict) -> str: + """Return field_masks""" + fields = [] + for k, v in setup.items(): + # 2nd layer, recursively get field masks see TODO(b/418290100) + if isinstance(v, dict) and v: + field = [f'{k}.{kk}' for kk in v.keys()] + else: + field = [k] # 1st layer + fields.extend(field) + + return ','.join(fields) + + +def _convert_bidi_setup_to_token_setup( + request_dict: _common.StringDict, + config: Optional[types.CreateAuthTokenConfigOrDict] = None, +) -> _common.StringDict: + """Converts bidiGenerateContentSetup.""" + bidi_setup = request_dict.get('bidiGenerateContentSetup') + if bidi_setup and bidi_setup.get('setup'): + # Handling mismatch between AuthToken service and + # BidiGenerateContent service + request_dict['bidiGenerateContentSetup'] = bidi_setup.get('setup') + + # Convert non null bidiGenerateContentSetup to field_mask + field_mask = _get_field_masks(request_dict['bidiGenerateContentSetup']) + + if ( + isinstance(config, dict) + and config.get('lock_additional_fields') is not None + and not config.get('lock_additional_fields') + ) or ( + isinstance(config, types.CreateAuthTokenConfig) + and config.lock_additional_fields is not None + and not config.lock_additional_fields # pylint: disable=literal-comparison + ): + # Empty list, lock non null fields + request_dict['fieldMask'] = field_mask + elif ( + isinstance(config, dict) + and config.get('lock_additional_fields') is None + ) or ( + isinstance(config, types.CreateAuthTokenConfig) + and config.lock_additional_fields is None + ): + # None. Global lock. unset fieldMask + request_dict.pop('fieldMask', None) + elif request_dict['fieldMask']: + # Lock non null + additional fields + additional_fields_list: Optional[List[str]] = request_dict.get( + 'fieldMask' + ) + generation_config_list = types.GenerationConfig().model_dump().keys() + if additional_fields_list: + field_mask_list = [] + for field in additional_fields_list: + if field in generation_config_list: + field = f'generationConfig.{field}' + field_mask_list.append(field) + else: + field_mask_list = [] + request_dict['fieldMask'] = ( + field_mask + ',' + ','.join(field_mask_list) + if field_mask_list + else field_mask + ) + else: + # Lock all fields + request_dict.pop('fieldMask', None) + else: + field_mask = request_dict.get('fieldMask', []) + field_mask_str = ','.join(field_mask) + if field_mask: + request_dict['fieldMask'] = field_mask_str + else: + request_dict.pop('fieldMask', None) + if not request_dict.get('bidiGenerateContentSetup'): + request_dict.pop('bidiGenerateContentSetup', None) + + return request_dict + + +class Tokens(_api_module.BaseModule): + """[Experimental] Auth Tokens API client. + + This class provides methods for creating auth tokens. + """ + + @_common.experimental_warning( + "The SDK's token creation implementation is experimental, " + 'and may change in future versions.', + ) + def create( + self, *, config: Optional[types.CreateAuthTokenConfigOrDict] = None + ) -> types.AuthToken: + """[Experimental] Creates an auth token. + + Args: + config (CreateAuthTokenConfig): Optional configuration for the request. + + The CreateAuthTokenConfig's `live_constrained_parameters` attrubite + Can be used to lock the parameters of the live session so they + can't be changed client side. This behavior has two basic modes depending on + whether `lock_additional_fields` is set: + + If you do not pass `lock_additional_fields` the entire + `live_constrained_parameters` is locked and can't be changed + by the token's user. + + If you set `lock_additional_fields`, then the non-null fields of + `live_constrained_parameters` are locked, and any additional fields + specified in `lock_additional_fields`. + + Usage: + + .. code-block:: python + + # Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig + # when using the token in Live API sessions. Each session connection can + # use a different configuration. + + config = types.CreateAuthTokenConfig( + uses=10, + expire_time='2025-05-01T00:00:00Z', + ) + auth_token = client.tokens.create(config=config) + + .. code-block:: python + + # Case 2: If LiveEphemeralParameters is set, lock all fields in + # LiveConnectConfig when using the token in Live API sessions. For + # example, changing `output_audio_transcription` in the Live API + # connection will be ignored by the API. + + auth_token = client.tokens.create( + config=types.CreateAuthTokenConfig( + uses=10, + live_constrained_parameters=types.LiveEphemeralParameters( + model='gemini-live-2.5-flash-preview', + config=types.LiveConnectConfig( + system_instruction='You are an LLM called Gemini.' + ), + ), + ) + ) + + .. code-block:: python + + # Case 3: If LiveEphemeralParameters is set and lockAdditionalFields is + # empty, lock LiveConnectConfig with set fields (e.g. + # system_instruction in this example) when using the token in Live API + # sessions. + auth_token = client.tokens.create( + config=types.CreateAuthTokenConfig( + uses=10, + live_constrained_parameters=types.LiveEphemeralParameters( + config=types.LiveConnectConfig( + system_instruction='You are an LLM called Gemini.' + ), + ), + lock_additional_fields=[], + ) + ) + + .. code-block:: python + + # Case 4: If LiveEphemeralParameters is set and lockAdditionalFields is + # set, lock LiveConnectConfig with set and additional fields (e.g. + # system_instruction, temperature in this example) when using the token + # in Live API sessions. + auth_token = client.tokens.create( + config=types.CreateAuthTokenConfig( + uses=10, + live_constrained_parameters=types.LiveEphemeralParameters( + model='gemini-live-2.5-flash-preview', + config=types.LiveConnectConfig( + system_instruction='You are an LLM called Gemini.' + ), + ), + lock_additional_fields=['temperature'], + ) + ) + """ + + parameter_model = types.CreateAuthTokenParameters( + config=config, + ) + request_url_dict: Optional[dict[str, str]] + if self._api_client.vertexai: + raise ValueError( + 'This method is only supported in the Gemini Developer client.' + ) + else: + request_dict = tokens_converters._CreateAuthTokenParameters_to_mldev( + self._api_client, + parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'auth_tokens'.format_map(request_url_dict) + else: + path = 'auth_tokens' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + + request_dict.pop('config', None) + + # Token creation request data need to replace 'setup' with + # 'bidiGenerateContentSetup' + if request_dict: + request_dict = _convert_bidi_setup_to_token_setup(request_dict, config) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model is not None + and parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request( + 'post', path, request_dict, http_options + ) + response_dict = {} if not response.body else json.loads(response.body) + + return_value = types.AuthToken._from_response( + response=response_dict, kwargs=parameter_model.model_dump() + ) + self._api_client._verify_response(return_value) + return return_value + + +class AsyncTokens(_api_module.BaseModule): + """[Experimental] Async Auth Tokens API client. + + This class provides asynchronous methods for creating auth tokens. + """ + + @_common.experimental_warning( + "The SDK's token creation implementation is experimental, " + 'and may change in future versions.', + ) + async def create( + self, *, config: Optional[types.CreateAuthTokenConfigOrDict] = None + ) -> types.AuthToken: + """Creates an auth token asynchronously. Support in v1alpha only. + + Args: + config (CreateAuthTokenConfig): Optional configuration for the request. + + Usage: + + .. code-block:: python + + client = genai.Client( + api_key=API_KEY, + http_options=types.HttpOptions(api_version='v1alpha'), + ) + + auth_token = await client.aio.tokens.create( + config=types.CreateAuthTokenConfig( + uses=10, + live_constrained_parameters=types.LiveEphemeralParameters( + model='gemini-live-2.5-flash-preview', + config=types.LiveConnectConfig( + system_instruction='You are an LLM called Gemini.' + ), + ), + ) + ) + """ + + parameter_model = types.CreateAuthTokenParameters( + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if self._api_client.vertexai: + raise ValueError( + 'This method is only supported in the Gemini Developer client.' + ) + else: + request_dict = tokens_converters._CreateAuthTokenParameters_to_mldev( + self._api_client, + parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'auth_tokens'.format_map(request_url_dict) + else: + path = 'auth_tokens' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + # Token creation request data need to replace 'setup' with + # 'bidiGenerateContentSetup' + request_dict = _convert_bidi_setup_to_token_setup(request_dict, config) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model is not None + and parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'post', + path, + request_dict, + http_options=http_options, + ) + response_dict = {} if not response.body else json.loads(response.body) + + return_value = types.AuthToken._from_response( + response=response_dict, kwargs=parameter_model.model_dump() + ) + self._api_client._verify_response(return_value) + return return_value diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tunings.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tunings.py new file mode 100644 index 0000000000000000000000000000000000000000..9b53b49b86fdc00c3407a8fc727e2b425485f526 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/tunings.py @@ -0,0 +1,2875 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# Code generated by the Google Gen AI SDK generator DO NOT EDIT. + +import json +import logging +from typing import Any, Optional, Union +from urllib.parse import urlencode + +from . import _api_module +from . import _common +from . import _transformers as t +from . import types +from ._common import get_value_by_path as getv +from ._common import set_value_by_path as setv +from .pagers import AsyncPager, Pager + +logger = logging.getLogger('google_genai.tunings') + + +def _AutoraterConfig_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['samplingCount']) is not None: + setv(to_object, ['sampling_count'], getv(from_object, ['samplingCount'])) + + if getv(from_object, ['flipEnabled']) is not None: + setv(to_object, ['flip_enabled'], getv(from_object, ['flipEnabled'])) + + if getv(from_object, ['autoraterModel']) is not None: + setv(to_object, ['autorater_model'], getv(from_object, ['autoraterModel'])) + + if getv(from_object, ['generationConfig']) is not None: + setv( + to_object, + ['generation_config'], + _GenerationConfig_from_vertex( + getv(from_object, ['generationConfig']), to_object, root_object + ), + ) + + return to_object + + +def _AutoraterConfig_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['sampling_count']) is not None: + setv(to_object, ['samplingCount'], getv(from_object, ['sampling_count'])) + + if getv(from_object, ['flip_enabled']) is not None: + setv(to_object, ['flipEnabled'], getv(from_object, ['flip_enabled'])) + + if getv(from_object, ['autorater_model']) is not None: + setv(to_object, ['autoraterModel'], getv(from_object, ['autorater_model'])) + + if getv(from_object, ['generation_config']) is not None: + setv( + to_object, + ['generationConfig'], + _GenerationConfig_to_vertex( + getv(from_object, ['generation_config']), to_object, root_object + ), + ) + + return to_object + + +def _CancelTuningJobParameters_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['name']) is not None: + setv(to_object, ['_url', 'name'], getv(from_object, ['name'])) + + return to_object + + +def _CancelTuningJobParameters_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['name']) is not None: + setv(to_object, ['_url', 'name'], getv(from_object, ['name'])) + + return to_object + + +def _CancelTuningJobResponse_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['sdkHttpResponse']) is not None: + setv( + to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse']) + ) + + return to_object + + +def _CancelTuningJobResponse_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['sdkHttpResponse']) is not None: + setv( + to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse']) + ) + + return to_object + + +def _CreateTuningJobConfig_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['validation_dataset']) is not None: + raise ValueError( + 'validation_dataset parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['tuned_model_display_name']) is not None: + setv( + parent_object, + ['displayName'], + getv(from_object, ['tuned_model_display_name']), + ) + + if getv(from_object, ['description']) is not None: + raise ValueError('description parameter is not supported in Gemini API.') + + if getv(from_object, ['epoch_count']) is not None: + setv( + parent_object, + ['tuningTask', 'hyperparameters', 'epochCount'], + getv(from_object, ['epoch_count']), + ) + + if getv(from_object, ['learning_rate_multiplier']) is not None: + setv( + to_object, + ['tuningTask', 'hyperparameters', 'learningRateMultiplier'], + getv(from_object, ['learning_rate_multiplier']), + ) + + if getv(from_object, ['export_last_checkpoint_only']) is not None: + raise ValueError( + 'export_last_checkpoint_only parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['pre_tuned_model_checkpoint_id']) is not None: + raise ValueError( + 'pre_tuned_model_checkpoint_id parameter is not supported in Gemini' + ' API.' + ) + + if getv(from_object, ['adapter_size']) is not None: + raise ValueError('adapter_size parameter is not supported in Gemini API.') + + if getv(from_object, ['tuning_mode']) is not None: + raise ValueError('tuning_mode parameter is not supported in Gemini API.') + + if getv(from_object, ['custom_base_model']) is not None: + raise ValueError( + 'custom_base_model parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['batch_size']) is not None: + setv( + parent_object, + ['tuningTask', 'hyperparameters', 'batchSize'], + getv(from_object, ['batch_size']), + ) + + if getv(from_object, ['learning_rate']) is not None: + setv( + parent_object, + ['tuningTask', 'hyperparameters', 'learningRate'], + getv(from_object, ['learning_rate']), + ) + + if getv(from_object, ['evaluation_config']) is not None: + raise ValueError( + 'evaluation_config parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['labels']) is not None: + raise ValueError('labels parameter is not supported in Gemini API.') + + if getv(from_object, ['beta']) is not None: + raise ValueError('beta parameter is not supported in Gemini API.') + + if getv(from_object, ['base_teacher_model']) is not None: + raise ValueError( + 'base_teacher_model parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['tuned_teacher_model_source']) is not None: + raise ValueError( + 'tuned_teacher_model_source parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['sft_loss_weight_multiplier']) is not None: + raise ValueError( + 'sft_loss_weight_multiplier parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['output_uri']) is not None: + raise ValueError('output_uri parameter is not supported in Gemini API.') + + if getv(from_object, ['encryption_spec']) is not None: + raise ValueError( + 'encryption_spec parameter is not supported in Gemini API.' + ) + + return to_object + + +def _CreateTuningJobConfig_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + discriminator = getv(root_object, ['config', 'method']) + if discriminator is None: + discriminator = 'SUPERVISED_FINE_TUNING' + if discriminator == 'SUPERVISED_FINE_TUNING': + if getv(from_object, ['validation_dataset']) is not None: + setv( + parent_object, + ['supervisedTuningSpec'], + _TuningValidationDataset_to_vertex( + getv(from_object, ['validation_dataset']), to_object, root_object + ), + ) + elif discriminator == 'PREFERENCE_TUNING': + if getv(from_object, ['validation_dataset']) is not None: + setv( + parent_object, + ['preferenceOptimizationSpec'], + _TuningValidationDataset_to_vertex( + getv(from_object, ['validation_dataset']), to_object, root_object + ), + ) + elif discriminator == 'DISTILLATION': + if getv(from_object, ['validation_dataset']) is not None: + setv( + parent_object, + ['distillationSpec'], + _TuningValidationDataset_to_vertex( + getv(from_object, ['validation_dataset']), to_object, root_object + ), + ) + + if getv(from_object, ['tuned_model_display_name']) is not None: + setv( + parent_object, + ['tunedModelDisplayName'], + getv(from_object, ['tuned_model_display_name']), + ) + + if getv(from_object, ['description']) is not None: + setv(parent_object, ['description'], getv(from_object, ['description'])) + + discriminator = getv(root_object, ['config', 'method']) + if discriminator is None: + discriminator = 'SUPERVISED_FINE_TUNING' + if discriminator == 'SUPERVISED_FINE_TUNING': + if getv(from_object, ['epoch_count']) is not None: + setv( + parent_object, + ['supervisedTuningSpec', 'hyperParameters', 'epochCount'], + getv(from_object, ['epoch_count']), + ) + elif discriminator == 'PREFERENCE_TUNING': + if getv(from_object, ['epoch_count']) is not None: + setv( + parent_object, + ['preferenceOptimizationSpec', 'hyperParameters', 'epochCount'], + getv(from_object, ['epoch_count']), + ) + elif discriminator == 'DISTILLATION': + if getv(from_object, ['epoch_count']) is not None: + setv( + parent_object, + ['distillationSpec', 'hyperParameters', 'epochCount'], + getv(from_object, ['epoch_count']), + ) + + discriminator = getv(root_object, ['config', 'method']) + if discriminator is None: + discriminator = 'SUPERVISED_FINE_TUNING' + if discriminator == 'SUPERVISED_FINE_TUNING': + if getv(from_object, ['learning_rate_multiplier']) is not None: + setv( + parent_object, + ['supervisedTuningSpec', 'hyperParameters', 'learningRateMultiplier'], + getv(from_object, ['learning_rate_multiplier']), + ) + elif discriminator == 'PREFERENCE_TUNING': + if getv(from_object, ['learning_rate_multiplier']) is not None: + setv( + parent_object, + [ + 'preferenceOptimizationSpec', + 'hyperParameters', + 'learningRateMultiplier', + ], + getv(from_object, ['learning_rate_multiplier']), + ) + elif discriminator == 'DISTILLATION': + if getv(from_object, ['learning_rate_multiplier']) is not None: + setv( + parent_object, + ['distillationSpec', 'hyperParameters', 'learningRateMultiplier'], + getv(from_object, ['learning_rate_multiplier']), + ) + + discriminator = getv(root_object, ['config', 'method']) + if discriminator is None: + discriminator = 'SUPERVISED_FINE_TUNING' + if discriminator == 'SUPERVISED_FINE_TUNING': + if getv(from_object, ['export_last_checkpoint_only']) is not None: + setv( + parent_object, + ['supervisedTuningSpec', 'exportLastCheckpointOnly'], + getv(from_object, ['export_last_checkpoint_only']), + ) + elif discriminator == 'PREFERENCE_TUNING': + if getv(from_object, ['export_last_checkpoint_only']) is not None: + setv( + parent_object, + ['preferenceOptimizationSpec', 'exportLastCheckpointOnly'], + getv(from_object, ['export_last_checkpoint_only']), + ) + elif discriminator == 'DISTILLATION': + if getv(from_object, ['export_last_checkpoint_only']) is not None: + setv( + parent_object, + ['distillationSpec', 'exportLastCheckpointOnly'], + getv(from_object, ['export_last_checkpoint_only']), + ) + + discriminator = getv(root_object, ['config', 'method']) + if discriminator is None: + discriminator = 'SUPERVISED_FINE_TUNING' + if discriminator == 'SUPERVISED_FINE_TUNING': + if getv(from_object, ['adapter_size']) is not None: + setv( + parent_object, + ['supervisedTuningSpec', 'hyperParameters', 'adapterSize'], + getv(from_object, ['adapter_size']), + ) + elif discriminator == 'PREFERENCE_TUNING': + if getv(from_object, ['adapter_size']) is not None: + setv( + parent_object, + ['preferenceOptimizationSpec', 'hyperParameters', 'adapterSize'], + getv(from_object, ['adapter_size']), + ) + elif discriminator == 'DISTILLATION': + if getv(from_object, ['adapter_size']) is not None: + setv( + parent_object, + ['distillationSpec', 'hyperParameters', 'adapterSize'], + getv(from_object, ['adapter_size']), + ) + + discriminator = getv(root_object, ['config', 'method']) + if discriminator is None: + discriminator = 'SUPERVISED_FINE_TUNING' + if discriminator == 'SUPERVISED_FINE_TUNING': + if getv(from_object, ['tuning_mode']) is not None: + setv( + parent_object, + ['supervisedTuningSpec', 'tuningMode'], + getv(from_object, ['tuning_mode']), + ) + elif discriminator == 'DISTILLATION': + if getv(from_object, ['tuning_mode']) is not None: + setv( + parent_object, + ['distillationSpec', 'tuningMode'], + getv(from_object, ['tuning_mode']), + ) + + if getv(from_object, ['custom_base_model']) is not None: + setv( + parent_object, + ['customBaseModel'], + getv(from_object, ['custom_base_model']), + ) + + discriminator = getv(root_object, ['config', 'method']) + if discriminator is None: + discriminator = 'SUPERVISED_FINE_TUNING' + if discriminator == 'SUPERVISED_FINE_TUNING': + if getv(from_object, ['batch_size']) is not None: + setv( + parent_object, + ['supervisedTuningSpec', 'hyperParameters', 'batchSize'], + getv(from_object, ['batch_size']), + ) + elif discriminator == 'DISTILLATION': + if getv(from_object, ['batch_size']) is not None: + setv( + parent_object, + ['distillationSpec', 'hyperParameters', 'batchSize'], + getv(from_object, ['batch_size']), + ) + + discriminator = getv(root_object, ['config', 'method']) + if discriminator is None: + discriminator = 'SUPERVISED_FINE_TUNING' + if discriminator == 'SUPERVISED_FINE_TUNING': + if getv(from_object, ['learning_rate']) is not None: + setv( + parent_object, + ['supervisedTuningSpec', 'hyperParameters', 'learningRate'], + getv(from_object, ['learning_rate']), + ) + elif discriminator == 'DISTILLATION': + if getv(from_object, ['learning_rate']) is not None: + setv( + parent_object, + ['distillationSpec', 'hyperParameters', 'learningRate'], + getv(from_object, ['learning_rate']), + ) + + discriminator = getv(root_object, ['config', 'method']) + if discriminator is None: + discriminator = 'SUPERVISED_FINE_TUNING' + if discriminator == 'SUPERVISED_FINE_TUNING': + if getv(from_object, ['evaluation_config']) is not None: + setv( + parent_object, + ['supervisedTuningSpec', 'evaluationConfig'], + _EvaluationConfig_to_vertex( + getv(from_object, ['evaluation_config']), to_object, root_object + ), + ) + elif discriminator == 'PREFERENCE_TUNING': + if getv(from_object, ['evaluation_config']) is not None: + setv( + parent_object, + ['preferenceOptimizationSpec', 'evaluationConfig'], + _EvaluationConfig_to_vertex( + getv(from_object, ['evaluation_config']), to_object, root_object + ), + ) + elif discriminator == 'DISTILLATION': + if getv(from_object, ['evaluation_config']) is not None: + setv( + parent_object, + ['distillationSpec', 'evaluationConfig'], + _EvaluationConfig_to_vertex( + getv(from_object, ['evaluation_config']), to_object, root_object + ), + ) + + if getv(from_object, ['labels']) is not None: + setv(parent_object, ['labels'], getv(from_object, ['labels'])) + + if getv(from_object, ['beta']) is not None: + setv( + parent_object, + ['preferenceOptimizationSpec', 'hyperParameters', 'beta'], + getv(from_object, ['beta']), + ) + + if getv(from_object, ['base_teacher_model']) is not None: + setv( + parent_object, + ['distillationSpec', 'baseTeacherModel'], + getv(from_object, ['base_teacher_model']), + ) + + if getv(from_object, ['tuned_teacher_model_source']) is not None: + setv( + parent_object, + ['distillationSpec', 'tunedTeacherModelSource'], + getv(from_object, ['tuned_teacher_model_source']), + ) + + if getv(from_object, ['sft_loss_weight_multiplier']) is not None: + setv( + parent_object, + ['distillationSpec', 'hyperParameters', 'sftLossWeightMultiplier'], + getv(from_object, ['sft_loss_weight_multiplier']), + ) + + if getv(from_object, ['output_uri']) is not None: + setv(parent_object, ['outputUri'], getv(from_object, ['output_uri'])) + + if getv(from_object, ['encryption_spec']) is not None: + setv( + parent_object, + ['encryptionSpec'], + getv(from_object, ['encryption_spec']), + ) + + return to_object + + +def _CreateTuningJobParametersPrivate_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['base_model']) is not None: + setv(to_object, ['baseModel'], getv(from_object, ['base_model'])) + + if getv(from_object, ['pre_tuned_model']) is not None: + setv(to_object, ['preTunedModel'], getv(from_object, ['pre_tuned_model'])) + + if getv(from_object, ['training_dataset']) is not None: + _TuningDataset_to_mldev( + getv(from_object, ['training_dataset']), to_object, root_object + ) + + if getv(from_object, ['config']) is not None: + _CreateTuningJobConfig_to_mldev( + getv(from_object, ['config']), to_object, root_object + ) + + return to_object + + +def _CreateTuningJobParametersPrivate_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['base_model']) is not None: + setv(to_object, ['baseModel'], getv(from_object, ['base_model'])) + + if getv(from_object, ['pre_tuned_model']) is not None: + setv(to_object, ['preTunedModel'], getv(from_object, ['pre_tuned_model'])) + + if getv(from_object, ['training_dataset']) is not None: + _TuningDataset_to_vertex( + getv(from_object, ['training_dataset']), to_object, root_object + ) + + if getv(from_object, ['config']) is not None: + _CreateTuningJobConfig_to_vertex( + getv(from_object, ['config']), to_object, root_object + ) + + return to_object + + +def _EvaluationConfig_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['metrics']) is not None: + setv(to_object, ['metrics'], t.t_metrics(getv(from_object, ['metrics']))) + + if getv(from_object, ['outputConfig']) is not None: + setv(to_object, ['output_config'], getv(from_object, ['outputConfig'])) + + if getv(from_object, ['autoraterConfig']) is not None: + setv( + to_object, + ['autorater_config'], + _AutoraterConfig_from_vertex( + getv(from_object, ['autoraterConfig']), to_object, root_object + ), + ) + + if getv(from_object, ['inferenceGenerationConfig']) is not None: + setv( + to_object, + ['inference_generation_config'], + _GenerationConfig_from_vertex( + getv(from_object, ['inferenceGenerationConfig']), + to_object, + root_object, + ), + ) + + return to_object + + +def _EvaluationConfig_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['metrics']) is not None: + setv(to_object, ['metrics'], t.t_metrics(getv(from_object, ['metrics']))) + + if getv(from_object, ['output_config']) is not None: + setv(to_object, ['outputConfig'], getv(from_object, ['output_config'])) + + if getv(from_object, ['autorater_config']) is not None: + setv( + to_object, + ['autoraterConfig'], + _AutoraterConfig_to_vertex( + getv(from_object, ['autorater_config']), to_object, root_object + ), + ) + + if getv(from_object, ['inference_generation_config']) is not None: + setv( + to_object, + ['inferenceGenerationConfig'], + _GenerationConfig_to_vertex( + getv(from_object, ['inference_generation_config']), + to_object, + root_object, + ), + ) + + return to_object + + +def _GenerationConfig_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['modelConfig']) is not None: + setv( + to_object, + ['model_selection_config'], + getv(from_object, ['modelConfig']), + ) + + if getv(from_object, ['responseJsonSchema']) is not None: + setv( + to_object, + ['response_json_schema'], + getv(from_object, ['responseJsonSchema']), + ) + + if getv(from_object, ['audioTimestamp']) is not None: + setv(to_object, ['audio_timestamp'], getv(from_object, ['audioTimestamp'])) + + if getv(from_object, ['candidateCount']) is not None: + setv(to_object, ['candidate_count'], getv(from_object, ['candidateCount'])) + + if getv(from_object, ['enableAffectiveDialog']) is not None: + setv( + to_object, + ['enable_affective_dialog'], + getv(from_object, ['enableAffectiveDialog']), + ) + + if getv(from_object, ['frequencyPenalty']) is not None: + setv( + to_object, + ['frequency_penalty'], + getv(from_object, ['frequencyPenalty']), + ) + + if getv(from_object, ['logprobs']) is not None: + setv(to_object, ['logprobs'], getv(from_object, ['logprobs'])) + + if getv(from_object, ['maxOutputTokens']) is not None: + setv( + to_object, ['max_output_tokens'], getv(from_object, ['maxOutputTokens']) + ) + + if getv(from_object, ['mediaResolution']) is not None: + setv( + to_object, ['media_resolution'], getv(from_object, ['mediaResolution']) + ) + + if getv(from_object, ['presencePenalty']) is not None: + setv( + to_object, ['presence_penalty'], getv(from_object, ['presencePenalty']) + ) + + if getv(from_object, ['responseLogprobs']) is not None: + setv( + to_object, + ['response_logprobs'], + getv(from_object, ['responseLogprobs']), + ) + + if getv(from_object, ['responseMimeType']) is not None: + setv( + to_object, + ['response_mime_type'], + getv(from_object, ['responseMimeType']), + ) + + if getv(from_object, ['responseModalities']) is not None: + setv( + to_object, + ['response_modalities'], + getv(from_object, ['responseModalities']), + ) + + if getv(from_object, ['responseSchema']) is not None: + setv(to_object, ['response_schema'], getv(from_object, ['responseSchema'])) + + if getv(from_object, ['routingConfig']) is not None: + setv(to_object, ['routing_config'], getv(from_object, ['routingConfig'])) + + if getv(from_object, ['seed']) is not None: + setv(to_object, ['seed'], getv(from_object, ['seed'])) + + if getv(from_object, ['speechConfig']) is not None: + setv(to_object, ['speech_config'], getv(from_object, ['speechConfig'])) + + if getv(from_object, ['stopSequences']) is not None: + setv(to_object, ['stop_sequences'], getv(from_object, ['stopSequences'])) + + if getv(from_object, ['temperature']) is not None: + setv(to_object, ['temperature'], getv(from_object, ['temperature'])) + + if getv(from_object, ['thinkingConfig']) is not None: + setv(to_object, ['thinking_config'], getv(from_object, ['thinkingConfig'])) + + if getv(from_object, ['topK']) is not None: + setv(to_object, ['top_k'], getv(from_object, ['topK'])) + + if getv(from_object, ['topP']) is not None: + setv(to_object, ['top_p'], getv(from_object, ['topP'])) + + return to_object + + +def _GenerationConfig_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['model_selection_config']) is not None: + setv( + to_object, + ['modelConfig'], + getv(from_object, ['model_selection_config']), + ) + + if getv(from_object, ['response_json_schema']) is not None: + setv( + to_object, + ['responseJsonSchema'], + getv(from_object, ['response_json_schema']), + ) + + if getv(from_object, ['audio_timestamp']) is not None: + setv(to_object, ['audioTimestamp'], getv(from_object, ['audio_timestamp'])) + + if getv(from_object, ['candidate_count']) is not None: + setv(to_object, ['candidateCount'], getv(from_object, ['candidate_count'])) + + if getv(from_object, ['enable_affective_dialog']) is not None: + setv( + to_object, + ['enableAffectiveDialog'], + getv(from_object, ['enable_affective_dialog']), + ) + + if getv(from_object, ['frequency_penalty']) is not None: + setv( + to_object, + ['frequencyPenalty'], + getv(from_object, ['frequency_penalty']), + ) + + if getv(from_object, ['logprobs']) is not None: + setv(to_object, ['logprobs'], getv(from_object, ['logprobs'])) + + if getv(from_object, ['max_output_tokens']) is not None: + setv( + to_object, ['maxOutputTokens'], getv(from_object, ['max_output_tokens']) + ) + + if getv(from_object, ['media_resolution']) is not None: + setv( + to_object, ['mediaResolution'], getv(from_object, ['media_resolution']) + ) + + if getv(from_object, ['presence_penalty']) is not None: + setv( + to_object, ['presencePenalty'], getv(from_object, ['presence_penalty']) + ) + + if getv(from_object, ['response_logprobs']) is not None: + setv( + to_object, + ['responseLogprobs'], + getv(from_object, ['response_logprobs']), + ) + + if getv(from_object, ['response_mime_type']) is not None: + setv( + to_object, + ['responseMimeType'], + getv(from_object, ['response_mime_type']), + ) + + if getv(from_object, ['response_modalities']) is not None: + setv( + to_object, + ['responseModalities'], + getv(from_object, ['response_modalities']), + ) + + if getv(from_object, ['response_schema']) is not None: + setv(to_object, ['responseSchema'], getv(from_object, ['response_schema'])) + + if getv(from_object, ['routing_config']) is not None: + setv(to_object, ['routingConfig'], getv(from_object, ['routing_config'])) + + if getv(from_object, ['seed']) is not None: + setv(to_object, ['seed'], getv(from_object, ['seed'])) + + if getv(from_object, ['speech_config']) is not None: + setv( + to_object, + ['speechConfig'], + _SpeechConfig_to_vertex( + getv(from_object, ['speech_config']), to_object, root_object + ), + ) + + if getv(from_object, ['stop_sequences']) is not None: + setv(to_object, ['stopSequences'], getv(from_object, ['stop_sequences'])) + + if getv(from_object, ['temperature']) is not None: + setv(to_object, ['temperature'], getv(from_object, ['temperature'])) + + if getv(from_object, ['thinking_config']) is not None: + setv(to_object, ['thinkingConfig'], getv(from_object, ['thinking_config'])) + + if getv(from_object, ['top_k']) is not None: + setv(to_object, ['topK'], getv(from_object, ['top_k'])) + + if getv(from_object, ['top_p']) is not None: + setv(to_object, ['topP'], getv(from_object, ['top_p'])) + + if getv(from_object, ['enable_enhanced_civic_answers']) is not None: + raise ValueError( + 'enable_enhanced_civic_answers parameter is not supported in Vertex AI.' + ) + + return to_object + + +def _GetTuningJobParameters_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['name']) is not None: + setv(to_object, ['_url', 'name'], getv(from_object, ['name'])) + + return to_object + + +def _GetTuningJobParameters_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['name']) is not None: + setv(to_object, ['_url', 'name'], getv(from_object, ['name'])) + + return to_object + + +def _ListTuningJobsConfig_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['page_size']) is not None: + setv( + parent_object, ['_query', 'pageSize'], getv(from_object, ['page_size']) + ) + + if getv(from_object, ['page_token']) is not None: + setv( + parent_object, + ['_query', 'pageToken'], + getv(from_object, ['page_token']), + ) + + if getv(from_object, ['filter']) is not None: + setv(parent_object, ['_query', 'filter'], getv(from_object, ['filter'])) + + return to_object + + +def _ListTuningJobsConfig_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ['page_size']) is not None: + setv( + parent_object, ['_query', 'pageSize'], getv(from_object, ['page_size']) + ) + + if getv(from_object, ['page_token']) is not None: + setv( + parent_object, + ['_query', 'pageToken'], + getv(from_object, ['page_token']), + ) + + if getv(from_object, ['filter']) is not None: + setv(parent_object, ['_query', 'filter'], getv(from_object, ['filter'])) + + return to_object + + +def _ListTuningJobsParameters_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['config']) is not None: + _ListTuningJobsConfig_to_mldev( + getv(from_object, ['config']), to_object, root_object + ) + + return to_object + + +def _ListTuningJobsParameters_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['config']) is not None: + _ListTuningJobsConfig_to_vertex( + getv(from_object, ['config']), to_object, root_object + ) + + return to_object + + +def _ListTuningJobsResponse_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['sdkHttpResponse']) is not None: + setv( + to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse']) + ) + + if getv(from_object, ['nextPageToken']) is not None: + setv(to_object, ['next_page_token'], getv(from_object, ['nextPageToken'])) + + if getv(from_object, ['tunedModels']) is not None: + setv( + to_object, + ['tuning_jobs'], + [ + _TuningJob_from_mldev(item, to_object, root_object) + for item in getv(from_object, ['tunedModels']) + ], + ) + + return to_object + + +def _ListTuningJobsResponse_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['sdkHttpResponse']) is not None: + setv( + to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse']) + ) + + if getv(from_object, ['nextPageToken']) is not None: + setv(to_object, ['next_page_token'], getv(from_object, ['nextPageToken'])) + + if getv(from_object, ['tuningJobs']) is not None: + setv( + to_object, + ['tuning_jobs'], + [ + _TuningJob_from_vertex(item, to_object, root_object) + for item in getv(from_object, ['tuningJobs']) + ], + ) + + return to_object + + +def _MultiSpeakerVoiceConfig_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['speaker_voice_configs']) is not None: + setv( + to_object, + ['speakerVoiceConfigs'], + [ + _SpeakerVoiceConfig_to_vertex(item, to_object, root_object) + for item in getv(from_object, ['speaker_voice_configs']) + ], + ) + + return to_object + + +def _ReplicatedVoiceConfig_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['mime_type']) is not None: + setv(to_object, ['mimeType'], getv(from_object, ['mime_type'])) + + if getv(from_object, ['voice_sample_audio']) is not None: + setv( + to_object, + ['voiceSampleAudio'], + getv(from_object, ['voice_sample_audio']), + ) + + if getv(from_object, ['consent_audio']) is not None: + raise ValueError('consent_audio parameter is not supported in Vertex AI.') + + if getv(from_object, ['voice_consent_signature']) is not None: + raise ValueError( + 'voice_consent_signature parameter is not supported in Vertex AI.' + ) + + return to_object + + +def _SpeakerVoiceConfig_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['speaker']) is not None: + setv(to_object, ['speaker'], getv(from_object, ['speaker'])) + + if getv(from_object, ['voice_config']) is not None: + setv( + to_object, + ['voiceConfig'], + _VoiceConfig_to_vertex( + getv(from_object, ['voice_config']), to_object, root_object + ), + ) + + return to_object + + +def _SpeechConfig_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['voice_config']) is not None: + setv( + to_object, + ['voiceConfig'], + _VoiceConfig_to_vertex( + getv(from_object, ['voice_config']), to_object, root_object + ), + ) + + if getv(from_object, ['language_code']) is not None: + setv(to_object, ['languageCode'], getv(from_object, ['language_code'])) + + if getv(from_object, ['multi_speaker_voice_config']) is not None: + setv( + to_object, + ['multiSpeakerVoiceConfig'], + _MultiSpeakerVoiceConfig_to_vertex( + getv(from_object, ['multi_speaker_voice_config']), + to_object, + root_object, + ), + ) + + return to_object + + +def _TunedModel_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['name']) is not None: + setv(to_object, ['model'], getv(from_object, ['name'])) + + if getv(from_object, ['name']) is not None: + setv(to_object, ['endpoint'], getv(from_object, ['name'])) + + return to_object + + +def _TuningDataset_to_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['gcs_uri']) is not None: + raise ValueError('gcs_uri parameter is not supported in Gemini API.') + + if getv(from_object, ['vertex_dataset_resource']) is not None: + raise ValueError( + 'vertex_dataset_resource parameter is not supported in Gemini API.' + ) + + if getv(from_object, ['examples']) is not None: + setv( + to_object, + ['examples', 'examples'], + [item for item in getv(from_object, ['examples'])], + ) + + return to_object + + +def _TuningDataset_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + discriminator = getv(root_object, ['config', 'method']) + if discriminator is None: + discriminator = 'SUPERVISED_FINE_TUNING' + if discriminator == 'SUPERVISED_FINE_TUNING': + if getv(from_object, ['gcs_uri']) is not None: + setv( + parent_object, + ['supervisedTuningSpec', 'trainingDatasetUri'], + getv(from_object, ['gcs_uri']), + ) + elif discriminator == 'PREFERENCE_TUNING': + if getv(from_object, ['gcs_uri']) is not None: + setv( + parent_object, + ['preferenceOptimizationSpec', 'trainingDatasetUri'], + getv(from_object, ['gcs_uri']), + ) + elif discriminator == 'DISTILLATION': + if getv(from_object, ['gcs_uri']) is not None: + setv( + parent_object, + ['distillationSpec', 'promptDatasetUri'], + getv(from_object, ['gcs_uri']), + ) + + discriminator = getv(root_object, ['config', 'method']) + if discriminator is None: + discriminator = 'SUPERVISED_FINE_TUNING' + if discriminator == 'SUPERVISED_FINE_TUNING': + if getv(from_object, ['vertex_dataset_resource']) is not None: + setv( + parent_object, + ['supervisedTuningSpec', 'trainingDatasetUri'], + getv(from_object, ['vertex_dataset_resource']), + ) + elif discriminator == 'PREFERENCE_TUNING': + if getv(from_object, ['vertex_dataset_resource']) is not None: + setv( + parent_object, + ['preferenceOptimizationSpec', 'trainingDatasetUri'], + getv(from_object, ['vertex_dataset_resource']), + ) + elif discriminator == 'DISTILLATION': + if getv(from_object, ['vertex_dataset_resource']) is not None: + setv( + parent_object, + ['distillationSpec', 'promptDatasetUri'], + getv(from_object, ['vertex_dataset_resource']), + ) + + if getv(from_object, ['examples']) is not None: + raise ValueError('examples parameter is not supported in Vertex AI.') + + return to_object + + +def _TuningJob_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['sdkHttpResponse']) is not None: + setv( + to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse']) + ) + + if getv(from_object, ['name']) is not None: + setv(to_object, ['name'], getv(from_object, ['name'])) + + if getv(from_object, ['state']) is not None: + setv( + to_object, + ['state'], + t.t_tuning_job_status(getv(from_object, ['state'])), + ) + + if getv(from_object, ['createTime']) is not None: + setv(to_object, ['create_time'], getv(from_object, ['createTime'])) + + if getv(from_object, ['tuningTask', 'startTime']) is not None: + setv( + to_object, + ['start_time'], + getv(from_object, ['tuningTask', 'startTime']), + ) + + if getv(from_object, ['tuningTask', 'completeTime']) is not None: + setv( + to_object, + ['end_time'], + getv(from_object, ['tuningTask', 'completeTime']), + ) + + if getv(from_object, ['updateTime']) is not None: + setv(to_object, ['update_time'], getv(from_object, ['updateTime'])) + + if getv(from_object, ['description']) is not None: + setv(to_object, ['description'], getv(from_object, ['description'])) + + if getv(from_object, ['baseModel']) is not None: + setv(to_object, ['base_model'], getv(from_object, ['baseModel'])) + + if getv(from_object, ['_self']) is not None: + setv( + to_object, + ['tuned_model'], + _TunedModel_from_mldev( + getv(from_object, ['_self']), to_object, root_object + ), + ) + + return to_object + + +def _TuningJob_from_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['sdkHttpResponse']) is not None: + setv( + to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse']) + ) + + if getv(from_object, ['name']) is not None: + setv(to_object, ['name'], getv(from_object, ['name'])) + + if getv(from_object, ['state']) is not None: + setv( + to_object, + ['state'], + t.t_tuning_job_status(getv(from_object, ['state'])), + ) + + if getv(from_object, ['createTime']) is not None: + setv(to_object, ['create_time'], getv(from_object, ['createTime'])) + + if getv(from_object, ['startTime']) is not None: + setv(to_object, ['start_time'], getv(from_object, ['startTime'])) + + if getv(from_object, ['endTime']) is not None: + setv(to_object, ['end_time'], getv(from_object, ['endTime'])) + + if getv(from_object, ['updateTime']) is not None: + setv(to_object, ['update_time'], getv(from_object, ['updateTime'])) + + if getv(from_object, ['error']) is not None: + setv(to_object, ['error'], getv(from_object, ['error'])) + + if getv(from_object, ['description']) is not None: + setv(to_object, ['description'], getv(from_object, ['description'])) + + if getv(from_object, ['baseModel']) is not None: + setv(to_object, ['base_model'], getv(from_object, ['baseModel'])) + + if getv(from_object, ['tunedModel']) is not None: + setv(to_object, ['tuned_model'], getv(from_object, ['tunedModel'])) + + if getv(from_object, ['preTunedModel']) is not None: + setv(to_object, ['pre_tuned_model'], getv(from_object, ['preTunedModel'])) + + if getv(from_object, ['supervisedTuningSpec']) is not None: + setv( + to_object, + ['supervised_tuning_spec'], + getv(from_object, ['supervisedTuningSpec']), + ) + + if getv(from_object, ['preferenceOptimizationSpec']) is not None: + setv( + to_object, + ['preference_optimization_spec'], + getv(from_object, ['preferenceOptimizationSpec']), + ) + + if getv(from_object, ['distillationSpec']) is not None: + setv( + to_object, + ['distillation_spec'], + getv(from_object, ['distillationSpec']), + ) + + if getv(from_object, ['tuningDataStats']) is not None: + setv( + to_object, ['tuning_data_stats'], getv(from_object, ['tuningDataStats']) + ) + + if getv(from_object, ['encryptionSpec']) is not None: + setv(to_object, ['encryption_spec'], getv(from_object, ['encryptionSpec'])) + + if getv(from_object, ['partnerModelTuningSpec']) is not None: + setv( + to_object, + ['partner_model_tuning_spec'], + getv(from_object, ['partnerModelTuningSpec']), + ) + + if getv(from_object, ['evaluationConfig']) is not None: + setv( + to_object, + ['evaluation_config'], + _EvaluationConfig_from_vertex( + getv(from_object, ['evaluationConfig']), to_object, root_object + ), + ) + + if getv(from_object, ['customBaseModel']) is not None: + setv( + to_object, ['custom_base_model'], getv(from_object, ['customBaseModel']) + ) + + if getv(from_object, ['evaluateDatasetRuns']) is not None: + setv( + to_object, + ['evaluate_dataset_runs'], + [item for item in getv(from_object, ['evaluateDatasetRuns'])], + ) + + if getv(from_object, ['experiment']) is not None: + setv(to_object, ['experiment'], getv(from_object, ['experiment'])) + + if getv(from_object, ['fullFineTuningSpec']) is not None: + setv( + to_object, + ['full_fine_tuning_spec'], + getv(from_object, ['fullFineTuningSpec']), + ) + + if getv(from_object, ['labels']) is not None: + setv(to_object, ['labels'], getv(from_object, ['labels'])) + + if getv(from_object, ['outputUri']) is not None: + setv(to_object, ['output_uri'], getv(from_object, ['outputUri'])) + + if getv(from_object, ['pipelineJob']) is not None: + setv(to_object, ['pipeline_job'], getv(from_object, ['pipelineJob'])) + + if getv(from_object, ['serviceAccount']) is not None: + setv(to_object, ['service_account'], getv(from_object, ['serviceAccount'])) + + if getv(from_object, ['tunedModelDisplayName']) is not None: + setv( + to_object, + ['tuned_model_display_name'], + getv(from_object, ['tunedModelDisplayName']), + ) + + if getv(from_object, ['tuningJobState']) is not None: + setv(to_object, ['tuning_job_state'], getv(from_object, ['tuningJobState'])) + + if getv(from_object, ['veoTuningSpec']) is not None: + setv(to_object, ['veo_tuning_spec'], getv(from_object, ['veoTuningSpec'])) + + if getv(from_object, ['distillationSamplingSpec']) is not None: + setv( + to_object, + ['distillation_sampling_spec'], + getv(from_object, ['distillationSamplingSpec']), + ) + + if getv(from_object, ['tuningJobMetadata']) is not None: + setv( + to_object, + ['tuning_job_metadata'], + getv(from_object, ['tuningJobMetadata']), + ) + + return to_object + + +def _TuningOperation_from_mldev( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['sdkHttpResponse']) is not None: + setv( + to_object, ['sdk_http_response'], getv(from_object, ['sdkHttpResponse']) + ) + + if getv(from_object, ['name']) is not None: + setv(to_object, ['name'], getv(from_object, ['name'])) + + if getv(from_object, ['metadata']) is not None: + setv(to_object, ['metadata'], getv(from_object, ['metadata'])) + + if getv(from_object, ['done']) is not None: + setv(to_object, ['done'], getv(from_object, ['done'])) + + if getv(from_object, ['error']) is not None: + setv(to_object, ['error'], getv(from_object, ['error'])) + + return to_object + + +def _TuningValidationDataset_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['gcs_uri']) is not None: + setv(to_object, ['validationDatasetUri'], getv(from_object, ['gcs_uri'])) + + if getv(from_object, ['vertex_dataset_resource']) is not None: + setv( + to_object, + ['validationDatasetUri'], + getv(from_object, ['vertex_dataset_resource']), + ) + + return to_object + + +def _VoiceConfig_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, + root_object: Optional[Union[dict[str, Any], object]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ['replicated_voice_config']) is not None: + setv( + to_object, + ['replicatedVoiceConfig'], + _ReplicatedVoiceConfig_to_vertex( + getv(from_object, ['replicated_voice_config']), + to_object, + root_object, + ), + ) + + if getv(from_object, ['prebuilt_voice_config']) is not None: + setv( + to_object, + ['prebuiltVoiceConfig'], + getv(from_object, ['prebuilt_voice_config']), + ) + + return to_object + + +class Tunings(_api_module.BaseModule): + + def _get( + self, + *, + name: str, + config: Optional[types.GetTuningJobConfigOrDict] = None, + ) -> types.TuningJob: + """Gets a TuningJob. + + Args: + name: The resource name of the tuning job. + + Returns: + A TuningJob object. + """ + + parameter_model = types._GetTuningJobParameters( + name=name, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _GetTuningJobParameters_to_vertex( + parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{name}'.format_map(request_url_dict) + else: + path = '{name}' + else: + request_dict = _GetTuningJobParameters_to_mldev( + parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{name}'.format_map(request_url_dict) + else: + path = '{name}' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request('get', path, request_dict, http_options) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _TuningJob_from_vertex( + response_dict, None, parameter_model + ) + + if not self._api_client.vertexai: + response_dict = _TuningJob_from_mldev( + response_dict, None, parameter_model + ) + + return_value = types.TuningJob._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + return_value.sdk_http_response = types.HttpResponse( + headers=response.headers + ) + self._api_client._verify_response(return_value) + return return_value + + def _list( + self, *, config: Optional[types.ListTuningJobsConfigOrDict] = None + ) -> types.ListTuningJobsResponse: + parameter_model = types._ListTuningJobsParameters( + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _ListTuningJobsParameters_to_vertex( + parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'tuningJobs'.format_map(request_url_dict) + else: + path = 'tuningJobs' + else: + request_dict = _ListTuningJobsParameters_to_mldev( + parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'tunedModels'.format_map(request_url_dict) + else: + path = 'tunedModels' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request('get', path, request_dict, http_options) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _ListTuningJobsResponse_from_vertex( + response_dict, None, parameter_model + ) + + if not self._api_client.vertexai: + response_dict = _ListTuningJobsResponse_from_mldev( + response_dict, None, parameter_model + ) + + return_value = types.ListTuningJobsResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + return_value.sdk_http_response = types.HttpResponse( + headers=response.headers + ) + self._api_client._verify_response(return_value) + return return_value + + def cancel( + self, + *, + name: str, + config: Optional[types.CancelTuningJobConfigOrDict] = None, + ) -> types.CancelTuningJobResponse: + """Cancels a tuning job. + + Args: + name (str): TuningJob resource name. + """ + + parameter_model = types._CancelTuningJobParameters( + name=name, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _CancelTuningJobParameters_to_vertex( + parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{name}:cancel'.format_map(request_url_dict) + else: + path = '{name}:cancel' + else: + request_dict = _CancelTuningJobParameters_to_mldev( + parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{name}:cancel'.format_map(request_url_dict) + else: + path = '{name}:cancel' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request( + 'post', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _CancelTuningJobResponse_from_vertex( + response_dict, None, parameter_model + ) + + if not self._api_client.vertexai: + response_dict = _CancelTuningJobResponse_from_mldev( + response_dict, None, parameter_model + ) + + return_value = types.CancelTuningJobResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + return_value.sdk_http_response = types.HttpResponse( + headers=response.headers + ) + self._api_client._verify_response(return_value) + return return_value + + def _tune( + self, + *, + base_model: Optional[str] = None, + pre_tuned_model: Optional[types.PreTunedModelOrDict] = None, + training_dataset: types.TuningDatasetOrDict, + config: Optional[types.CreateTuningJobConfigOrDict] = None, + ) -> types.TuningJob: + """Creates a tuning job and returns the TuningJob object. + + Args: + base_model: The name of the model to tune. + training_dataset: The training dataset to use. + config: The configuration to use for the tuning job. + + Returns: + A TuningJob object. + """ + + parameter_model = types._CreateTuningJobParametersPrivate( + base_model=base_model, + pre_tuned_model=pre_tuned_model, + training_dataset=training_dataset, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if not self._api_client.vertexai: + raise ValueError('This method is only supported in the Vertex AI client.') + else: + request_dict = _CreateTuningJobParametersPrivate_to_vertex( + parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'tuningJobs'.format_map(request_url_dict) + else: + path = 'tuningJobs' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request( + 'post', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _TuningJob_from_vertex( + response_dict, None, parameter_model + ) + + return_value = types.TuningJob._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + return_value.sdk_http_response = types.HttpResponse( + headers=response.headers + ) + self._api_client._verify_response(return_value) + return return_value + + def _tune_mldev( + self, + *, + base_model: Optional[str] = None, + pre_tuned_model: Optional[types.PreTunedModelOrDict] = None, + training_dataset: types.TuningDatasetOrDict, + config: Optional[types.CreateTuningJobConfigOrDict] = None, + ) -> types.TuningOperation: + """Creates a tuning job and returns the TuningJob object. + + Args: + base_model: The name of the model to tune. + training_dataset: The training dataset to use. + config: The configuration to use for the tuning job. + + Returns: + A TuningJob operation. + """ + + parameter_model = types._CreateTuningJobParametersPrivate( + base_model=base_model, + pre_tuned_model=pre_tuned_model, + training_dataset=training_dataset, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if self._api_client.vertexai: + raise ValueError( + 'This method is only supported in the Gemini Developer client.' + ) + else: + request_dict = _CreateTuningJobParametersPrivate_to_mldev( + parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'tunedModels'.format_map(request_url_dict) + else: + path = 'tunedModels' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request( + 'post', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if not self._api_client.vertexai: + response_dict = _TuningOperation_from_mldev( + response_dict, None, parameter_model + ) + + return_value = types.TuningOperation._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + return_value.sdk_http_response = types.HttpResponse( + headers=response.headers + ) + self._api_client._verify_response(return_value) + return return_value + + def get( + self, + *, + name: str, + config: Optional[types.GetTuningJobConfigOrDict] = None, + ) -> types.TuningJob: + job = self._get(name=name, config=config) + if ( + job.experiment + and self._api_client.vertexai + and self._api_client.project is not None + ): + _IpythonUtils.display_experiment_button( + experiment=job.experiment, + project=self._api_client.project, + ) + return job + + @_common.experimental_warning( + "The SDK's tuning implementation is experimental, " + 'and may change in future versions.', + ) + def tune( + self, + *, + base_model: str, + training_dataset: types.TuningDatasetOrDict, + config: Optional[types.CreateTuningJobConfigOrDict] = None, + ) -> types.TuningJob: + if self._api_client.vertexai: + if base_model.startswith('projects/'): # Pre-tuned model + checkpoint_id = None + if config: + checkpoint_id = getattr(config, 'pre_tuned_model_checkpoint_id', None) + pre_tuned_model = types.PreTunedModel( + tuned_model_name=base_model, checkpoint_id=checkpoint_id + ) + tuning_job = self._tune( + pre_tuned_model=pre_tuned_model, + training_dataset=training_dataset, + config=config, + ) + else: + validated_evaluation_config: Optional[types.EvaluationConfig] = None + if ( + config is not None + and getattr(config, 'evaluation_config', None) is not None + ): + evaluation_config = getattr(config, 'evaluation_config') + if isinstance(evaluation_config, dict): + evaluation_config = types.EvaluationConfig(**evaluation_config) + if ( + not evaluation_config.metrics + or not evaluation_config.output_config + ): + raise ValueError( + 'Evaluation config must have at least one metric and an output' + ' config.' + ) + for i in range(len(evaluation_config.metrics)): + if isinstance(evaluation_config.metrics[i], dict): + evaluation_config.metrics[i] = types.Metric.model_validate( + evaluation_config.metrics[i] + ) + if isinstance(config, dict): + config['evaluation_config'] = evaluation_config + else: + config.evaluation_config = evaluation_config + validated_evaluation_config = evaluation_config + tuning_job = self._tune( + base_model=base_model, + training_dataset=training_dataset, + config=config, + ) + if ( + config is not None + and getattr(config, 'evaluation_config', None) is not None + ): + tuning_job.evaluation_config = validated_evaluation_config + else: + operation = self._tune_mldev( + base_model=base_model, + training_dataset=training_dataset, + config=config, + ) + if operation.metadata is not None and 'tunedModel' in operation.metadata: + tuned_model_name = operation.metadata['tunedModel'] + else: + if operation.name is None: + raise ValueError('Operation name is required.') + tuned_model_name = operation.name.partition('/operations/')[0] + tuning_job = types.TuningJob( + name=tuned_model_name, + state=types.JobState.JOB_STATE_QUEUED, + ) + if tuning_job.name and self._api_client.vertexai: + _IpythonUtils.display_model_tuning_button( + tuning_job_resource=tuning_job.name + ) + return tuning_job + + def list( + self, *, config: Optional[types.ListTuningJobsConfigOrDict] = None + ) -> Pager[types.TuningJob]: + """Lists `TuningJob` objects. + + Args: + config: The configuration for the list request. + + Returns: + A Pager object that contains one page of tuning jobs. When iterating over + the pager, it automatically fetches the next page if there are more. + + Usage: + + .. code-block:: python + for tuning_job in client.tunings.list(): + print(tuning_job.name) + """ + + list_request = self._list + return Pager( + 'tuning_jobs', + list_request, + self._list(config=config), + config, + ) + + +class AsyncTunings(_api_module.BaseModule): + + async def _get( + self, + *, + name: str, + config: Optional[types.GetTuningJobConfigOrDict] = None, + ) -> types.TuningJob: + """Gets a TuningJob. + + Args: + name: The resource name of the tuning job. + + Returns: + A TuningJob object. + """ + + parameter_model = types._GetTuningJobParameters( + name=name, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _GetTuningJobParameters_to_vertex( + parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{name}'.format_map(request_url_dict) + else: + path = '{name}' + else: + request_dict = _GetTuningJobParameters_to_mldev( + parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{name}'.format_map(request_url_dict) + else: + path = '{name}' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'get', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _TuningJob_from_vertex( + response_dict, None, parameter_model + ) + + if not self._api_client.vertexai: + response_dict = _TuningJob_from_mldev( + response_dict, None, parameter_model + ) + + return_value = types.TuningJob._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + return_value.sdk_http_response = types.HttpResponse( + headers=response.headers + ) + self._api_client._verify_response(return_value) + return return_value + + async def _list( + self, *, config: Optional[types.ListTuningJobsConfigOrDict] = None + ) -> types.ListTuningJobsResponse: + parameter_model = types._ListTuningJobsParameters( + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _ListTuningJobsParameters_to_vertex( + parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'tuningJobs'.format_map(request_url_dict) + else: + path = 'tuningJobs' + else: + request_dict = _ListTuningJobsParameters_to_mldev( + parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'tunedModels'.format_map(request_url_dict) + else: + path = 'tunedModels' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'get', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _ListTuningJobsResponse_from_vertex( + response_dict, None, parameter_model + ) + + if not self._api_client.vertexai: + response_dict = _ListTuningJobsResponse_from_mldev( + response_dict, None, parameter_model + ) + + return_value = types.ListTuningJobsResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + return_value.sdk_http_response = types.HttpResponse( + headers=response.headers + ) + self._api_client._verify_response(return_value) + return return_value + + async def cancel( + self, + *, + name: str, + config: Optional[types.CancelTuningJobConfigOrDict] = None, + ) -> types.CancelTuningJobResponse: + """Cancels a tuning job asynchronously. + + Args: + name (str): A TuningJob resource name. + """ + + parameter_model = types._CancelTuningJobParameters( + name=name, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + + if self._api_client.vertexai: + request_dict = _CancelTuningJobParameters_to_vertex( + parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{name}:cancel'.format_map(request_url_dict) + else: + path = '{name}:cancel' + else: + request_dict = _CancelTuningJobParameters_to_mldev( + parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = '{name}:cancel'.format_map(request_url_dict) + else: + path = '{name}:cancel' + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'post', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _CancelTuningJobResponse_from_vertex( + response_dict, None, parameter_model + ) + + if not self._api_client.vertexai: + response_dict = _CancelTuningJobResponse_from_mldev( + response_dict, None, parameter_model + ) + + return_value = types.CancelTuningJobResponse._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + return_value.sdk_http_response = types.HttpResponse( + headers=response.headers + ) + self._api_client._verify_response(return_value) + return return_value + + async def _tune( + self, + *, + base_model: Optional[str] = None, + pre_tuned_model: Optional[types.PreTunedModelOrDict] = None, + training_dataset: types.TuningDatasetOrDict, + config: Optional[types.CreateTuningJobConfigOrDict] = None, + ) -> types.TuningJob: + """Creates a tuning job and returns the TuningJob object. + + Args: + base_model: The name of the model to tune. + training_dataset: The training dataset to use. + config: The configuration to use for the tuning job. + + Returns: + A TuningJob object. + """ + + parameter_model = types._CreateTuningJobParametersPrivate( + base_model=base_model, + pre_tuned_model=pre_tuned_model, + training_dataset=training_dataset, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if not self._api_client.vertexai: + raise ValueError('This method is only supported in the Vertex AI client.') + else: + request_dict = _CreateTuningJobParametersPrivate_to_vertex( + parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'tuningJobs'.format_map(request_url_dict) + else: + path = 'tuningJobs' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'post', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if self._api_client.vertexai: + response_dict = _TuningJob_from_vertex( + response_dict, None, parameter_model + ) + + return_value = types.TuningJob._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + return_value.sdk_http_response = types.HttpResponse( + headers=response.headers + ) + self._api_client._verify_response(return_value) + return return_value + + async def _tune_mldev( + self, + *, + base_model: Optional[str] = None, + pre_tuned_model: Optional[types.PreTunedModelOrDict] = None, + training_dataset: types.TuningDatasetOrDict, + config: Optional[types.CreateTuningJobConfigOrDict] = None, + ) -> types.TuningOperation: + """Creates a tuning job and returns the TuningJob object. + + Args: + base_model: The name of the model to tune. + training_dataset: The training dataset to use. + config: The configuration to use for the tuning job. + + Returns: + A TuningJob operation. + """ + + parameter_model = types._CreateTuningJobParametersPrivate( + base_model=base_model, + pre_tuned_model=pre_tuned_model, + training_dataset=training_dataset, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if self._api_client.vertexai: + raise ValueError( + 'This method is only supported in the Gemini Developer client.' + ) + else: + request_dict = _CreateTuningJobParametersPrivate_to_mldev( + parameter_model, None, parameter_model + ) + request_url_dict = request_dict.get('_url') + if request_url_dict: + path = 'tunedModels'.format_map(request_url_dict) + else: + path = 'tunedModels' + + query_params = request_dict.get('_query') + if query_params: + path = f'{path}?{urlencode(query_params)}' + # TODO: remove the hack that pops config. + request_dict.pop('config', None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + 'post', path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + if not self._api_client.vertexai: + response_dict = _TuningOperation_from_mldev( + response_dict, None, parameter_model + ) + + return_value = types.TuningOperation._from_response( + response=response_dict, + kwargs={ + 'config': { + 'response_schema': getattr( + parameter_model.config, 'response_schema', None + ), + 'response_json_schema': getattr( + parameter_model.config, 'response_json_schema', None + ), + 'include_all_fields': getattr( + parameter_model.config, 'include_all_fields', None + ), + } + } + if getattr(parameter_model, 'config', None) + else {}, + ) + return_value.sdk_http_response = types.HttpResponse( + headers=response.headers + ) + self._api_client._verify_response(return_value) + return return_value + + async def get( + self, + *, + name: str, + config: Optional[types.GetTuningJobConfigOrDict] = None, + ) -> types.TuningJob: + job = await self._get(name=name, config=config) + if ( + job.experiment + and self._api_client.vertexai + and self._api_client.project is not None + ): + _IpythonUtils.display_experiment_button( + experiment=job.experiment, + project=self._api_client.project, + ) + return job + + @_common.experimental_warning( + "The SDK's tuning implementation is experimental, " + 'and may change in future versions.' + ) + async def tune( + self, + *, + base_model: str, + training_dataset: types.TuningDatasetOrDict, + config: Optional[types.CreateTuningJobConfigOrDict] = None, + ) -> types.TuningJob: + if self._api_client.vertexai: + if base_model.startswith('projects/'): # Pre-tuned model + checkpoint_id = None + if config: + checkpoint_id = getattr(config, 'pre_tuned_model_checkpoint_id', None) + pre_tuned_model = types.PreTunedModel( + tuned_model_name=base_model, checkpoint_id=checkpoint_id + ) + + tuning_job = await self._tune( + pre_tuned_model=pre_tuned_model, + training_dataset=training_dataset, + config=config, + ) + else: + if ( + config is not None + and getattr(config, 'evaluation_config', None) is not None + ): + evaluation_config = getattr(config, 'evaluation_config') + if isinstance(evaluation_config, dict): + evaluation_config = types.EvaluationConfig(**evaluation_config) + if ( + not evaluation_config.metrics + or not evaluation_config.output_config + ): + raise ValueError( + 'Evaluation config must have at least one metric and an output' + ' config.' + ) + for i in range(len(evaluation_config.metrics)): + if isinstance(evaluation_config.metrics[i], dict): + evaluation_config.metrics[i] = types.Metric.model_validate( + evaluation_config.metrics[i] + ) + if isinstance(config, dict): + config['evaluation_config'] = evaluation_config + else: + config.evaluation_config = evaluation_config + tuning_job = await self._tune( + base_model=base_model, + training_dataset=training_dataset, + config=config, + ) + else: + operation = await self._tune_mldev( + base_model=base_model, + training_dataset=training_dataset, + config=config, + ) + if operation.metadata is not None and 'tunedModel' in operation.metadata: + tuned_model_name = operation.metadata['tunedModel'] + else: + if operation.name is None: + raise ValueError('Operation name is required.') + tuned_model_name = operation.name.partition('/operations/')[0] + tuning_job = types.TuningJob( + name=tuned_model_name, + state=types.JobState.JOB_STATE_QUEUED, + ) + if tuning_job.name and self._api_client.vertexai: + _IpythonUtils.display_model_tuning_button( + tuning_job_resource=tuning_job.name + ) + return tuning_job + + async def list( + self, *, config: Optional[types.ListTuningJobsConfigOrDict] = None + ) -> AsyncPager[types.TuningJob]: + """Lists `TuningJob` objects asynchronously. + + Args: + config: The configuration for the list request. + + Returns: + A Pager object that contains one page of tuning jobs. When iterating over + the pager, it automatically fetches the next page if there are more. + + Usage: + + .. code-block:: python + async for tuning_job in await client.aio.tunings.list(): + print(tuning_job.name) + """ + + list_request = self._list + return AsyncPager( + 'tuning_jobs', + list_request, + await self._list(config=config), + config, + ) + + +class _IpythonUtils: + """Temporary class to hold the IPython related functions.""" + + displayed_experiments: set[str] = set() + + @staticmethod + def _get_ipython_shell_name() -> Union[str, Any]: + import sys + + if 'IPython' in sys.modules: + from IPython import get_ipython + + return get_ipython().__class__.__name__ + return '' + + @staticmethod + def is_ipython_available() -> bool: + return bool(_IpythonUtils._get_ipython_shell_name()) + + @staticmethod + def _get_styles() -> str: + """Returns the HTML style markup to support custom buttons.""" + return """ + + + """ + + @staticmethod + def _parse_resource_name(marker: str, resource_parts: list[str]) -> str: + """Returns the part after the marker text part.""" + for i in range(len(resource_parts)): + if resource_parts[i] == marker and i + 1 < len(resource_parts): + return resource_parts[i + 1] + return '' + + @staticmethod + def _display_link( + text: str, url: str, icon: Optional[str] = 'open_in_new' + ) -> None: + """Creates and displays the link to open the Vertex resource. + + Args: + text: The text displayed on the clickable button. + url: The url that the button will lead to. Only cloud console URIs are + allowed. + icon: The icon name on the button (from material-icons library) + """ + CLOUD_UI_URL = 'https://console.cloud.google.com' # pylint: disable=invalid-name + if not url.startswith(CLOUD_UI_URL): + raise ValueError(f'Only urls starting with {CLOUD_UI_URL} are allowed.') + + import uuid + + button_id = f'view-vertex-resource-{str(uuid.uuid4())}' + + # Add the markup for the CSS and link component + html = f""" + {_IpythonUtils._get_styles()} + + {icon} + {text} + + """ + + # Add the click handler for the link + html += f""" + + """ + + from IPython.display import display + from IPython.display import HTML + + display(HTML(html)) + + @staticmethod + def display_experiment_button(experiment: str, project: str) -> None: + """Function to generate a link bound to the Vertex experiment. + + Args: + experiment: The Vertex experiment name. Example format: + projects/{project_id}/locations/{location}/metadataStores/default/contexts/{experiment_name} + project: The project (alphanumeric) name. + """ + if ( + not _IpythonUtils.is_ipython_available() + or experiment in _IpythonUtils.displayed_experiments + ): + return + # Experiment gives the numeric id, but we need the alphanumeric project + # name. So we get the project from the api client object as an argument. + resource_parts = experiment.split('/') + location = resource_parts[3] + experiment_name = resource_parts[-1] + + uri = ( + 'https://console.cloud.google.com/vertex-ai/experiments/locations/' + + f'{location}/experiments/{experiment_name}/' + + f'runs?project={project}' + ) + _IpythonUtils._display_link('View Experiment', uri, 'science') + + # Avoid repeatedly showing the button + _IpythonUtils.displayed_experiments.add(experiment) + + @staticmethod + def display_model_tuning_button(tuning_job_resource: str) -> None: + """Function to generate a link bound to the Vertex model tuning job. + + Args: + tuning_job_resource: The Vertex tuning job name. Example format: + projects/{project_id}/locations/{location}/tuningJobs/{tuning_job_id} + """ + if not _IpythonUtils.is_ipython_available(): + return + + resource_parts = tuning_job_resource.split('/') + project = resource_parts[1] + location = resource_parts[3] + tuning_job_id = resource_parts[-1] + + uri = ( + 'https://console.cloud.google.com/vertex-ai/generative/language/' + + f'locations/{location}/tuning/tuningJob/{tuning_job_id}' + + f'?project={project}' + ) + _IpythonUtils._display_link('View Tuning Job', uri, 'tune') diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/types.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/types.py new file mode 100644 index 0000000000000000000000000000000000000000..20c4f1c0ee773bd0d498bdbd82086aa6b750c218 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/types.py @@ -0,0 +1,21078 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +# Code generated by the Google Gen AI SDK generator DO NOT EDIT. + +from abc import ABC, abstractmethod +import datetime +from enum import Enum, EnumMeta +import inspect +import io +import json +import logging +import sys +import types as builtin_types +import typing +from typing import Any, Callable, Dict, List, Literal, Optional, Sequence, Union, _UnionGenericAlias # type: ignore +import pydantic +from pydantic import ConfigDict, Field, PrivateAttr, model_validator +from typing_extensions import Self, TypedDict +from . import _common +from ._operations_converters import ( + _GenerateVideosOperation_from_mldev, + _GenerateVideosOperation_from_vertex, + _ImportFileOperation_from_mldev, + _UploadToFileSearchStoreOperation_from_mldev, +) + +if sys.version_info >= (3, 10): + # Supports both Union[t1, t2] and t1 | t2 + VersionedUnionType = Union[builtin_types.UnionType, _UnionGenericAlias] + _UNION_TYPES = (typing.Union, builtin_types.UnionType) +else: + # Supports only Union[t1, t2] + VersionedUnionType = _UnionGenericAlias + _UNION_TYPES = (typing.Union,) + +_is_pillow_image_imported = False +if typing.TYPE_CHECKING: + from ._api_client import BaseApiClient + import PIL.Image + + PIL_Image = PIL.Image.Image + _is_pillow_image_imported = True +else: + PIL_Image: typing.Type = Any + try: + import PIL.Image + + PIL_Image = PIL.Image.Image + _is_pillow_image_imported = True + except ImportError: + PIL_Image = None + +_is_mcp_imported = False +if typing.TYPE_CHECKING: + from mcp import types as mcp_types + from mcp import ClientSession as McpClientSession + from mcp.types import CallToolResult as McpCallToolResult + + _is_mcp_imported = True +else: + McpClientSession: typing.Type = Any + McpCallToolResult: typing.Type = Any + try: + from mcp import types as mcp_types + from mcp import ClientSession as McpClientSession + from mcp.types import CallToolResult as McpCallToolResult + + _is_mcp_imported = True + except ImportError: + McpClientSession = None + McpCallToolResult = None + +if typing.TYPE_CHECKING: + import yaml + +_is_httpx_imported = False +if typing.TYPE_CHECKING: + import httpx + + HttpxClient = httpx.Client + HttpxAsyncClient = httpx.AsyncClient + _is_httpx_imported = True +else: + HttpxClient: typing.Type = Any + HttpxAsyncClient: typing.Type = Any + + try: + import httpx + + HttpxClient = httpx.Client + HttpxAsyncClient = httpx.AsyncClient + _is_httpx_imported = True + except ImportError: + HttpxClient = None + HttpxAsyncClient = None + +_is_aiohttp_imported = False +if typing.TYPE_CHECKING: + from aiohttp import ClientSession + + _is_aiohttp_imported = True +else: + ClientSession: typing.Type = Any + try: + from aiohttp import ClientSession + + _is_aiohttp_imported = True + except ImportError: + ClientSession = None + +logger = logging.getLogger('google_genai.types') +_from_json_schema_warning_logged = False +_json_schema_warning_logged = False +_response_text_warning_logged = False +_response_text_non_text_warning_logged = False +_response_parts_warning_logged = False +_response_function_calls_warning_logged = False +_response_executable_code_warning_logged = False +_response_code_execution_warning_logged = False +_live_server_text_warning_logged = False +_live_server_data_warning_logged = False + + +T = typing.TypeVar('T', bound='GenerateContentResponse') + +MetricSubclass = typing.TypeVar('MetricSubclass', bound='Metric') + + +class Language(_common.CaseInSensitiveEnum): + """Programming language of the `code`.""" + + LANGUAGE_UNSPECIFIED = 'LANGUAGE_UNSPECIFIED' + """Unspecified language. This value should not be used.""" + PYTHON = 'PYTHON' + """Python >= 3.10, with numpy and simpy available.""" + + +class Outcome(_common.CaseInSensitiveEnum): + """Outcome of the code execution.""" + + OUTCOME_UNSPECIFIED = 'OUTCOME_UNSPECIFIED' + """Unspecified status. This value should not be used.""" + OUTCOME_OK = 'OUTCOME_OK' + """Code execution completed successfully.""" + OUTCOME_FAILED = 'OUTCOME_FAILED' + """Code execution finished but with a failure. `stderr` should contain the reason.""" + OUTCOME_DEADLINE_EXCEEDED = 'OUTCOME_DEADLINE_EXCEEDED' + """Code execution ran for too long, and was cancelled. There may or may not be a partial output present.""" + + +class FunctionResponseScheduling(_common.CaseInSensitiveEnum): + """Specifies how the response should be scheduled in the conversation.""" + + SCHEDULING_UNSPECIFIED = 'SCHEDULING_UNSPECIFIED' + """This value is unused.""" + SILENT = 'SILENT' + """Only add the result to the conversation context, do not interrupt or trigger generation.""" + WHEN_IDLE = 'WHEN_IDLE' + """Add the result to the conversation context, and prompt to generate output without interrupting ongoing generation.""" + INTERRUPT = 'INTERRUPT' + """Add the result to the conversation context, interrupt ongoing generation and prompt to generate output.""" + + +class Type(_common.CaseInSensitiveEnum): + """Data type of the schema field.""" + + TYPE_UNSPECIFIED = 'TYPE_UNSPECIFIED' + """Not specified, should not be used.""" + STRING = 'STRING' + """OpenAPI string type""" + NUMBER = 'NUMBER' + """OpenAPI number type""" + INTEGER = 'INTEGER' + """OpenAPI integer type""" + BOOLEAN = 'BOOLEAN' + """OpenAPI boolean type""" + ARRAY = 'ARRAY' + """OpenAPI array type""" + OBJECT = 'OBJECT' + """OpenAPI object type""" + NULL = 'NULL' + """Null type""" + + +class Environment(_common.CaseInSensitiveEnum): + """The environment being operated.""" + + ENVIRONMENT_UNSPECIFIED = 'ENVIRONMENT_UNSPECIFIED' + """Defaults to browser.""" + ENVIRONMENT_BROWSER = 'ENVIRONMENT_BROWSER' + """Operates in a web browser.""" + + +class AuthType(_common.CaseInSensitiveEnum): + """Type of auth scheme. This enum is not supported in Gemini API.""" + + AUTH_TYPE_UNSPECIFIED = 'AUTH_TYPE_UNSPECIFIED' + NO_AUTH = 'NO_AUTH' + """No Auth.""" + API_KEY_AUTH = 'API_KEY_AUTH' + """API Key Auth.""" + HTTP_BASIC_AUTH = 'HTTP_BASIC_AUTH' + """HTTP Basic Auth.""" + GOOGLE_SERVICE_ACCOUNT_AUTH = 'GOOGLE_SERVICE_ACCOUNT_AUTH' + """Google Service Account Auth.""" + OAUTH = 'OAUTH' + """OAuth auth.""" + OIDC_AUTH = 'OIDC_AUTH' + """OpenID Connect (OIDC) Auth.""" + + +class HttpElementLocation(_common.CaseInSensitiveEnum): + """The location of the API key. This enum is not supported in Gemini API.""" + + HTTP_IN_UNSPECIFIED = 'HTTP_IN_UNSPECIFIED' + HTTP_IN_QUERY = 'HTTP_IN_QUERY' + """Element is in the HTTP request query.""" + HTTP_IN_HEADER = 'HTTP_IN_HEADER' + """Element is in the HTTP request header.""" + HTTP_IN_PATH = 'HTTP_IN_PATH' + """Element is in the HTTP request path.""" + HTTP_IN_BODY = 'HTTP_IN_BODY' + """Element is in the HTTP request body.""" + HTTP_IN_COOKIE = 'HTTP_IN_COOKIE' + """Element is in the HTTP request cookie.""" + + +class ApiSpec(_common.CaseInSensitiveEnum): + """The API spec that the external API implements. + + This enum is not supported in Gemini API. + """ + + API_SPEC_UNSPECIFIED = 'API_SPEC_UNSPECIFIED' + """Unspecified API spec. This value should not be used.""" + SIMPLE_SEARCH = 'SIMPLE_SEARCH' + """Simple search API spec.""" + ELASTIC_SEARCH = 'ELASTIC_SEARCH' + """Elastic search API spec.""" + + +class PhishBlockThreshold(_common.CaseInSensitiveEnum): + """Sites with confidence level chosen & above this value will be blocked from the search results. + + This enum is not supported in Gemini API. + """ + + PHISH_BLOCK_THRESHOLD_UNSPECIFIED = 'PHISH_BLOCK_THRESHOLD_UNSPECIFIED' + """Defaults to unspecified.""" + BLOCK_LOW_AND_ABOVE = 'BLOCK_LOW_AND_ABOVE' + """Blocks Low and above confidence URL that is risky.""" + BLOCK_MEDIUM_AND_ABOVE = 'BLOCK_MEDIUM_AND_ABOVE' + """Blocks Medium and above confidence URL that is risky.""" + BLOCK_HIGH_AND_ABOVE = 'BLOCK_HIGH_AND_ABOVE' + """Blocks High and above confidence URL that is risky.""" + BLOCK_HIGHER_AND_ABOVE = 'BLOCK_HIGHER_AND_ABOVE' + """Blocks Higher and above confidence URL that is risky.""" + BLOCK_VERY_HIGH_AND_ABOVE = 'BLOCK_VERY_HIGH_AND_ABOVE' + """Blocks Very high and above confidence URL that is risky.""" + BLOCK_ONLY_EXTREMELY_HIGH = 'BLOCK_ONLY_EXTREMELY_HIGH' + """Blocks Extremely high confidence URL that is risky.""" + + +class Behavior(_common.CaseInSensitiveEnum): + """Specifies the function Behavior. + + Currently only supported by the BidiGenerateContent method. This enum is not + supported in Vertex AI. + """ + + UNSPECIFIED = 'UNSPECIFIED' + """This value is unused.""" + BLOCKING = 'BLOCKING' + """If set, the system will wait to receive the function response before continuing the conversation.""" + NON_BLOCKING = 'NON_BLOCKING' + """If set, the system will not wait to receive the function response. Instead, it will attempt to handle function responses as they become available while maintaining the conversation between the user and the model.""" + + +class DynamicRetrievalConfigMode(_common.CaseInSensitiveEnum): + """The mode of the predictor to be used in dynamic retrieval.""" + + MODE_UNSPECIFIED = 'MODE_UNSPECIFIED' + """Always trigger retrieval.""" + MODE_DYNAMIC = 'MODE_DYNAMIC' + """Run retrieval only when system decides it is necessary.""" + + +class FunctionCallingConfigMode(_common.CaseInSensitiveEnum): + """Function calling mode.""" + + MODE_UNSPECIFIED = 'MODE_UNSPECIFIED' + """Unspecified function calling mode. This value should not be used.""" + AUTO = 'AUTO' + """Default model behavior, model decides to predict either function calls or natural language response.""" + ANY = 'ANY' + """Model is constrained to always predicting function calls only. If "allowed_function_names" are set, the predicted function calls will be limited to any one of "allowed_function_names", else the predicted function calls will be any one of the provided "function_declarations".""" + NONE = 'NONE' + """Model will not predict any function calls. Model behavior is same as when not passing any function declarations.""" + VALIDATED = 'VALIDATED' + """Model is constrained to predict either function calls or natural language response. If "allowed_function_names" are set, the predicted function calls will be limited to any one of "allowed_function_names", else the predicted function calls will be any one of the provided "function_declarations".""" + + +class ThinkingLevel(_common.CaseInSensitiveEnum): + """The number of thoughts tokens that the model should generate.""" + + THINKING_LEVEL_UNSPECIFIED = 'THINKING_LEVEL_UNSPECIFIED' + """Unspecified thinking level.""" + MINIMAL = 'MINIMAL' + """MINIMAL thinking level.""" + LOW = 'LOW' + """Low thinking level.""" + MEDIUM = 'MEDIUM' + """Medium thinking level.""" + HIGH = 'HIGH' + """High thinking level.""" + + +class PersonGeneration(_common.CaseInSensitiveEnum): + """Enum that controls the generation of people.""" + + DONT_ALLOW = 'DONT_ALLOW' + """Block generation of images of people.""" + ALLOW_ADULT = 'ALLOW_ADULT' + """Generate images of adults, but not children.""" + ALLOW_ALL = 'ALLOW_ALL' + """Generate images that include adults and children.""" + + +class ProminentPeople(_common.CaseInSensitiveEnum): + """Controls whether prominent people (celebrities) generation is allowed. + + If used with personGeneration, personGeneration enum would take precedence. + For instance, if ALLOW_NONE is set, all person generation would be blocked. If + this field is unspecified, the default behavior is to allow prominent people. + This enum is not supported in Gemini API. + """ + + PROMINENT_PEOPLE_UNSPECIFIED = 'PROMINENT_PEOPLE_UNSPECIFIED' + """Unspecified value. The model will proceed with the default behavior, which is to allow generation of prominent people.""" + ALLOW_PROMINENT_PEOPLE = 'ALLOW_PROMINENT_PEOPLE' + """Allows the model to generate images of prominent people.""" + BLOCK_PROMINENT_PEOPLE = 'BLOCK_PROMINENT_PEOPLE' + """Prevents the model from generating images of prominent people.""" + + +class HarmCategory(_common.CaseInSensitiveEnum): + """The harm category to be blocked.""" + + HARM_CATEGORY_UNSPECIFIED = 'HARM_CATEGORY_UNSPECIFIED' + """Default value. This value is unused.""" + HARM_CATEGORY_HARASSMENT = 'HARM_CATEGORY_HARASSMENT' + """Abusive, threatening, or content intended to bully, torment, or ridicule.""" + HARM_CATEGORY_HATE_SPEECH = 'HARM_CATEGORY_HATE_SPEECH' + """Content that promotes violence or incites hatred against individuals or groups based on certain attributes.""" + HARM_CATEGORY_SEXUALLY_EXPLICIT = 'HARM_CATEGORY_SEXUALLY_EXPLICIT' + """Content that contains sexually explicit material.""" + HARM_CATEGORY_DANGEROUS_CONTENT = 'HARM_CATEGORY_DANGEROUS_CONTENT' + """Content that promotes, facilitates, or enables dangerous activities.""" + HARM_CATEGORY_CIVIC_INTEGRITY = 'HARM_CATEGORY_CIVIC_INTEGRITY' + """Deprecated: Election filter is not longer supported. The harm category is civic integrity.""" + HARM_CATEGORY_IMAGE_HATE = 'HARM_CATEGORY_IMAGE_HATE' + """Images that contain hate speech. This enum value is not supported in Gemini API.""" + HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT = ( + 'HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT' + ) + """Images that contain dangerous content. This enum value is not supported in Gemini API.""" + HARM_CATEGORY_IMAGE_HARASSMENT = 'HARM_CATEGORY_IMAGE_HARASSMENT' + """Images that contain harassment. This enum value is not supported in Gemini API.""" + HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT = ( + 'HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT' + ) + """Images that contain sexually explicit content. This enum value is not supported in Gemini API.""" + HARM_CATEGORY_JAILBREAK = 'HARM_CATEGORY_JAILBREAK' + """Prompts designed to bypass safety filters. This enum value is not supported in Gemini API.""" + + +class HarmBlockMethod(_common.CaseInSensitiveEnum): + """The method for blocking content. + + If not specified, the default behavior is to use the probability score. This + enum is not supported in Gemini API. + """ + + HARM_BLOCK_METHOD_UNSPECIFIED = 'HARM_BLOCK_METHOD_UNSPECIFIED' + """The harm block method is unspecified.""" + SEVERITY = 'SEVERITY' + """The harm block method uses both probability and severity scores.""" + PROBABILITY = 'PROBABILITY' + """The harm block method uses the probability score.""" + + +class HarmBlockThreshold(_common.CaseInSensitiveEnum): + """The threshold for blocking content. + + If the harm probability exceeds this threshold, the content will be blocked. + """ + + HARM_BLOCK_THRESHOLD_UNSPECIFIED = 'HARM_BLOCK_THRESHOLD_UNSPECIFIED' + """The harm block threshold is unspecified.""" + BLOCK_LOW_AND_ABOVE = 'BLOCK_LOW_AND_ABOVE' + """Block content with a low harm probability or higher.""" + BLOCK_MEDIUM_AND_ABOVE = 'BLOCK_MEDIUM_AND_ABOVE' + """Block content with a medium harm probability or higher.""" + BLOCK_ONLY_HIGH = 'BLOCK_ONLY_HIGH' + """Block content with a high harm probability.""" + BLOCK_NONE = 'BLOCK_NONE' + """Do not block any content, regardless of its harm probability.""" + OFF = 'OFF' + """Turn off the safety filter entirely.""" + + +class FinishReason(_common.CaseInSensitiveEnum): + """Output only. The reason why the model stopped generating tokens. + + If empty, the model has not stopped generating the tokens. + """ + + FINISH_REASON_UNSPECIFIED = 'FINISH_REASON_UNSPECIFIED' + """The finish reason is unspecified.""" + STOP = 'STOP' + """Token generation reached a natural stopping point or a configured stop sequence.""" + MAX_TOKENS = 'MAX_TOKENS' + """Token generation reached the configured maximum output tokens.""" + SAFETY = 'SAFETY' + """Token generation stopped because the content potentially contains safety violations. NOTE: When streaming, [content][] is empty if content filters blocks the output.""" + RECITATION = 'RECITATION' + """The token generation stopped because of potential recitation.""" + LANGUAGE = 'LANGUAGE' + """The token generation stopped because of using an unsupported language.""" + OTHER = 'OTHER' + """All other reasons that stopped the token generation.""" + BLOCKLIST = 'BLOCKLIST' + """Token generation stopped because the content contains forbidden terms.""" + PROHIBITED_CONTENT = 'PROHIBITED_CONTENT' + """Token generation stopped for potentially containing prohibited content.""" + SPII = 'SPII' + """Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII).""" + MALFORMED_FUNCTION_CALL = 'MALFORMED_FUNCTION_CALL' + """The function call generated by the model is invalid.""" + IMAGE_SAFETY = 'IMAGE_SAFETY' + """Token generation stopped because generated images have safety violations.""" + UNEXPECTED_TOOL_CALL = 'UNEXPECTED_TOOL_CALL' + """The tool call generated by the model is invalid.""" + IMAGE_PROHIBITED_CONTENT = 'IMAGE_PROHIBITED_CONTENT' + """Image generation stopped because the generated images have prohibited content.""" + NO_IMAGE = 'NO_IMAGE' + """The model was expected to generate an image, but none was generated.""" + IMAGE_RECITATION = 'IMAGE_RECITATION' + """Image generation stopped because the generated image may be a recitation from a source.""" + IMAGE_OTHER = 'IMAGE_OTHER' + """Image generation stopped for a reason not otherwise specified.""" + + +class HarmProbability(_common.CaseInSensitiveEnum): + """Output only. The probability of harm for this category.""" + + HARM_PROBABILITY_UNSPECIFIED = 'HARM_PROBABILITY_UNSPECIFIED' + """The harm probability is unspecified.""" + NEGLIGIBLE = 'NEGLIGIBLE' + """The harm probability is negligible.""" + LOW = 'LOW' + """The harm probability is low.""" + MEDIUM = 'MEDIUM' + """The harm probability is medium.""" + HIGH = 'HIGH' + """The harm probability is high.""" + + +class HarmSeverity(_common.CaseInSensitiveEnum): + """Output only. + + The severity of harm for this category. This enum is not supported in Gemini + API. + """ + + HARM_SEVERITY_UNSPECIFIED = 'HARM_SEVERITY_UNSPECIFIED' + """The harm severity is unspecified.""" + HARM_SEVERITY_NEGLIGIBLE = 'HARM_SEVERITY_NEGLIGIBLE' + """The harm severity is negligible.""" + HARM_SEVERITY_LOW = 'HARM_SEVERITY_LOW' + """The harm severity is low.""" + HARM_SEVERITY_MEDIUM = 'HARM_SEVERITY_MEDIUM' + """The harm severity is medium.""" + HARM_SEVERITY_HIGH = 'HARM_SEVERITY_HIGH' + """The harm severity is high.""" + + +class UrlRetrievalStatus(_common.CaseInSensitiveEnum): + """The status of the URL retrieval.""" + + URL_RETRIEVAL_STATUS_UNSPECIFIED = 'URL_RETRIEVAL_STATUS_UNSPECIFIED' + """Default value. This value is unused.""" + URL_RETRIEVAL_STATUS_SUCCESS = 'URL_RETRIEVAL_STATUS_SUCCESS' + """The URL was retrieved successfully.""" + URL_RETRIEVAL_STATUS_ERROR = 'URL_RETRIEVAL_STATUS_ERROR' + """The URL retrieval failed.""" + URL_RETRIEVAL_STATUS_PAYWALL = 'URL_RETRIEVAL_STATUS_PAYWALL' + """Url retrieval is failed because the content is behind paywall. This enum value is not supported in Vertex AI.""" + URL_RETRIEVAL_STATUS_UNSAFE = 'URL_RETRIEVAL_STATUS_UNSAFE' + """Url retrieval is failed because the content is unsafe. This enum value is not supported in Vertex AI.""" + + +class BlockedReason(_common.CaseInSensitiveEnum): + """Output only. The reason why the prompt was blocked.""" + + BLOCKED_REASON_UNSPECIFIED = 'BLOCKED_REASON_UNSPECIFIED' + """The blocked reason is unspecified.""" + SAFETY = 'SAFETY' + """The prompt was blocked for safety reasons.""" + OTHER = 'OTHER' + """The prompt was blocked for other reasons. For example, it may be due to the prompt's language, or because it contains other harmful content.""" + BLOCKLIST = 'BLOCKLIST' + """The prompt was blocked because it contains a term from the terminology blocklist.""" + PROHIBITED_CONTENT = 'PROHIBITED_CONTENT' + """The prompt was blocked because it contains prohibited content.""" + IMAGE_SAFETY = 'IMAGE_SAFETY' + """The prompt was blocked because it contains content that is unsafe for image generation.""" + MODEL_ARMOR = 'MODEL_ARMOR' + """The prompt was blocked by Model Armor. This enum value is not supported in Gemini API.""" + JAILBREAK = 'JAILBREAK' + """The prompt was blocked as a jailbreak attempt. This enum value is not supported in Gemini API.""" + + +class TrafficType(_common.CaseInSensitiveEnum): + """Output only. + + The traffic type for this request. This enum is not supported in Gemini API. + """ + + TRAFFIC_TYPE_UNSPECIFIED = 'TRAFFIC_TYPE_UNSPECIFIED' + """Unspecified request traffic type.""" + ON_DEMAND = 'ON_DEMAND' + """The request was processed using Pay-As-You-Go quota.""" + ON_DEMAND_PRIORITY = 'ON_DEMAND_PRIORITY' + """Type for Priority Pay-As-You-Go traffic.""" + ON_DEMAND_FLEX = 'ON_DEMAND_FLEX' + """Type for Flex traffic.""" + PROVISIONED_THROUGHPUT = 'PROVISIONED_THROUGHPUT' + """Type for Provisioned Throughput traffic.""" + + +class Modality(_common.CaseInSensitiveEnum): + """Server content modalities.""" + + MODALITY_UNSPECIFIED = 'MODALITY_UNSPECIFIED' + """The modality is unspecified.""" + TEXT = 'TEXT' + """Indicates the model should return text""" + IMAGE = 'IMAGE' + """Indicates the model should return images.""" + AUDIO = 'AUDIO' + """Indicates the model should return audio.""" + VIDEO = 'VIDEO' + """Indicates the model should return video.""" + + +class ModelStage(_common.CaseInSensitiveEnum): + """The stage of the underlying model. + + This enum is not supported in Vertex AI. + """ + + MODEL_STAGE_UNSPECIFIED = 'MODEL_STAGE_UNSPECIFIED' + """Unspecified model stage.""" + UNSTABLE_EXPERIMENTAL = 'UNSTABLE_EXPERIMENTAL' + """The underlying model is subject to lots of tunings.""" + EXPERIMENTAL = 'EXPERIMENTAL' + """Models in this stage are for experimental purposes only.""" + PREVIEW = 'PREVIEW' + """Models in this stage are more mature than experimental models.""" + STABLE = 'STABLE' + """Models in this stage are considered stable and ready for production use.""" + LEGACY = 'LEGACY' + """If the model is on this stage, it means that this model is on the path to deprecation in near future. Only existing customers can use this model.""" + DEPRECATED = 'DEPRECATED' + """Models in this stage are deprecated. These models cannot be used.""" + RETIRED = 'RETIRED' + """Models in this stage are retired. These models cannot be used.""" + + +class MediaResolution(_common.CaseInSensitiveEnum): + """The media resolution to use.""" + + MEDIA_RESOLUTION_UNSPECIFIED = 'MEDIA_RESOLUTION_UNSPECIFIED' + """Media resolution has not been set""" + MEDIA_RESOLUTION_LOW = 'MEDIA_RESOLUTION_LOW' + """Media resolution set to low (64 tokens).""" + MEDIA_RESOLUTION_MEDIUM = 'MEDIA_RESOLUTION_MEDIUM' + """Media resolution set to medium (256 tokens).""" + MEDIA_RESOLUTION_HIGH = 'MEDIA_RESOLUTION_HIGH' + """Media resolution set to high (zoomed reframing with 256 tokens).""" + + +class TuningMode(_common.CaseInSensitiveEnum): + """Tuning mode. This enum is not supported in Gemini API.""" + + TUNING_MODE_UNSPECIFIED = 'TUNING_MODE_UNSPECIFIED' + """Tuning mode is unspecified.""" + TUNING_MODE_FULL = 'TUNING_MODE_FULL' + """Full fine-tuning mode.""" + TUNING_MODE_PEFT_ADAPTER = 'TUNING_MODE_PEFT_ADAPTER' + """PEFT adapter tuning mode.""" + + +class AdapterSize(_common.CaseInSensitiveEnum): + """Adapter size for tuning. This enum is not supported in Gemini API.""" + + ADAPTER_SIZE_UNSPECIFIED = 'ADAPTER_SIZE_UNSPECIFIED' + """Adapter size is unspecified.""" + ADAPTER_SIZE_ONE = 'ADAPTER_SIZE_ONE' + """Adapter size 1.""" + ADAPTER_SIZE_TWO = 'ADAPTER_SIZE_TWO' + """Adapter size 2.""" + ADAPTER_SIZE_FOUR = 'ADAPTER_SIZE_FOUR' + """Adapter size 4.""" + ADAPTER_SIZE_EIGHT = 'ADAPTER_SIZE_EIGHT' + """Adapter size 8.""" + ADAPTER_SIZE_SIXTEEN = 'ADAPTER_SIZE_SIXTEEN' + """Adapter size 16.""" + ADAPTER_SIZE_THIRTY_TWO = 'ADAPTER_SIZE_THIRTY_TWO' + """Adapter size 32.""" + + +class JobState(_common.CaseInSensitiveEnum): + """Job state.""" + + JOB_STATE_UNSPECIFIED = 'JOB_STATE_UNSPECIFIED' + """The job state is unspecified.""" + JOB_STATE_QUEUED = 'JOB_STATE_QUEUED' + """The job has been just created or resumed and processing has not yet begun.""" + JOB_STATE_PENDING = 'JOB_STATE_PENDING' + """The service is preparing to run the job.""" + JOB_STATE_RUNNING = 'JOB_STATE_RUNNING' + """The job is in progress.""" + JOB_STATE_SUCCEEDED = 'JOB_STATE_SUCCEEDED' + """The job completed successfully.""" + JOB_STATE_FAILED = 'JOB_STATE_FAILED' + """The job failed.""" + JOB_STATE_CANCELLING = 'JOB_STATE_CANCELLING' + """The job is being cancelled. From this state the job may only go to either `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`.""" + JOB_STATE_CANCELLED = 'JOB_STATE_CANCELLED' + """The job has been cancelled.""" + JOB_STATE_PAUSED = 'JOB_STATE_PAUSED' + """The job has been stopped, and can be resumed.""" + JOB_STATE_EXPIRED = 'JOB_STATE_EXPIRED' + """The job has expired.""" + JOB_STATE_UPDATING = 'JOB_STATE_UPDATING' + """The job is being updated. Only jobs in the `JOB_STATE_RUNNING` state can be updated. After updating, the job goes back to the `JOB_STATE_RUNNING` state.""" + JOB_STATE_PARTIALLY_SUCCEEDED = 'JOB_STATE_PARTIALLY_SUCCEEDED' + """The job is partially succeeded, some results may be missing due to errors.""" + + +class TuningJobState(_common.CaseInSensitiveEnum): + """Output only. + + The detail state of the tuning job (while the overall `JobState` is running). + This enum is not supported in Gemini API. + """ + + TUNING_JOB_STATE_UNSPECIFIED = 'TUNING_JOB_STATE_UNSPECIFIED' + """Default tuning job state.""" + TUNING_JOB_STATE_WAITING_FOR_QUOTA = 'TUNING_JOB_STATE_WAITING_FOR_QUOTA' + """Tuning job is waiting for job quota.""" + TUNING_JOB_STATE_PROCESSING_DATASET = 'TUNING_JOB_STATE_PROCESSING_DATASET' + """Tuning job is validating the dataset.""" + TUNING_JOB_STATE_WAITING_FOR_CAPACITY = ( + 'TUNING_JOB_STATE_WAITING_FOR_CAPACITY' + ) + """Tuning job is waiting for hardware capacity.""" + TUNING_JOB_STATE_TUNING = 'TUNING_JOB_STATE_TUNING' + """Tuning job is running.""" + TUNING_JOB_STATE_POST_PROCESSING = 'TUNING_JOB_STATE_POST_PROCESSING' + """Tuning job is doing some post processing steps.""" + + +class AggregationMetric(_common.CaseInSensitiveEnum): + """Aggregation metric. This enum is not supported in Gemini API.""" + + AGGREGATION_METRIC_UNSPECIFIED = 'AGGREGATION_METRIC_UNSPECIFIED' + """Unspecified aggregation metric.""" + AVERAGE = 'AVERAGE' + """Average aggregation metric. Not supported for Pairwise metric.""" + MODE = 'MODE' + """Mode aggregation metric.""" + STANDARD_DEVIATION = 'STANDARD_DEVIATION' + """Standard deviation aggregation metric. Not supported for pairwise metric.""" + VARIANCE = 'VARIANCE' + """Variance aggregation metric. Not supported for pairwise metric.""" + MINIMUM = 'MINIMUM' + """Minimum aggregation metric. Not supported for pairwise metric.""" + MAXIMUM = 'MAXIMUM' + """Maximum aggregation metric. Not supported for pairwise metric.""" + MEDIAN = 'MEDIAN' + """Median aggregation metric. Not supported for pairwise metric.""" + PERCENTILE_P90 = 'PERCENTILE_P90' + """90th percentile aggregation metric. Not supported for pairwise metric.""" + PERCENTILE_P95 = 'PERCENTILE_P95' + """95th percentile aggregation metric. Not supported for pairwise metric.""" + PERCENTILE_P99 = 'PERCENTILE_P99' + """99th percentile aggregation metric. Not supported for pairwise metric.""" + + +class PairwiseChoice(_common.CaseInSensitiveEnum): + """Output only. + + Pairwise metric choice. This enum is not supported in Gemini API. + """ + + PAIRWISE_CHOICE_UNSPECIFIED = 'PAIRWISE_CHOICE_UNSPECIFIED' + """Unspecified prediction choice.""" + BASELINE = 'BASELINE' + """Baseline prediction wins""" + CANDIDATE = 'CANDIDATE' + """Candidate prediction wins""" + TIE = 'TIE' + """Winner cannot be determined""" + + +class TuningTask(_common.CaseInSensitiveEnum): + """The tuning task. + + Either I2V or T2V. This enum is not supported in Gemini API. + """ + + TUNING_TASK_UNSPECIFIED = 'TUNING_TASK_UNSPECIFIED' + """Default value. This value is unused.""" + TUNING_TASK_I2V = 'TUNING_TASK_I2V' + """Tuning task for image to video.""" + TUNING_TASK_T2V = 'TUNING_TASK_T2V' + """Tuning task for text to video.""" + TUNING_TASK_R2V = 'TUNING_TASK_R2V' + """Tuning task for reference to video.""" + + +class DocumentState(_common.CaseInSensitiveEnum): + """Output only. + + Current state of the `Document`. This enum is not supported in Vertex AI. + """ + + STATE_UNSPECIFIED = 'STATE_UNSPECIFIED' + """The default value. This value is used if the state is omitted.""" + STATE_PENDING = 'STATE_PENDING' + """Some `Chunks` of the `Document` are being processed (embedding and vector storage).""" + STATE_ACTIVE = 'STATE_ACTIVE' + """All `Chunks` of the `Document` is processed and available for querying.""" + STATE_FAILED = 'STATE_FAILED' + """Some `Chunks` of the `Document` failed processing.""" + + +class RubricContentType(_common.CaseInSensitiveEnum): + """Represents the rubric content type.""" + + RUBRIC_CONTENT_TYPE_UNSPECIFIED = 'RUBRIC_CONTENT_TYPE_UNSPECIFIED' + """Rubric content type is unspecified.""" + PROPERTY = 'PROPERTY' + """Generate rubrics based on properties.""" + NL_QUESTION_ANSWER = 'NL_QUESTION_ANSWER' + """Generate rubrics in an NL question answer format.""" + PYTHON_CODE_ASSERTION = 'PYTHON_CODE_ASSERTION' + """Generate rubrics in a unit test format.""" + + +class ComputationBasedMetricType(_common.CaseInSensitiveEnum): + """Represents the type of the computation based metric.""" + + COMPUTATION_BASED_METRIC_TYPE_UNSPECIFIED = ( + 'COMPUTATION_BASED_METRIC_TYPE_UNSPECIFIED' + ) + """Computation based metric type is unspecified.""" + EXACT_MATCH = 'EXACT_MATCH' + """Exact match metric.""" + BLEU = 'BLEU' + """BLEU metric.""" + ROUGE = 'ROUGE' + """ROUGE metric.""" + + +class PartMediaResolutionLevel(_common.CaseInSensitiveEnum): + """The tokenization quality used for given media.""" + + MEDIA_RESOLUTION_UNSPECIFIED = 'MEDIA_RESOLUTION_UNSPECIFIED' + """Media resolution has not been set.""" + MEDIA_RESOLUTION_LOW = 'MEDIA_RESOLUTION_LOW' + """Media resolution set to low.""" + MEDIA_RESOLUTION_MEDIUM = 'MEDIA_RESOLUTION_MEDIUM' + """Media resolution set to medium.""" + MEDIA_RESOLUTION_HIGH = 'MEDIA_RESOLUTION_HIGH' + """Media resolution set to high.""" + MEDIA_RESOLUTION_ULTRA_HIGH = 'MEDIA_RESOLUTION_ULTRA_HIGH' + """Media resolution set to ultra high.""" + + +class ToolType(_common.CaseInSensitiveEnum): + """The type of tool in the function call.""" + + TOOL_TYPE_UNSPECIFIED = 'TOOL_TYPE_UNSPECIFIED' + """Unspecified tool type.""" + GOOGLE_SEARCH_WEB = 'GOOGLE_SEARCH_WEB' + """Google search tool, maps to Tool.google_search.search_types.web_search.""" + GOOGLE_SEARCH_IMAGE = 'GOOGLE_SEARCH_IMAGE' + """Image search tool, maps to Tool.google_search.search_types.image_search.""" + URL_CONTEXT = 'URL_CONTEXT' + """URL context tool, maps to Tool.url_context.""" + GOOGLE_MAPS = 'GOOGLE_MAPS' + """Google maps tool, maps to Tool.google_maps.""" + FILE_SEARCH = 'FILE_SEARCH' + """File search tool, maps to Tool.file_search.""" + + +class ResourceScope(_common.CaseInSensitiveEnum): + """Resource scope.""" + + COLLECTION = 'COLLECTION' + """When setting base_url, this value configures resource scope to be the collection. + The resource name will not include api version, project, or location. + For example, if base_url is set to "https://aiplatform.googleapis.com", + then the resource name for a Model would be + "https://aiplatform.googleapis.com/publishers/google/models/gemini-3-pro-preview""" + + +class ServiceTier(_common.CaseInSensitiveEnum): + """Pricing and performance service tier.""" + + UNSPECIFIED = 'unspecified' + """Default service tier, which is standard.""" + FLEX = 'flex' + """Flex service tier.""" + STANDARD = 'standard' + """Standard service tier.""" + PRIORITY = 'priority' + """Priority service tier.""" + + +class JSONSchemaType(Enum): + """The type of the data supported by JSON Schema. + + The values of the enums are lower case strings, while the values of the enums + for the Type class are upper case strings. + """ + + NULL = 'null' + BOOLEAN = 'boolean' + OBJECT = 'object' + ARRAY = 'array' + NUMBER = 'number' + INTEGER = 'integer' + STRING = 'string' + + +class FeatureSelectionPreference(_common.CaseInSensitiveEnum): + """Options for feature selection preference.""" + + FEATURE_SELECTION_PREFERENCE_UNSPECIFIED = ( + 'FEATURE_SELECTION_PREFERENCE_UNSPECIFIED' + ) + PRIORITIZE_QUALITY = 'PRIORITIZE_QUALITY' + BALANCED = 'BALANCED' + PRIORITIZE_COST = 'PRIORITIZE_COST' + + +class EmbeddingApiType(_common.CaseInSensitiveEnum): + """Enum representing the Vertex embedding API to use.""" + + PREDICT = 'PREDICT' + """predict API endpoint (default)""" + EMBED_CONTENT = 'EMBED_CONTENT' + """embedContent API Endpoint""" + + +class SafetyFilterLevel(_common.CaseInSensitiveEnum): + """Enum that controls the safety filter level for objectionable content.""" + + BLOCK_LOW_AND_ABOVE = 'BLOCK_LOW_AND_ABOVE' + BLOCK_MEDIUM_AND_ABOVE = 'BLOCK_MEDIUM_AND_ABOVE' + BLOCK_ONLY_HIGH = 'BLOCK_ONLY_HIGH' + BLOCK_NONE = 'BLOCK_NONE' + + +class ImagePromptLanguage(_common.CaseInSensitiveEnum): + """Enum that specifies the language of the text in the prompt.""" + + auto = 'auto' + """Auto-detect the language.""" + en = 'en' + """English""" + ja = 'ja' + """Japanese""" + ko = 'ko' + """Korean""" + hi = 'hi' + """Hindi""" + zh = 'zh' + """Chinese""" + pt = 'pt' + """Portuguese""" + es = 'es' + """Spanish""" + + +class MaskReferenceMode(_common.CaseInSensitiveEnum): + """Enum representing the mask mode of a mask reference image.""" + + MASK_MODE_DEFAULT = 'MASK_MODE_DEFAULT' + MASK_MODE_USER_PROVIDED = 'MASK_MODE_USER_PROVIDED' + MASK_MODE_BACKGROUND = 'MASK_MODE_BACKGROUND' + MASK_MODE_FOREGROUND = 'MASK_MODE_FOREGROUND' + MASK_MODE_SEMANTIC = 'MASK_MODE_SEMANTIC' + + +class ControlReferenceType(_common.CaseInSensitiveEnum): + """Enum representing the control type of a control reference image.""" + + CONTROL_TYPE_DEFAULT = 'CONTROL_TYPE_DEFAULT' + CONTROL_TYPE_CANNY = 'CONTROL_TYPE_CANNY' + CONTROL_TYPE_SCRIBBLE = 'CONTROL_TYPE_SCRIBBLE' + CONTROL_TYPE_FACE_MESH = 'CONTROL_TYPE_FACE_MESH' + + +class SubjectReferenceType(_common.CaseInSensitiveEnum): + """Enum representing the subject type of a subject reference image.""" + + SUBJECT_TYPE_DEFAULT = 'SUBJECT_TYPE_DEFAULT' + SUBJECT_TYPE_PERSON = 'SUBJECT_TYPE_PERSON' + SUBJECT_TYPE_ANIMAL = 'SUBJECT_TYPE_ANIMAL' + SUBJECT_TYPE_PRODUCT = 'SUBJECT_TYPE_PRODUCT' + + +class EditMode(_common.CaseInSensitiveEnum): + """Enum representing the editing mode.""" + + EDIT_MODE_DEFAULT = 'EDIT_MODE_DEFAULT' + EDIT_MODE_INPAINT_REMOVAL = 'EDIT_MODE_INPAINT_REMOVAL' + EDIT_MODE_INPAINT_INSERTION = 'EDIT_MODE_INPAINT_INSERTION' + EDIT_MODE_OUTPAINT = 'EDIT_MODE_OUTPAINT' + EDIT_MODE_CONTROLLED_EDITING = 'EDIT_MODE_CONTROLLED_EDITING' + EDIT_MODE_STYLE = 'EDIT_MODE_STYLE' + EDIT_MODE_BGSWAP = 'EDIT_MODE_BGSWAP' + EDIT_MODE_PRODUCT_IMAGE = 'EDIT_MODE_PRODUCT_IMAGE' + + +class SegmentMode(_common.CaseInSensitiveEnum): + """Enum that represents the segmentation mode.""" + + FOREGROUND = 'FOREGROUND' + BACKGROUND = 'BACKGROUND' + PROMPT = 'PROMPT' + SEMANTIC = 'SEMANTIC' + INTERACTIVE = 'INTERACTIVE' + + +class VideoGenerationReferenceType(_common.CaseInSensitiveEnum): + """Enum for the reference type of a video generation reference image.""" + + ASSET = 'ASSET' + """A reference image that provides assets to the generated video, + such as the scene, an object, a character, etc.""" + STYLE = 'STYLE' + """A reference image that provides aesthetics including colors, + lighting, texture, etc., to be used as the style of the generated video, + such as 'anime', 'photography', 'origami', etc.""" + + +class VideoGenerationMaskMode(_common.CaseInSensitiveEnum): + """Enum for the mask mode of a video generation mask.""" + + INSERT = 'INSERT' + """The image mask contains a masked rectangular region which is + applied on the first frame of the input video. The object described in + the prompt is inserted into this region and will appear in subsequent + frames.""" + REMOVE = 'REMOVE' + """The image mask is used to determine an object in the + first video frame to track. This object is removed from the video.""" + REMOVE_STATIC = 'REMOVE_STATIC' + """The image mask is used to determine a region in the + video. Objects in this region will be removed.""" + OUTPAINT = 'OUTPAINT' + """The image mask contains a masked rectangular region where + the input video will go. The remaining area will be generated. Video + masks are not supported.""" + + +class VideoCompressionQuality(_common.CaseInSensitiveEnum): + """Enum that controls the compression quality of the generated videos.""" + + OPTIMIZED = 'OPTIMIZED' + """Optimized video compression quality. This will produce videos + with a compressed, smaller file size.""" + LOSSLESS = 'LOSSLESS' + """Lossless video compression quality. This will produce videos + with a larger file size.""" + + +class TuningMethod(_common.CaseInSensitiveEnum): + """Enum representing the tuning method.""" + + SUPERVISED_FINE_TUNING = 'SUPERVISED_FINE_TUNING' + """Supervised fine tuning.""" + PREFERENCE_TUNING = 'PREFERENCE_TUNING' + """Preference optimization tuning.""" + DISTILLATION = 'DISTILLATION' + """Distillation tuning.""" + + +class FileState(_common.CaseInSensitiveEnum): + """State for the lifecycle of a File.""" + + STATE_UNSPECIFIED = 'STATE_UNSPECIFIED' + PROCESSING = 'PROCESSING' + ACTIVE = 'ACTIVE' + FAILED = 'FAILED' + + +class FileSource(_common.CaseInSensitiveEnum): + """Source of the File.""" + + SOURCE_UNSPECIFIED = 'SOURCE_UNSPECIFIED' + UPLOADED = 'UPLOADED' + GENERATED = 'GENERATED' + REGISTERED = 'REGISTERED' + + +class TurnCompleteReason(_common.CaseInSensitiveEnum): + """The reason why the turn is complete.""" + + TURN_COMPLETE_REASON_UNSPECIFIED = 'TURN_COMPLETE_REASON_UNSPECIFIED' + """Default value. Reason is unspecified.""" + MALFORMED_FUNCTION_CALL = 'MALFORMED_FUNCTION_CALL' + """The function call generated by the model is invalid.""" + RESPONSE_REJECTED = 'RESPONSE_REJECTED' + """The response is rejected by the model.""" + NEED_MORE_INPUT = 'NEED_MORE_INPUT' + """Needs more input from the user.""" + PROHIBITED_INPUT_CONTENT = 'PROHIBITED_INPUT_CONTENT' + """Input content is prohibited.""" + IMAGE_PROHIBITED_INPUT_CONTENT = 'IMAGE_PROHIBITED_INPUT_CONTENT' + """Input image contains prohibited content.""" + INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED = ( + 'INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED' + ) + """Input text contains prominent person reference.""" + INPUT_IMAGE_CELEBRITY = 'INPUT_IMAGE_CELEBRITY' + """Input image contains celebrity.""" + INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED = ( + 'INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED' + ) + """Input image contains photo realistic child.""" + INPUT_TEXT_NCII_PROHIBITED = 'INPUT_TEXT_NCII_PROHIBITED' + """Input text contains NCII content.""" + INPUT_OTHER = 'INPUT_OTHER' + """Other input safety issue.""" + INPUT_IP_PROHIBITED = 'INPUT_IP_PROHIBITED' + """Input contains IP violation.""" + BLOCKLIST = 'BLOCKLIST' + """Input matched blocklist.""" + UNSAFE_PROMPT_FOR_IMAGE_GENERATION = 'UNSAFE_PROMPT_FOR_IMAGE_GENERATION' + """Input is unsafe for image generation.""" + GENERATED_IMAGE_SAFETY = 'GENERATED_IMAGE_SAFETY' + """Generated image failed safety check.""" + GENERATED_CONTENT_SAFETY = 'GENERATED_CONTENT_SAFETY' + """Generated content failed safety check.""" + GENERATED_AUDIO_SAFETY = 'GENERATED_AUDIO_SAFETY' + """Generated audio failed safety check.""" + GENERATED_VIDEO_SAFETY = 'GENERATED_VIDEO_SAFETY' + """Generated video failed safety check.""" + GENERATED_CONTENT_PROHIBITED = 'GENERATED_CONTENT_PROHIBITED' + """Generated content is prohibited.""" + GENERATED_CONTENT_BLOCKLIST = 'GENERATED_CONTENT_BLOCKLIST' + """Generated content matched blocklist.""" + GENERATED_IMAGE_PROHIBITED = 'GENERATED_IMAGE_PROHIBITED' + """Generated image is prohibited.""" + GENERATED_IMAGE_CELEBRITY = 'GENERATED_IMAGE_CELEBRITY' + """Generated image contains celebrity.""" + GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER = ( + 'GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER' + ) + """Generated image contains prominent people detected by rewriter.""" + GENERATED_IMAGE_IDENTIFIABLE_PEOPLE = 'GENERATED_IMAGE_IDENTIFIABLE_PEOPLE' + """Generated image contains identifiable people.""" + GENERATED_IMAGE_MINORS = 'GENERATED_IMAGE_MINORS' + """Generated image contains minors.""" + OUTPUT_IMAGE_IP_PROHIBITED = 'OUTPUT_IMAGE_IP_PROHIBITED' + """Generated image contains IP violation.""" + GENERATED_OTHER = 'GENERATED_OTHER' + """Other generated content issue.""" + MAX_REGENERATION_REACHED = 'MAX_REGENERATION_REACHED' + """Max regeneration attempts reached.""" + + +class MediaModality(_common.CaseInSensitiveEnum): + """Server content modalities.""" + + MODALITY_UNSPECIFIED = 'MODALITY_UNSPECIFIED' + """The modality is unspecified.""" + TEXT = 'TEXT' + """Plain text.""" + IMAGE = 'IMAGE' + """Images.""" + VIDEO = 'VIDEO' + """Video.""" + AUDIO = 'AUDIO' + """Audio.""" + DOCUMENT = 'DOCUMENT' + """Document, e.g. PDF.""" + + +class VadSignalType(_common.CaseInSensitiveEnum): + """The type of the VAD signal.""" + + VAD_SIGNAL_TYPE_UNSPECIFIED = 'VAD_SIGNAL_TYPE_UNSPECIFIED' + """The default is VAD_SIGNAL_TYPE_UNSPECIFIED.""" + VAD_SIGNAL_TYPE_SOS = 'VAD_SIGNAL_TYPE_SOS' + """Start of sentence signal.""" + VAD_SIGNAL_TYPE_EOS = 'VAD_SIGNAL_TYPE_EOS' + """End of sentence signal.""" + + +class VoiceActivityType(_common.CaseInSensitiveEnum): + """The type of the voice activity signal.""" + + TYPE_UNSPECIFIED = 'TYPE_UNSPECIFIED' + """The default is VOICE_ACTIVITY_TYPE_UNSPECIFIED.""" + ACTIVITY_START = 'ACTIVITY_START' + """Start of sentence signal.""" + ACTIVITY_END = 'ACTIVITY_END' + """End of sentence signal.""" + + +class StartSensitivity(_common.CaseInSensitiveEnum): + """Start of speech sensitivity.""" + + START_SENSITIVITY_UNSPECIFIED = 'START_SENSITIVITY_UNSPECIFIED' + """The default is START_SENSITIVITY_LOW.""" + START_SENSITIVITY_HIGH = 'START_SENSITIVITY_HIGH' + """Automatic detection will detect the start of speech more often.""" + START_SENSITIVITY_LOW = 'START_SENSITIVITY_LOW' + """Automatic detection will detect the start of speech less often.""" + + +class EndSensitivity(_common.CaseInSensitiveEnum): + """End of speech sensitivity.""" + + END_SENSITIVITY_UNSPECIFIED = 'END_SENSITIVITY_UNSPECIFIED' + """The default is END_SENSITIVITY_LOW.""" + END_SENSITIVITY_HIGH = 'END_SENSITIVITY_HIGH' + """Automatic detection ends speech more often.""" + END_SENSITIVITY_LOW = 'END_SENSITIVITY_LOW' + """Automatic detection ends speech less often.""" + + +class ActivityHandling(_common.CaseInSensitiveEnum): + """The different ways of handling user activity.""" + + ACTIVITY_HANDLING_UNSPECIFIED = 'ACTIVITY_HANDLING_UNSPECIFIED' + """If unspecified, the default behavior is `START_OF_ACTIVITY_INTERRUPTS`.""" + START_OF_ACTIVITY_INTERRUPTS = 'START_OF_ACTIVITY_INTERRUPTS' + """If true, start of activity will interrupt the model's response (also called "barge in"). The model's current response will be cut-off in the moment of the interruption. This is the default behavior.""" + NO_INTERRUPTION = 'NO_INTERRUPTION' + """The model's response will not be interrupted.""" + + +class TurnCoverage(_common.CaseInSensitiveEnum): + """Options about which input is included in the user's turn.""" + + TURN_COVERAGE_UNSPECIFIED = 'TURN_COVERAGE_UNSPECIFIED' + """If unspecified, the default behavior is `TURN_INCLUDES_ONLY_ACTIVITY`.""" + TURN_INCLUDES_ONLY_ACTIVITY = 'TURN_INCLUDES_ONLY_ACTIVITY' + """The users turn only includes activity since the last turn, excluding inactivity (e.g. silence on the audio stream). This is the default behavior.""" + TURN_INCLUDES_ALL_INPUT = 'TURN_INCLUDES_ALL_INPUT' + """The users turn includes all realtime input since the last turn, including inactivity (e.g. silence on the audio stream).""" + TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO = ( + 'TURN_INCLUDES_AUDIO_ACTIVITY_AND_ALL_VIDEO' + ) + """Includes audio activity and all video since the last turn. With automatic activity detection, audio activity means speech and excludes silence.""" + + +class Scale(_common.CaseInSensitiveEnum): + """Scale of the generated music.""" + + SCALE_UNSPECIFIED = 'SCALE_UNSPECIFIED' + """Default value. This value is unused.""" + C_MAJOR_A_MINOR = 'C_MAJOR_A_MINOR' + """C major or A minor.""" + D_FLAT_MAJOR_B_FLAT_MINOR = 'D_FLAT_MAJOR_B_FLAT_MINOR' + """Db major or Bb minor.""" + D_MAJOR_B_MINOR = 'D_MAJOR_B_MINOR' + """D major or B minor.""" + E_FLAT_MAJOR_C_MINOR = 'E_FLAT_MAJOR_C_MINOR' + """Eb major or C minor""" + E_MAJOR_D_FLAT_MINOR = 'E_MAJOR_D_FLAT_MINOR' + """E major or Db minor.""" + F_MAJOR_D_MINOR = 'F_MAJOR_D_MINOR' + """F major or D minor.""" + G_FLAT_MAJOR_E_FLAT_MINOR = 'G_FLAT_MAJOR_E_FLAT_MINOR' + """Gb major or Eb minor.""" + G_MAJOR_E_MINOR = 'G_MAJOR_E_MINOR' + """G major or E minor.""" + A_FLAT_MAJOR_F_MINOR = 'A_FLAT_MAJOR_F_MINOR' + """Ab major or F minor.""" + A_MAJOR_G_FLAT_MINOR = 'A_MAJOR_G_FLAT_MINOR' + """A major or Gb minor.""" + B_FLAT_MAJOR_G_MINOR = 'B_FLAT_MAJOR_G_MINOR' + """Bb major or G minor.""" + B_MAJOR_A_FLAT_MINOR = 'B_MAJOR_A_FLAT_MINOR' + """B major or Ab minor.""" + + +class MusicGenerationMode(_common.CaseInSensitiveEnum): + """The mode of music generation.""" + + MUSIC_GENERATION_MODE_UNSPECIFIED = 'MUSIC_GENERATION_MODE_UNSPECIFIED' + """Rely on the server default generation mode.""" + QUALITY = 'QUALITY' + """Steer text prompts to regions of latent space with higher quality + music.""" + DIVERSITY = 'DIVERSITY' + """Steer text prompts to regions of latent space with a larger + diversity of music.""" + VOCALIZATION = 'VOCALIZATION' + """Steer text prompts to regions of latent space more likely to + generate music with vocals.""" + + +class LiveMusicPlaybackControl(_common.CaseInSensitiveEnum): + """The playback control signal to apply to the music generation.""" + + PLAYBACK_CONTROL_UNSPECIFIED = 'PLAYBACK_CONTROL_UNSPECIFIED' + """This value is unused.""" + PLAY = 'PLAY' + """Start generating the music.""" + PAUSE = 'PAUSE' + """Hold the music generation. Use PLAY to resume from the current position.""" + STOP = 'STOP' + """Stop the music generation and reset the context (prompts retained). + Use PLAY to restart the music generation.""" + RESET_CONTEXT = 'RESET_CONTEXT' + """Reset the context of the music generation without stopping it. + Retains the current prompts and config.""" + + +class ExecutableCode(_common.BaseModel): + """Model-generated code executed server-side, results returned to the model. + + Only generated when using the `CodeExecution` tool, in which the code will + be automatically executed, and a corresponding `CodeExecutionResult` will + also be generated. + """ + + code: Optional[str] = Field( + default=None, description="""Required. The code to be executed.""" + ) + language: Optional[Language] = Field( + default=None, + description="""Required. Programming language of the `code`.""", + ) + id: Optional[str] = Field( + default=None, + description="""Unique identifier of the `ExecutableCode` part. The server returns the `CodeExecutionResult` with the matching `id`.""", + ) + + +class ExecutableCodeDict(TypedDict, total=False): + """Model-generated code executed server-side, results returned to the model. + + Only generated when using the `CodeExecution` tool, in which the code will + be automatically executed, and a corresponding `CodeExecutionResult` will + also be generated. + """ + + code: Optional[str] + """Required. The code to be executed.""" + + language: Optional[Language] + """Required. Programming language of the `code`.""" + + id: Optional[str] + """Unique identifier of the `ExecutableCode` part. The server returns the `CodeExecutionResult` with the matching `id`.""" + + +ExecutableCodeOrDict = Union[ExecutableCode, ExecutableCodeDict] + + +class CodeExecutionResult(_common.BaseModel): + """Result of executing the `ExecutableCode`. + + Generated only when the `CodeExecution` tool is used. + """ + + outcome: Optional[Outcome] = Field( + default=None, description="""Required. Outcome of the code execution.""" + ) + output: Optional[str] = Field( + default=None, + description="""Optional. Contains stdout when code execution is successful, stderr or other description otherwise.""", + ) + id: Optional[str] = Field( + default=None, + description="""The identifier of the `ExecutableCode` part this result is for. Only populated if the corresponding `ExecutableCode` has an id.""", + ) + + +class CodeExecutionResultDict(TypedDict, total=False): + """Result of executing the `ExecutableCode`. + + Generated only when the `CodeExecution` tool is used. + """ + + outcome: Optional[Outcome] + """Required. Outcome of the code execution.""" + + output: Optional[str] + """Optional. Contains stdout when code execution is successful, stderr or other description otherwise.""" + + id: Optional[str] + """The identifier of the `ExecutableCode` part this result is for. Only populated if the corresponding `ExecutableCode` has an id.""" + + +CodeExecutionResultOrDict = Union[CodeExecutionResult, CodeExecutionResultDict] + + +class PartMediaResolution(_common.BaseModel): + """Media resolution for the input media.""" + + level: Optional[PartMediaResolutionLevel] = Field( + default=None, + description="""The tokenization quality used for given media. + """, + ) + num_tokens: Optional[int] = Field( + default=None, + description="""Specifies the required sequence length for media tokenization. + """, + ) + + +class PartMediaResolutionDict(TypedDict, total=False): + """Media resolution for the input media.""" + + level: Optional[PartMediaResolutionLevel] + """The tokenization quality used for given media. + """ + + num_tokens: Optional[int] + """Specifies the required sequence length for media tokenization. + """ + + +PartMediaResolutionOrDict = Union[PartMediaResolution, PartMediaResolutionDict] + + +class ToolCall(_common.BaseModel): + """A predicted server-side `ToolCall` returned from the model. + + This message contains information about a tool that the model wants to invoke. + The client is NOT expected to execute this `ToolCall`. Instead, the + client should pass this `ToolCall` back to the API in a subsequent turn + within a `Content` message, along with the corresponding `ToolResponse`. + """ + + id: Optional[str] = Field( + default=None, + description="""Unique identifier of the tool call. The server returns the tool response with the matching `id`.""", + ) + tool_type: Optional[ToolType] = Field( + default=None, description="""The type of tool that was called.""" + ) + args: Optional[dict[str, Any]] = Field( + default=None, + description="""The tool call arguments. Example: {"arg1": "value1", "arg2": "value2"}.""", + ) + + +class ToolCallDict(TypedDict, total=False): + """A predicted server-side `ToolCall` returned from the model. + + This message contains information about a tool that the model wants to invoke. + The client is NOT expected to execute this `ToolCall`. Instead, the + client should pass this `ToolCall` back to the API in a subsequent turn + within a `Content` message, along with the corresponding `ToolResponse`. + """ + + id: Optional[str] + """Unique identifier of the tool call. The server returns the tool response with the matching `id`.""" + + tool_type: Optional[ToolType] + """The type of tool that was called.""" + + args: Optional[dict[str, Any]] + """The tool call arguments. Example: {"arg1": "value1", "arg2": "value2"}.""" + + +ToolCallOrDict = Union[ToolCall, ToolCallDict] + + +class ToolResponse(_common.BaseModel): + """The output from a server-side `ToolCall` execution. + + This message contains the results of a tool invocation that was initiated by a + `ToolCall` from the model. The client should pass this `ToolResponse` back to + the API in a subsequent turn within a `Content` message, along with the + corresponding `ToolCall`. + """ + + id: Optional[str] = Field( + default=None, + description="""The identifier of the tool call this response is for.""", + ) + tool_type: Optional[ToolType] = Field( + default=None, + description="""The type of tool that was called, matching the tool_type in the corresponding ToolCall.""", + ) + response: Optional[dict[str, Any]] = Field( + default=None, description="""The tool response.""" + ) + + +class ToolResponseDict(TypedDict, total=False): + """The output from a server-side `ToolCall` execution. + + This message contains the results of a tool invocation that was initiated by a + `ToolCall` from the model. The client should pass this `ToolResponse` back to + the API in a subsequent turn within a `Content` message, along with the + corresponding `ToolCall`. + """ + + id: Optional[str] + """The identifier of the tool call this response is for.""" + + tool_type: Optional[ToolType] + """The type of tool that was called, matching the tool_type in the corresponding ToolCall.""" + + response: Optional[dict[str, Any]] + """The tool response.""" + + +ToolResponseOrDict = Union[ToolResponse, ToolResponseDict] + + +class FileData(_common.BaseModel): + """URI-based data. + + A FileData message contains a URI pointing to data of a specific media type. + It is used to represent images, audio, and video stored in Google Cloud + Storage. + """ + + display_name: Optional[str] = Field( + default=None, + description="""Optional. The display name of the file. Used to provide a label or filename to distinguish files. This field is only returned in `PromptMessage` for prompt management. It is used in the Gemini calls only when server side tools (`code_execution`, `google_search`, and `url_context`) are enabled. This field is not supported in Gemini API.""", + ) + file_uri: Optional[str] = Field( + default=None, + description="""Required. The URI of the file in Google Cloud Storage.""", + ) + mime_type: Optional[str] = Field( + default=None, + description="""Required. The IANA standard MIME type of the source data.""", + ) + + +class FileDataDict(TypedDict, total=False): + """URI-based data. + + A FileData message contains a URI pointing to data of a specific media type. + It is used to represent images, audio, and video stored in Google Cloud + Storage. + """ + + display_name: Optional[str] + """Optional. The display name of the file. Used to provide a label or filename to distinguish files. This field is only returned in `PromptMessage` for prompt management. It is used in the Gemini calls only when server side tools (`code_execution`, `google_search`, and `url_context`) are enabled. This field is not supported in Gemini API.""" + + file_uri: Optional[str] + """Required. The URI of the file in Google Cloud Storage.""" + + mime_type: Optional[str] + """Required. The IANA standard MIME type of the source data.""" + + +FileDataOrDict = Union[FileData, FileDataDict] + + +class PartialArg(_common.BaseModel): + """Partial argument value of the function call. + + This data type is not supported in Gemini API. + """ + + bool_value: Optional[bool] = Field( + default=None, description="""Optional. Represents a boolean value.""" + ) + json_path: Optional[str] = Field( + default=None, + description="""Required. A JSON Path (RFC 9535) to the argument being streamed. https://datatracker.ietf.org/doc/html/rfc9535. e.g. "$.foo.bar[0].data".""", + ) + null_value: Optional[Literal['NULL_VALUE']] = Field( + default=None, description="""Optional. Represents a null value.""" + ) + number_value: Optional[float] = Field( + default=None, description="""Optional. Represents a double value.""" + ) + string_value: Optional[str] = Field( + default=None, description="""Optional. Represents a string value.""" + ) + will_continue: Optional[bool] = Field( + default=None, + description="""Optional. Whether this is not the last part of the same json_path. If true, another PartialArg message for the current json_path is expected to follow.""", + ) + + +class PartialArgDict(TypedDict, total=False): + """Partial argument value of the function call. + + This data type is not supported in Gemini API. + """ + + bool_value: Optional[bool] + """Optional. Represents a boolean value.""" + + json_path: Optional[str] + """Required. A JSON Path (RFC 9535) to the argument being streamed. https://datatracker.ietf.org/doc/html/rfc9535. e.g. "$.foo.bar[0].data".""" + + null_value: Optional[Literal['NULL_VALUE']] + """Optional. Represents a null value.""" + + number_value: Optional[float] + """Optional. Represents a double value.""" + + string_value: Optional[str] + """Optional. Represents a string value.""" + + will_continue: Optional[bool] + """Optional. Whether this is not the last part of the same json_path. If true, another PartialArg message for the current json_path is expected to follow.""" + + +PartialArgOrDict = Union[PartialArg, PartialArgDict] + + +class FunctionCall(_common.BaseModel): + """A function call.""" + + id: Optional[str] = Field( + default=None, + description="""The unique id of the function call. If populated, the client to execute the + `function_call` and return the response with the matching `id`.""", + ) + args: Optional[dict[str, Any]] = Field( + default=None, + description="""Optional. The function parameters and values in JSON object format. See [FunctionDeclaration.parameters] for parameter details.""", + ) + name: Optional[str] = Field( + default=None, + description="""Optional. The name of the function to call. Matches [FunctionDeclaration.name].""", + ) + partial_args: Optional[list[PartialArg]] = Field( + default=None, + description="""Optional. The partial argument value of the function call. If provided, represents the arguments/fields that are streamed incrementally. This field is not supported in Gemini API.""", + ) + will_continue: Optional[bool] = Field( + default=None, + description="""Optional. Whether this is the last part of the FunctionCall. If true, another partial message for the current FunctionCall is expected to follow. This field is not supported in Gemini API.""", + ) + + +class FunctionCallDict(TypedDict, total=False): + """A function call.""" + + id: Optional[str] + """The unique id of the function call. If populated, the client to execute the + `function_call` and return the response with the matching `id`.""" + + args: Optional[dict[str, Any]] + """Optional. The function parameters and values in JSON object format. See [FunctionDeclaration.parameters] for parameter details.""" + + name: Optional[str] + """Optional. The name of the function to call. Matches [FunctionDeclaration.name].""" + + partial_args: Optional[list[PartialArgDict]] + """Optional. The partial argument value of the function call. If provided, represents the arguments/fields that are streamed incrementally. This field is not supported in Gemini API.""" + + will_continue: Optional[bool] + """Optional. Whether this is the last part of the FunctionCall. If true, another partial message for the current FunctionCall is expected to follow. This field is not supported in Gemini API.""" + + +FunctionCallOrDict = Union[FunctionCall, FunctionCallDict] + + +class FunctionResponseBlob(_common.BaseModel): + """Raw media bytes for function response. + + Text should not be sent as raw bytes, use the FunctionResponse.response + field. + """ + + mime_type: Optional[str] = Field( + default=None, + description="""Required. The IANA standard MIME type of the source data.""", + ) + data: Optional[bytes] = Field( + default=None, description="""Required. Inline media bytes.""" + ) + display_name: Optional[str] = Field( + default=None, + description="""Optional. Display name of the blob. + Used to provide a label or filename to distinguish blobs.""", + ) + + +class FunctionResponseBlobDict(TypedDict, total=False): + """Raw media bytes for function response. + + Text should not be sent as raw bytes, use the FunctionResponse.response + field. + """ + + mime_type: Optional[str] + """Required. The IANA standard MIME type of the source data.""" + + data: Optional[bytes] + """Required. Inline media bytes.""" + + display_name: Optional[str] + """Optional. Display name of the blob. + Used to provide a label or filename to distinguish blobs.""" + + +FunctionResponseBlobOrDict = Union[ + FunctionResponseBlob, FunctionResponseBlobDict +] + + +class FunctionResponseFileData(_common.BaseModel): + """URI based data for function response.""" + + file_uri: Optional[str] = Field( + default=None, description="""Required. URI.""" + ) + mime_type: Optional[str] = Field( + default=None, + description="""Required. The IANA standard MIME type of the source data.""", + ) + display_name: Optional[str] = Field( + default=None, + description="""Optional. Display name of the file. + Used to provide a label or filename to distinguish files.""", + ) + + +class FunctionResponseFileDataDict(TypedDict, total=False): + """URI based data for function response.""" + + file_uri: Optional[str] + """Required. URI.""" + + mime_type: Optional[str] + """Required. The IANA standard MIME type of the source data.""" + + display_name: Optional[str] + """Optional. Display name of the file. + Used to provide a label or filename to distinguish files.""" + + +FunctionResponseFileDataOrDict = Union[ + FunctionResponseFileData, FunctionResponseFileDataDict +] + + +class FunctionResponsePart(_common.BaseModel): + """A datatype containing media that is part of a `FunctionResponse` message. + + A `FunctionResponsePart` consists of data which has an associated datatype. A + `FunctionResponsePart` can only contain one of the accepted types in + `FunctionResponsePart.data`. + + A `FunctionResponsePart` must have a fixed IANA MIME type identifying the + type and subtype of the media if the `inline_data` field is filled with raw + bytes. + """ + + inline_data: Optional[FunctionResponseBlob] = Field( + default=None, description="""Optional. Inline media bytes.""" + ) + file_data: Optional[FunctionResponseFileData] = Field( + default=None, description="""Optional. URI based data.""" + ) + + @classmethod + def from_bytes(cls, *, data: bytes, mime_type: str) -> 'FunctionResponsePart': + """Creates a FunctionResponsePart from bytes and mime type. + + Args: + data (bytes): The bytes of the data + mime_type (str): mime_type: The MIME type of the data. + """ + inline_data = FunctionResponseBlob( + data=data, + mime_type=mime_type, + ) + return cls(inline_data=inline_data) + + @classmethod + def from_uri( + cls, *, file_uri: str, mime_type: Optional[str] = None + ) -> 'FunctionResponsePart': + """Creates a FunctionResponsePart from a file uri. + + Args: + file_uri (str): The uri of the file + mime_type (str): mime_type: The MIME type of the file. If not provided, + the MIME type will be automatically determined. + """ + if mime_type is None: + import mimetypes + + mime_type, _ = mimetypes.guess_type(file_uri) + if not mime_type: + raise ValueError(f'Failed to determine mime type for file: {file_uri}') + file_data = FunctionResponseFileData(file_uri=file_uri, mime_type=mime_type) + return cls(file_data=file_data) + + +class FunctionResponsePartDict(TypedDict, total=False): + """A datatype containing media that is part of a `FunctionResponse` message. + + A `FunctionResponsePart` consists of data which has an associated datatype. A + `FunctionResponsePart` can only contain one of the accepted types in + `FunctionResponsePart.data`. + + A `FunctionResponsePart` must have a fixed IANA MIME type identifying the + type and subtype of the media if the `inline_data` field is filled with raw + bytes. + """ + + inline_data: Optional[FunctionResponseBlobDict] + """Optional. Inline media bytes.""" + + file_data: Optional[FunctionResponseFileDataDict] + """Optional. URI based data.""" + + +FunctionResponsePartOrDict = Union[ + FunctionResponsePart, FunctionResponsePartDict +] + + +class FunctionResponse(_common.BaseModel): + """A function response.""" + + will_continue: Optional[bool] = Field( + default=None, + description="""Signals that function call continues, and more responses will be returned, turning the function call into a generator. Is only applicable to NON_BLOCKING function calls (see FunctionDeclaration.behavior for details), ignored otherwise. If false, the default, future responses will not be considered. Is only applicable to NON_BLOCKING function calls, is ignored otherwise. If set to false, future responses will not be considered. It is allowed to return empty `response` with `will_continue=False` to signal that the function call is finished.""", + ) + scheduling: Optional[FunctionResponseScheduling] = Field( + default=None, + description="""Specifies how the response should be scheduled in the conversation. Only applicable to NON_BLOCKING function calls, is ignored otherwise. Defaults to WHEN_IDLE.""", + ) + parts: Optional[list[FunctionResponsePart]] = Field( + default=None, + description="""List of parts that constitute a function response. Each part may + have a different IANA MIME type.""", + ) + id: Optional[str] = Field( + default=None, + description="""Optional. The id of the function call this response is for. Populated by the client to match the corresponding function call `id`.""", + ) + name: Optional[str] = Field( + default=None, + description="""Required. The name of the function to call. Matches [FunctionDeclaration.name] and [FunctionCall.name].""", + ) + response: Optional[dict[str, Any]] = Field( + default=None, + description="""Required. The function response in JSON object format. Use "output" key to specify function output and "error" key to specify error details (if any). If "output" and "error" keys are not specified, then whole "response" is treated as function output.""", + ) + + @classmethod + def from_mcp_response( + cls, *, name: str, response: McpCallToolResult + ) -> 'FunctionResponse': + if not _is_mcp_imported: + raise ValueError( + 'MCP response is not supported. Please ensure that the MCP library is' + ' imported.' + ) + + if response.isError: + return cls(name=name, response={'error': 'MCP response is error.'}) + else: + return cls(name=name, response={'result': response.content}) + + +class FunctionResponseDict(TypedDict, total=False): + """A function response.""" + + will_continue: Optional[bool] + """Signals that function call continues, and more responses will be returned, turning the function call into a generator. Is only applicable to NON_BLOCKING function calls (see FunctionDeclaration.behavior for details), ignored otherwise. If false, the default, future responses will not be considered. Is only applicable to NON_BLOCKING function calls, is ignored otherwise. If set to false, future responses will not be considered. It is allowed to return empty `response` with `will_continue=False` to signal that the function call is finished.""" + + scheduling: Optional[FunctionResponseScheduling] + """Specifies how the response should be scheduled in the conversation. Only applicable to NON_BLOCKING function calls, is ignored otherwise. Defaults to WHEN_IDLE.""" + + parts: Optional[list[FunctionResponsePartDict]] + """List of parts that constitute a function response. Each part may + have a different IANA MIME type.""" + + id: Optional[str] + """Optional. The id of the function call this response is for. Populated by the client to match the corresponding function call `id`.""" + + name: Optional[str] + """Required. The name of the function to call. Matches [FunctionDeclaration.name] and [FunctionCall.name].""" + + response: Optional[dict[str, Any]] + """Required. The function response in JSON object format. Use "output" key to specify function output and "error" key to specify error details (if any). If "output" and "error" keys are not specified, then whole "response" is treated as function output.""" + + +FunctionResponseOrDict = Union[FunctionResponse, FunctionResponseDict] + + +class Blob(_common.BaseModel): + """A content blob. + + A Blob contains data of a specific media type. It is used to represent images, + audio, and video. + """ + + data: Optional[bytes] = Field( + default=None, description="""Required. The raw bytes of the data.""" + ) + display_name: Optional[str] = Field( + default=None, + description="""Optional. The display name of the blob. Used to provide a label or filename to distinguish blobs. This field is only returned in `PromptMessage` for prompt management. It is used in the Gemini calls only when server-side tools (`code_execution`, `google_search`, and `url_context`) are enabled. This field is not supported in Gemini API.""", + ) + mime_type: Optional[str] = Field( + default=None, + description="""Required. The IANA standard MIME type of the source data.""", + ) + + def as_image(self) -> Optional['Image']: + """Returns the Blob as a Image, or None if the Blob is not an image.""" + if ( + not self.data + or not self.mime_type + or not self.mime_type.startswith('image/') + ): + return None + return Image( + image_bytes=self.data, + mime_type=self.mime_type, + ) + + +class BlobDict(TypedDict, total=False): + """A content blob. + + A Blob contains data of a specific media type. It is used to represent images, + audio, and video. + """ + + data: Optional[bytes] + """Required. The raw bytes of the data.""" + + display_name: Optional[str] + """Optional. The display name of the blob. Used to provide a label or filename to distinguish blobs. This field is only returned in `PromptMessage` for prompt management. It is used in the Gemini calls only when server-side tools (`code_execution`, `google_search`, and `url_context`) are enabled. This field is not supported in Gemini API.""" + + mime_type: Optional[str] + """Required. The IANA standard MIME type of the source data.""" + + +BlobOrDict = Union[Blob, BlobDict] + + +class VideoMetadata(_common.BaseModel): + """Provides metadata for a video, including the start and end offsets for clipping and the frame rate.""" + + end_offset: Optional[str] = Field( + default=None, description="""Optional. The end offset of the video.""" + ) + fps: Optional[float] = Field( + default=None, + description="""Optional. The frame rate of the video sent to the model. If not specified, the default value is 1.0. The valid range is (0.0, 24.0].""", + ) + start_offset: Optional[str] = Field( + default=None, description="""Optional. The start offset of the video.""" + ) + + +class VideoMetadataDict(TypedDict, total=False): + """Provides metadata for a video, including the start and end offsets for clipping and the frame rate.""" + + end_offset: Optional[str] + """Optional. The end offset of the video.""" + + fps: Optional[float] + """Optional. The frame rate of the video sent to the model. If not specified, the default value is 1.0. The valid range is (0.0, 24.0].""" + + start_offset: Optional[str] + """Optional. The start offset of the video.""" + + +VideoMetadataOrDict = Union[VideoMetadata, VideoMetadataDict] + + +class Part(_common.BaseModel): + """A datatype containing media content. + + Exactly one field within a Part should be set, representing the specific type + of content being conveyed. Using multiple fields within the same `Part` + instance is considered invalid. + """ + + media_resolution: Optional[PartMediaResolution] = Field( + default=None, + description="""Media resolution for the input media. + """, + ) + code_execution_result: Optional[CodeExecutionResult] = Field( + default=None, + description="""Optional. The result of executing the ExecutableCode.""", + ) + executable_code: Optional[ExecutableCode] = Field( + default=None, + description="""Optional. Code generated by the model that is intended to be executed.""", + ) + file_data: Optional[FileData] = Field( + default=None, + description="""Optional. The URI-based data of the part. This can be used to include files from Google Cloud Storage.""", + ) + function_call: Optional[FunctionCall] = Field( + default=None, + description="""Optional. A predicted function call returned from the model. This contains the name of the function to call and the arguments to pass to the function.""", + ) + function_response: Optional[FunctionResponse] = Field( + default=None, + description="""Optional. The result of a function call. This is used to provide the model with the result of a function call that it predicted.""", + ) + inline_data: Optional[Blob] = Field( + default=None, + description="""Optional. The inline data content of the part. This can be used to include images, audio, or video in a request.""", + ) + text: Optional[str] = Field( + default=None, + description="""Optional. The text content of the part. When sent from the VSCode Gemini Code Assist extension, references to @mentioned items will be converted to markdown boldface text. For example `@my-repo` will be converted to and sent as `**my-repo**` by the IDE agent.""", + ) + thought: Optional[bool] = Field( + default=None, + description="""Optional. Indicates whether the `part` represents the model's thought process or reasoning.""", + ) + thought_signature: Optional[bytes] = Field( + default=None, + description="""Optional. An opaque signature for the thought so it can be reused in subsequent requests.""", + ) + video_metadata: Optional[VideoMetadata] = Field( + default=None, + description="""Optional. Video metadata. The metadata should only be specified while the video data is presented in inline_data or file_data.""", + ) + tool_call: Optional[ToolCall] = Field( + default=None, + description="""Server-side tool call. This field is populated when the model predicts a tool invocation that should be executed on the server. The client is expected to echo this message back to the API.""", + ) + tool_response: Optional[ToolResponse] = Field( + default=None, + description="""The output from a server-side ToolCall execution. This field is populated by the client with the results of executing the corresponding ToolCall.""", + ) + part_metadata: Optional[dict[str, Any]] = Field( + default=None, + description="""Custom metadata associated with the Part. Agents using genai.Part as content representation may need to keep track of the additional information. For example it can be name of a file/source from which the Part originates or a way to multiplex multiple Part streams. This field is not supported in Vertex AI.""", + ) + + def __init__( + self, + value: Optional['PartUnionDict'] = None, + /, + *, + video_metadata: Optional[VideoMetadata] = None, + thought: Optional[bool] = None, + inline_data: Optional[Blob] = None, + file_data: Optional[FileData] = None, + thought_signature: Optional[bytes] = None, + function_call: Optional[FunctionCall] = None, + code_execution_result: Optional[CodeExecutionResult] = None, + executable_code: Optional[ExecutableCode] = None, + function_response: Optional[FunctionResponse] = None, + text: Optional[str] = None, + # Pydantic allows CamelCase in addition to snake_case attribute + # names. kwargs here catch these aliases. + **kwargs: Any, + ): + part_dict = dict( + video_metadata=video_metadata, + thought=thought, + inline_data=inline_data, + file_data=file_data, + thought_signature=thought_signature, + function_call=function_call, + code_execution_result=code_execution_result, + executable_code=executable_code, + function_response=function_response, + text=text, + ) + part_dict = {k: v for k, v in part_dict.items() if v is not None} + + if part_dict and value is not None: + raise ValueError( + 'Positional and keyword arguments can not be combined when ' + 'initializing a Part.' + ) + + if value is None: + pass + elif isinstance(value, str): + part_dict['text'] = value + elif isinstance(value, File): + if not value.uri or not value.mime_type: + raise ValueError('file uri and mime_type are required.') + part_dict['file_data'] = FileData( + file_uri=value.uri, + mime_type=value.mime_type, + display_name=value.display_name, + ) + elif isinstance(value, dict): + try: + Part.model_validate(value) + part_dict.update(value) # type: ignore[arg-type] + except pydantic.ValidationError: + part_dict['file_data'] = FileData.model_validate(value) + elif isinstance(value, Part): + part_dict.update(value.dict()) + elif 'image' in value.__class__.__name__.lower(): + # PIL.Image case. + + suffix = value.format.lower() if value.format else 'jpeg' + mimetype = f'image/{suffix}' + bytes_io = io.BytesIO() + value.save(bytes_io, suffix.upper()) + + part_dict['inline_data'] = Blob( + data=bytes_io.getvalue(), mime_type=mimetype + ) + else: + raise ValueError(f'Unsupported content part type: {type(value)}') + + super().__init__(**part_dict, **kwargs) + + def as_image(self) -> Optional['Image']: + """Returns the part as a PIL Image, or None if the part is not an image.""" + if not self.inline_data: + return None + return self.inline_data.as_image() + + @classmethod + def _t_part_media_resolution( + cls, + part_media_resolution: Union[ + 'PartMediaResolutionOrDict', 'PartMediaResolutionLevel', str + ], + ) -> PartMediaResolution: + if isinstance(part_media_resolution, str): + part_media_resolution = PartMediaResolution(level=part_media_resolution) + elif isinstance(part_media_resolution, PartMediaResolutionLevel): + part_media_resolution = PartMediaResolution(level=part_media_resolution) + elif isinstance(part_media_resolution, dict): + part_media_resolution = PartMediaResolution(**part_media_resolution) + + return part_media_resolution + + @classmethod + def from_uri( + cls, + *, + file_uri: str, + mime_type: Optional[str] = None, + media_resolution: Optional[ + Union['PartMediaResolutionOrDict', 'PartMediaResolutionLevel', str] + ] = None, + ) -> 'Part': + """Creates a Part from a file uri. + + Args: + file_uri (str): The uri of the file + mime_type (str): mime_type: The MIME type of the file. If not provided, + the MIME type will be automatically determined. + """ + if mime_type is None: + import mimetypes + + mime_type, _ = mimetypes.guess_type(file_uri) + if not mime_type: + raise ValueError(f'Failed to determine mime type for file: {file_uri}') + if media_resolution is not None: + media_resolution = cls._t_part_media_resolution(media_resolution) + file_data = FileData(file_uri=file_uri, mime_type=mime_type) + return cls(file_data=file_data, media_resolution=media_resolution) + + @classmethod + def from_text(cls, *, text: str) -> 'Part': + return cls(text=text) + + @classmethod + def from_bytes( + cls, + *, + data: bytes, + mime_type: str, + media_resolution: Optional[ + Union['PartMediaResolutionOrDict', 'PartMediaResolutionLevel', str] + ] = None, + ) -> 'Part': + inline_data = Blob( + data=data, + mime_type=mime_type, + ) + if media_resolution is not None: + media_resolution = cls._t_part_media_resolution(media_resolution) + + return cls(inline_data=inline_data, media_resolution=media_resolution) + + @classmethod + def from_function_call(cls, *, name: str, args: dict[str, Any]) -> 'Part': + function_call = FunctionCall(name=name, args=args) + return cls(function_call=function_call) + + @classmethod + def from_function_response( + cls, + *, + name: str, + response: dict[str, Any], + parts: Optional[list[FunctionResponsePart]] = None, + ) -> 'Part': + function_response = FunctionResponse( + name=name, response=response, parts=parts + ) + return cls(function_response=function_response) + + @classmethod + def from_executable_code(cls, *, code: str, language: Language) -> 'Part': + executable_code = ExecutableCode(code=code, language=language) + return cls(executable_code=executable_code) + + @classmethod + def from_code_execution_result( + cls, *, outcome: Outcome, output: str + ) -> 'Part': + code_execution_result = CodeExecutionResult(outcome=outcome, output=output) + return cls(code_execution_result=code_execution_result) + + +class PartDict(TypedDict, total=False): + """A datatype containing media content. + + Exactly one field within a Part should be set, representing the specific type + of content being conveyed. Using multiple fields within the same `Part` + instance is considered invalid. + """ + + media_resolution: Optional[PartMediaResolutionDict] + """Media resolution for the input media. + """ + + code_execution_result: Optional[CodeExecutionResultDict] + """Optional. The result of executing the ExecutableCode.""" + + executable_code: Optional[ExecutableCodeDict] + """Optional. Code generated by the model that is intended to be executed.""" + + file_data: Optional[FileDataDict] + """Optional. The URI-based data of the part. This can be used to include files from Google Cloud Storage.""" + + function_call: Optional[FunctionCallDict] + """Optional. A predicted function call returned from the model. This contains the name of the function to call and the arguments to pass to the function.""" + + function_response: Optional[FunctionResponseDict] + """Optional. The result of a function call. This is used to provide the model with the result of a function call that it predicted.""" + + inline_data: Optional[BlobDict] + """Optional. The inline data content of the part. This can be used to include images, audio, or video in a request.""" + + text: Optional[str] + """Optional. The text content of the part. When sent from the VSCode Gemini Code Assist extension, references to @mentioned items will be converted to markdown boldface text. For example `@my-repo` will be converted to and sent as `**my-repo**` by the IDE agent.""" + + thought: Optional[bool] + """Optional. Indicates whether the `part` represents the model's thought process or reasoning.""" + + thought_signature: Optional[bytes] + """Optional. An opaque signature for the thought so it can be reused in subsequent requests.""" + + video_metadata: Optional[VideoMetadataDict] + """Optional. Video metadata. The metadata should only be specified while the video data is presented in inline_data or file_data.""" + + tool_call: Optional[ToolCallDict] + """Server-side tool call. This field is populated when the model predicts a tool invocation that should be executed on the server. The client is expected to echo this message back to the API.""" + + tool_response: Optional[ToolResponseDict] + """The output from a server-side ToolCall execution. This field is populated by the client with the results of executing the corresponding ToolCall.""" + + part_metadata: Optional[dict[str, Any]] + """Custom metadata associated with the Part. Agents using genai.Part as content representation may need to keep track of the additional information. For example it can be name of a file/source from which the Part originates or a way to multiplex multiple Part streams. This field is not supported in Vertex AI.""" + + +PartOrDict = Union[Part, PartDict] + + +class Content(_common.BaseModel): + """Contains the multi-part content of a message.""" + + parts: Optional[list[Part]] = Field( + default=None, + description="""List of parts that constitute a single message. Each part may have + a different IANA MIME type.""", + ) + role: Optional[str] = Field( + default=None, + description="""Optional. The producer of the content. Must be either 'user' or 'model'. If not set, the service will default to 'user'.""", + ) + + +class ContentDict(TypedDict, total=False): + """Contains the multi-part content of a message.""" + + parts: Optional[list[PartDict]] + """List of parts that constitute a single message. Each part may have + a different IANA MIME type.""" + + role: Optional[str] + """Optional. The producer of the content. Must be either 'user' or 'model'. If not set, the service will default to 'user'.""" + + +ContentOrDict = Union[Content, ContentDict] + + +class HttpRetryOptions(_common.BaseModel): + """HTTP retry options to be used in each of the requests.""" + + attempts: Optional[int] = Field( + default=None, + description="""Maximum number of attempts, including the original request. + If 0 or 1, it means no retries. If not specified, default to 5.""", + ) + initial_delay: Optional[float] = Field( + default=None, + description="""Initial delay before the first retry, in fractions of a second. If not specified, default to 1.0 second.""", + ) + max_delay: Optional[float] = Field( + default=None, + description="""Maximum delay between retries, in fractions of a second. If not specified, default to 60.0 seconds.""", + ) + exp_base: Optional[float] = Field( + default=None, + description="""Multiplier by which the delay increases after each attempt. If not specified, default to 2.0.""", + ) + jitter: Optional[float] = Field( + default=None, + description="""Randomness factor for the delay. If not specified, default to 1.0.""", + ) + http_status_codes: Optional[list[int]] = Field( + default=None, + description="""List of HTTP status codes that should trigger a retry. + If not specified, a default set of retryable codes (408, 429, and 5xx) may be used.""", + ) + + +class HttpRetryOptionsDict(TypedDict, total=False): + """HTTP retry options to be used in each of the requests.""" + + attempts: Optional[int] + """Maximum number of attempts, including the original request. + If 0 or 1, it means no retries. If not specified, default to 5.""" + + initial_delay: Optional[float] + """Initial delay before the first retry, in fractions of a second. If not specified, default to 1.0 second.""" + + max_delay: Optional[float] + """Maximum delay between retries, in fractions of a second. If not specified, default to 60.0 seconds.""" + + exp_base: Optional[float] + """Multiplier by which the delay increases after each attempt. If not specified, default to 2.0.""" + + jitter: Optional[float] + """Randomness factor for the delay. If not specified, default to 1.0.""" + + http_status_codes: Optional[list[int]] + """List of HTTP status codes that should trigger a retry. + If not specified, a default set of retryable codes (408, 429, and 5xx) may be used.""" + + +HttpRetryOptionsOrDict = Union[HttpRetryOptions, HttpRetryOptionsDict] + + +class HttpOptions(_common.BaseModel): + """HTTP options to be used in each of the requests.""" + + base_url: Optional[str] = Field( + default=None, + description="""The base URL for the AI platform service endpoint.""", + ) + base_url_resource_scope: Optional[ResourceScope] = Field( + default=None, + description="""The resource scope used to constructing the resource name when base_url is set""", + ) + api_version: Optional[str] = Field( + default=None, description="""Specifies the version of the API to use.""" + ) + headers: Optional[dict[str, str]] = Field( + default=None, + description="""Additional HTTP headers to be sent with the request.""", + ) + timeout: Optional[int] = Field( + default=None, description="""Timeout for the request in milliseconds.""" + ) + client_args: Optional[dict[str, Any]] = Field( + default=None, description="""Args passed to the HTTP client.""" + ) + async_client_args: Optional[dict[str, Any]] = Field( + default=None, description="""Args passed to the async HTTP client.""" + ) + extra_body: Optional[dict[str, Any]] = Field( + default=None, + description="""Extra parameters to add to the request body. + The structure must match the backend API's request structure. + - VertexAI backend API docs: https://cloud.google.com/vertex-ai/docs/reference/rest + - GeminiAPI backend API docs: https://ai.google.dev/api/rest""", + ) + retry_options: Optional[HttpRetryOptions] = Field( + default=None, description="""HTTP retry options for the request.""" + ) + + httpx_client: Optional['HttpxClient'] = Field( + default=None, + description="""A custom httpx client to be used for the request.""", + ) + httpx_async_client: Optional['HttpxAsyncClient'] = Field( + default=None, + description="""A custom httpx async client to be used for the request.""", + ) + aiohttp_client: Optional['ClientSession'] = Field( + default=None, + description="""A custom aiohttp client session to be used for the request.""", + ) + + +class HttpOptionsDict(TypedDict, total=False): + """HTTP options to be used in each of the requests.""" + + base_url: Optional[str] + """The base URL for the AI platform service endpoint.""" + + base_url_resource_scope: Optional[ResourceScope] + """The resource scope used to constructing the resource name when base_url is set""" + + api_version: Optional[str] + """Specifies the version of the API to use.""" + + headers: Optional[dict[str, str]] + """Additional HTTP headers to be sent with the request.""" + + timeout: Optional[int] + """Timeout for the request in milliseconds.""" + + client_args: Optional[dict[str, Any]] + """Args passed to the HTTP client.""" + + async_client_args: Optional[dict[str, Any]] + """Args passed to the async HTTP client.""" + + extra_body: Optional[dict[str, Any]] + """Extra parameters to add to the request body. + The structure must match the backend API's request structure. + - VertexAI backend API docs: https://cloud.google.com/vertex-ai/docs/reference/rest + - GeminiAPI backend API docs: https://ai.google.dev/api/rest""" + + retry_options: Optional[HttpRetryOptionsDict] + """HTTP retry options for the request.""" + + +HttpOptionsOrDict = Union[HttpOptions, HttpOptionsDict] + + +class JSONSchema(_common.BaseModel): + """A subset of JSON Schema according to 2020-12 JSON Schema draft. + + Represents a subset of a JSON Schema object that is used by the Gemini model. + The difference between this class and the Schema class is that this class is + compatible with OpenAPI 3.1 schema objects. And the Schema class is used to + make API call to Gemini model. + """ + + type: Optional[Union[JSONSchemaType, list[JSONSchemaType]]] = Field( + default=None, + description="""Validation succeeds if the type of the instance matches the type represented by the given type, or matches at least one of the given types.""", + ) + format: Optional[str] = Field( + default=None, + description='Define semantic information about a string instance.', + ) + title: Optional[str] = Field( + default=None, + description=( + 'A preferably short description about the purpose of the instance' + ' described by the schema.' + ), + ) + description: Optional[str] = Field( + default=None, + description=( + 'An explanation about the purpose of the instance described by the' + ' schema.' + ), + ) + default: Optional[Any] = Field( + default=None, + description=( + 'This keyword can be used to supply a default JSON value associated' + ' with a particular schema.' + ), + ) + items: Optional['JSONSchema'] = Field( + default=None, + description=( + 'Validation succeeds if each element of the instance not covered by' + ' prefixItems validates against this schema.' + ), + ) + min_items: Optional[int] = Field( + default=None, + description=( + 'An array instance is valid if its size is greater than, or equal to,' + ' the value of this keyword.' + ), + ) + max_items: Optional[int] = Field( + default=None, + description=( + 'An array instance is valid if its size is less than, or equal to,' + ' the value of this keyword.' + ), + ) + enum: Optional[list[Any]] = Field( + default=None, + description=( + 'Validation succeeds if the instance is equal to one of the elements' + ' in this keyword’s array value.' + ), + ) + properties: Optional[dict[str, 'JSONSchema']] = Field( + default=None, + description=( + 'Validation succeeds if, for each name that appears in both the' + ' instance and as a name within this keyword’s value, the child' + ' instance for that name successfully validates against the' + ' corresponding schema.' + ), + ) + required: Optional[list[str]] = Field( + default=None, + description=( + 'An object instance is valid against this keyword if every item in' + ' the array is the name of a property in the instance.' + ), + ) + min_properties: Optional[int] = Field( + default=None, + description=( + 'An object instance is valid if its number of properties is greater' + ' than, or equal to, the value of this keyword.' + ), + ) + max_properties: Optional[int] = Field( + default=None, + description=( + 'An object instance is valid if its number of properties is less' + ' than, or equal to, the value of this keyword.' + ), + ) + minimum: Optional[float] = Field( + default=None, + description=( + 'Validation succeeds if the numeric instance is greater than or equal' + ' to the given number.' + ), + ) + maximum: Optional[float] = Field( + default=None, + description=( + 'Validation succeeds if the numeric instance is less than or equal to' + ' the given number.' + ), + ) + min_length: Optional[int] = Field( + default=None, + description=( + 'A string instance is valid against this keyword if its length is' + ' greater than, or equal to, the value of this keyword.' + ), + ) + max_length: Optional[int] = Field( + default=None, + description=( + 'A string instance is valid against this keyword if its length is' + ' less than, or equal to, the value of this keyword.' + ), + ) + pattern: Optional[str] = Field( + default=None, + description=( + 'A string instance is considered valid if the regular expression' + ' matches the instance successfully.' + ), + ) + additional_properties: Optional[Any] = Field( + default=None, + description="""Can either be a boolean or an object; controls the presence of additional properties.""", + ) + any_of: Optional[list['JSONSchema']] = Field( + default=None, + description=( + 'An instance validates successfully against this keyword if it' + ' validates successfully against at least one schema defined by this' + ' keyword’s value.' + ), + ) + unique_items: Optional[bool] = Field( + default=None, + description="""Boolean value that indicates whether the items in an array are unique.""", + ) + ref: Optional[str] = Field( + default=None, + alias='$ref', + description="""Allows indirect references between schema nodes.""", + ) + defs: Optional[dict[str, 'JSONSchema']] = Field( + default=None, + alias='$defs', + description="""Schema definitions to be used with $ref.""", + ) + + +class Schema(_common.BaseModel): + """Schema is used to define the format of input/output data. + + Represents a select subset of an [OpenAPI 3.0 schema + object](https://spec.openapis.org/oas/v3.0.3#schema-object). More fields may + be added in the future as needed. + """ + + additional_properties: Optional[Any] = Field( + default=None, + description="""Optional. Can either be a boolean or an object; controls the presence of additional properties.""", + ) + defs: Optional[dict[str, 'Schema']] = Field( + default=None, + description="""Optional. A map of definitions for use by `ref` Only allowed at the root of the schema.""", + ) + ref: Optional[str] = Field( + default=None, + description="""Optional. Allows indirect references between schema nodes. The value should be a valid reference to a child of the root `defs`. For example, the following schema defines a reference to a schema node named "Pet": type: object properties: pet: ref: #/defs/Pet defs: Pet: type: object properties: name: type: string The value of the "pet" property is a reference to the schema node named "Pet". See details in https://json-schema.org/understanding-json-schema/structuring""", + ) + any_of: Optional[list['Schema']] = Field( + default=None, + description="""Optional. The instance must be valid against any (one or more) of the subschemas listed in `any_of`.""", + ) + default: Optional[Any] = Field( + default=None, + description="""Optional. Default value to use if the field is not specified.""", + ) + description: Optional[str] = Field( + default=None, + description="""Optional. Describes the data. The model uses this field to understand the purpose of the schema and how to use it. It is a best practice to provide a clear and descriptive explanation for the schema and its properties here, rather than in the prompt.""", + ) + enum: Optional[list[str]] = Field( + default=None, + description="""Optional. Possible values of the field. This field can be used to restrict a value to a fixed set of values. To mark a field as an enum, set `format` to `enum` and provide the list of possible values in `enum`. For example: 1. To define directions: `{type:STRING, format:enum, enum:["EAST", "NORTH", "SOUTH", "WEST"]}` 2. To define apartment numbers: `{type:INTEGER, format:enum, enum:["101", "201", "301"]}`""", + ) + example: Optional[Any] = Field( + default=None, + description="""Optional. Example of an instance of this schema.""", + ) + format: Optional[str] = Field( + default=None, + description="""Optional. The format of the data. For `NUMBER` type, format can be `float` or `double`. For `INTEGER` type, format can be `int32` or `int64`. For `STRING` type, format can be `email`, `byte`, `date`, `date-time`, `password`, and other formats to further refine the data type.""", + ) + items: Optional['Schema'] = Field( + default=None, + description="""Optional. If type is `ARRAY`, `items` specifies the schema of elements in the array.""", + ) + max_items: Optional[int] = Field( + default=None, + description="""Optional. If type is `ARRAY`, `max_items` specifies the maximum number of items in an array.""", + ) + max_length: Optional[int] = Field( + default=None, + description="""Optional. If type is `STRING`, `max_length` specifies the maximum length of the string.""", + ) + max_properties: Optional[int] = Field( + default=None, + description="""Optional. If type is `OBJECT`, `max_properties` specifies the maximum number of properties that can be provided.""", + ) + maximum: Optional[float] = Field( + default=None, + description="""Optional. If type is `INTEGER` or `NUMBER`, `maximum` specifies the maximum allowed value.""", + ) + min_items: Optional[int] = Field( + default=None, + description="""Optional. If type is `ARRAY`, `min_items` specifies the minimum number of items in an array.""", + ) + min_length: Optional[int] = Field( + default=None, + description="""Optional. If type is `STRING`, `min_length` specifies the minimum length of the string.""", + ) + min_properties: Optional[int] = Field( + default=None, + description="""Optional. If type is `OBJECT`, `min_properties` specifies the minimum number of properties that can be provided.""", + ) + minimum: Optional[float] = Field( + default=None, + description="""Optional. If type is `INTEGER` or `NUMBER`, `minimum` specifies the minimum allowed value.""", + ) + nullable: Optional[bool] = Field( + default=None, + description="""Optional. Indicates if the value of this field can be null.""", + ) + pattern: Optional[str] = Field( + default=None, + description="""Optional. If type is `STRING`, `pattern` specifies a regular expression that the string must match.""", + ) + properties: Optional[dict[str, 'Schema']] = Field( + default=None, + description="""Optional. If type is `OBJECT`, `properties` is a map of property names to schema definitions for each property of the object.""", + ) + property_ordering: Optional[list[str]] = Field( + default=None, + description="""Optional. Order of properties displayed or used where order matters. This is not a standard field in OpenAPI specification, but can be used to control the order of properties.""", + ) + required: Optional[list[str]] = Field( + default=None, + description="""Optional. If type is `OBJECT`, `required` lists the names of properties that must be present.""", + ) + title: Optional[str] = Field( + default=None, description="""Optional. Title for the schema.""" + ) + type: Optional[Type] = Field( + default=None, description="""Optional. Data type of the schema field.""" + ) + + @property + def json_schema(self) -> 'JSONSchema': + """Converts the Schema object to a JSONSchema object, that is compatible with 2020-12 JSON Schema draft. + + Note: Conversion of fields that are not included in the JSONSchema class + are ignored. + Json Schema is now supported natively by both Vertex AI and Gemini API. + Users + are recommended to pass/receive Json Schema directly to/from the API. For + example: + 1. the counter part of GenerateContentConfig.response_schema is + GenerateContentConfig.response_json_schema, which accepts [JSON + Schema](https://json-schema.org/) + 2. the counter part of FunctionDeclaration.parameters is + FunctionDeclaration.parameters_json_schema, which accepts [JSON + Schema](https://json-schema.org/) + 3. the counter part of FunctionDeclaration.response is + FunctionDeclaration.response_json_schema, which accepts [JSON + Schema](https://json-schema.org/) + """ + + global _json_schema_warning_logged + if not _json_schema_warning_logged: + info_message = """ +Note: Conversion of fields that are not included in the JSONSchema class are +ignored. +Json Schema is now supported natively by both Vertex AI and Gemini API. Users +are recommended to pass/receive Json Schema directly to/from the API. For example: +1. the counter part of GenerateContentConfig.response_schema is + GenerateContentConfig.response_json_schema, which accepts [JSON + Schema](https://json-schema.org/) +2. the counter part of FunctionDeclaration.parameters is + FunctionDeclaration.parameters_json_schema, which accepts [JSON + Schema](https://json-schema.org/) +3. the counter part of FunctionDeclaration.response is + FunctionDeclaration.response_json_schema, which accepts [JSON + Schema](https://json-schema.org/) +""" + logger.info(info_message) + _json_schema_warning_logged = True + + json_schema_field_names: set[str] = set(JSONSchema.model_fields.keys()) + schema_field_names: tuple[str] = ( + 'items', + ) # 'additional_properties' to come + list_schema_field_names: tuple[str] = ( + 'any_of', # 'one_of', 'all_of', 'not' to come + ) + dict_schema_field_names: tuple[str] = ('properties',) # 'defs' to come + + def convert_schema(schema: Union['Schema', dict[str, Any]]) -> 'JSONSchema': + if isinstance(schema, pydantic.BaseModel): + schema_dict = schema.model_dump(exclude_none=True) + else: + schema_dict = schema + json_schema = JSONSchema() + for field_name, field_value in schema_dict.items(): + if field_value is None: + continue + elif field_name == 'nullable': + if json_schema.type is None: + json_schema.type = JSONSchemaType.NULL + elif isinstance(json_schema.type, JSONSchemaType): + current_type: JSONSchemaType = json_schema.type + json_schema.type = [current_type, JSONSchemaType.NULL] + elif isinstance(json_schema.type, list): + json_schema.type.append(JSONSchemaType.NULL) + elif field_name not in json_schema_field_names: + continue + elif field_name == 'type': + if field_value == Type.TYPE_UNSPECIFIED: + continue + json_schema_type = JSONSchemaType(field_value.lower()) + if json_schema.type is None: + json_schema.type = json_schema_type + elif isinstance(json_schema.type, JSONSchemaType): + existing_type: JSONSchemaType = json_schema.type + json_schema.type = [existing_type, json_schema_type] + elif isinstance(json_schema.type, list): + json_schema.type.append(json_schema_type) + elif field_name in schema_field_names: + schema_field_value: 'JSONSchema' = convert_schema(field_value) + setattr(json_schema, field_name, schema_field_value) + elif field_name in list_schema_field_names: + list_schema_field_value: list['JSONSchema'] = [ + convert_schema(this_field_value) + for this_field_value in field_value + ] + setattr(json_schema, field_name, list_schema_field_value) + elif field_name in dict_schema_field_names: + dict_schema_field_value: dict[str, 'JSONSchema'] = { + key: convert_schema(value) for key, value in field_value.items() + } + setattr(json_schema, field_name, dict_schema_field_value) + else: + setattr(json_schema, field_name, field_value) + + return json_schema + + return convert_schema(self) + + @classmethod + def from_json_schema( + cls, + *, + json_schema: 'JSONSchema', + api_option: Literal['VERTEX_AI', 'GEMINI_API'] = 'GEMINI_API', + raise_error_on_unsupported_field: bool = False, + ) -> 'Schema': + """Converts a JSONSchema object to a Schema object. + + Note: Conversion of fields that are not included in the JSONSchema class + are ignored. + Json Schema is now supported natively by both Vertex AI and Gemini API. + Users + are recommended to pass/receive Json Schema directly to/from the API. For + example: + 1. the counter part of GenerateContentConfig.response_schema is + GenerateContentConfig.response_json_schema, which accepts [JSON + Schema](https://json-schema.org/) + 2. the counter part of FunctionDeclaration.parameters is + FunctionDeclaration.parameters_json_schema, which accepts [JSON + Schema](https://json-schema.org/) + 3. the counter part of FunctionDeclaration.response is + FunctionDeclaration.response_json_schema, which accepts [JSON + Schema](https://json-schema.org/) + The JSONSchema is compatible with 2020-12 JSON Schema draft, specified by + OpenAPI 3.1. + + Args: + json_schema: JSONSchema object to be converted. + api_option: API option to be used. If set to 'VERTEX_AI', the + JSONSchema will be converted to a Schema object that is compatible + with Vertex AI API. If set to 'GEMINI_API', the JSONSchema will be + converted to a Schema object that is compatible with Gemini API. + Default is 'GEMINI_API'. + raise_error_on_unsupported_field: If set to True, an error will be + raised if the JSONSchema contains any unsupported fields. Default is + False. + + Returns: + Schema object that is compatible with the specified API option. + Raises: + ValueError: If the JSONSchema contains any unsupported fields and + raise_error_on_unsupported_field is set to True. Or if the JSONSchema + is not compatible with the specified API option. + """ + global _from_json_schema_warning_logged + if not _from_json_schema_warning_logged: + info_message = """ +Note: Conversion of fields that are not included in the JSONSchema class are ignored. +Json Schema is now supported natively by both Vertex AI and Gemini API. Users +are recommended to pass/receive Json Schema directly to/from the API. For example: +1. the counter part of GenerateContentConfig.response_schema is + GenerateContentConfig.response_json_schema, which accepts [JSON + Schema](https://json-schema.org/) +2. the counter part of FunctionDeclaration.parameters is + FunctionDeclaration.parameters_json_schema, which accepts [JSON + Schema](https://json-schema.org/) +3. the counter part of FunctionDeclaration.response is + FunctionDeclaration.response_json_schema, which accepts [JSON + Schema](https://json-schema.org/) +""" + logger.info(info_message) + _from_json_schema_warning_logged = True + + google_schema_field_names: set[str] = set(cls.model_fields.keys()) + schema_field_names: tuple[str, ...] = ( + 'items', + ) # 'additional_properties' to come + list_schema_field_names: tuple[str, ...] = ( + 'any_of', # 'one_of', 'all_of', 'not' to come + ) + dict_schema_field_names: tuple[str, ...] = ('properties',) + + related_field_names_by_type: dict[str, tuple[str, ...]] = { + JSONSchemaType.NUMBER.value: ( + 'description', + 'enum', + 'format', + 'maximum', + 'minimum', + 'title', + ), + JSONSchemaType.STRING.value: ( + 'description', + 'enum', + 'format', + 'max_length', + 'min_length', + 'pattern', + 'title', + ), + JSONSchemaType.OBJECT.value: ( + 'any_of', + 'description', + 'max_properties', + 'min_properties', + 'properties', + 'required', + 'title', + ), + JSONSchemaType.ARRAY.value: ( + 'description', + 'items', + 'max_items', + 'min_items', + 'title', + ), + JSONSchemaType.BOOLEAN.value: ( + 'description', + 'title', + ), + } + # Treat `INTEGER` like `NUMBER`. + related_field_names_by_type[JSONSchemaType.INTEGER.value] = ( + related_field_names_by_type[JSONSchemaType.NUMBER.value] + ) + + # placeholder for potential gemini api unsupported fields + gemini_api_unsupported_field_names: tuple[str, ...] = () + + def _resolve_ref( + ref_path: str, root_schema_dict: dict[str, Any] + ) -> dict[str, Any]: + """Helper to resolve a $ref path.""" + current = root_schema_dict + for part in ref_path.lstrip('#/').split('/'): + if part == '$defs': + part = 'defs' + current = current[part] + current.pop('title', None) + if 'properties' in current and current['properties'] is not None: + for prop_schema in current['properties'].values(): + if isinstance(prop_schema, dict): + prop_schema.pop('title', None) + + return current + + def normalize_json_schema_type( + json_schema_type: Optional[ + Union[JSONSchemaType, Sequence[JSONSchemaType], str, Sequence[str]] + ], + ) -> tuple[list[str], bool]: + """Returns (non_null_types, nullable)""" + if json_schema_type is None: + return [], False + type_sequence: Sequence[Union[JSONSchemaType, str]] + if isinstance(json_schema_type, str) or not isinstance( + json_schema_type, Sequence + ): + type_sequence = [json_schema_type] + else: + type_sequence = json_schema_type + non_null_types = [] + nullable = False + for type_value in type_sequence: + if isinstance(type_value, JSONSchemaType): + type_value = type_value.value + if type_value == JSONSchemaType.NULL.value: + nullable = True + else: + non_null_types.append(type_value) + return non_null_types, nullable + + def raise_error_if_cannot_convert( + json_schema_dict: dict[str, Any], + api_option: Literal['VERTEX_AI', 'GEMINI_API'], + raise_error_on_unsupported_field: bool, + ) -> None: + """Raises an error if the JSONSchema cannot be converted to the specified Schema object.""" + if not raise_error_on_unsupported_field: + return + for field_name, field_value in json_schema_dict.items(): + if field_value is None: + continue + if field_name not in google_schema_field_names and field_name not in [ + 'ref', + 'defs', + ]: + raise ValueError( + f'JSONSchema field "{field_name}" is not supported by the Schema' + ' object. And the "raise_error_on_unsupported_field" argument is' + ' set to True. If you still want to convert it into the Schema' + f' object, please either remove the field "{field_name}" from the' + ' JSONSchema object, leave the' + ' "raise_error_on_unsupported_field" unset, or try using' + ' response_json_schema instead.' + ) + if ( + field_name in gemini_api_unsupported_field_names + and api_option == 'GEMINI_API' + ): + raise ValueError( + f'The "{field_name}" field is not supported by the Schema ' + 'object for GEMINI_API.' + ) + + def copy_schema_fields( + json_schema_dict: dict[str, Any], + related_fields_to_copy: tuple[str, ...], + sub_schema_in_any_of: dict[str, Any], + ) -> None: + """Copies the fields from json_schema_dict to sub_schema_in_any_of.""" + for field_name in related_fields_to_copy: + sub_schema_in_any_of[field_name] = json_schema_dict.get( + field_name, None + ) + + def convert_json_schema( + current_json_schema: 'JSONSchema', + root_json_schema_dict: dict[str, Any], + api_option: Literal['VERTEX_AI', 'GEMINI_API'], + raise_error_on_unsupported_field: bool, + visited_refs: Optional[set[str]] = None, + ) -> 'Schema': + if visited_refs is None: + visited_refs = set() + + schema = Schema() + json_schema_dict = current_json_schema.model_dump() + + ref = json_schema_dict.get('ref') + if ref: + if ref in visited_refs: + return Schema() + visited_refs.add(ref) + json_schema_dict = _resolve_ref(ref, root_json_schema_dict) + + raise_error_if_cannot_convert( + json_schema_dict=json_schema_dict, + api_option=api_option, + raise_error_on_unsupported_field=raise_error_on_unsupported_field, + ) + + # At the highest level of the logic, there are two passes: + # Pass 1: the JSONSchema.type is union-like, + # e.g. ['null', 'string', 'array']. + # for this case, we need to split the JSONSchema into multiple + # sub-schemas, and copy them into the any_of field of the Schema. + # And when we copy the non-type fields into any_of field, + # we only copy the fields related to the specific type. + # Detailed logic is commented below with `Pass 1` keyword tag. + # Pass 2: the JSONSchema.type is not union-like, + # e.g. 'string', ['string'], ['null', 'string']. + # for this case, no splitting is needed. Detailed + # logic is commented below with `Pass 2` keyword tag. + # + # + # Pass 1: the JSONSchema.type is union-like + # e.g. ['null', 'string', 'array']. + non_null_types, nullable = normalize_json_schema_type( + json_schema_dict.get('type', None) + ) + is_union_like_type = len(non_null_types) > 1 + if len(non_null_types) > 1: + logger.warning( + 'JSONSchema type is union-like, e.g. ["null", "string", "array"]. ' + 'Converting it into multiple sub-schemas, and copying them into ' + 'the any_of field of the Schema. The value of `default` field is ' + 'ignored because it is ambiguous to tell which sub-schema it ' + 'belongs to.' + ) + reformed_json_schema = JSONSchema() + # start splitting the JSONSchema into multiple sub-schemas + any_of = [] + if nullable: + schema.nullable = True + for normalized_type in non_null_types: + sub_schema_in_any_of = {'type': normalized_type} + related_field_names = related_field_names_by_type.get(normalized_type) + if related_field_names is not None: + copy_schema_fields( + json_schema_dict=json_schema_dict, + related_fields_to_copy=related_field_names, + sub_schema_in_any_of=sub_schema_in_any_of, + ) + any_of.append(JSONSchema(**sub_schema_in_any_of)) + reformed_json_schema.any_of = any_of + json_schema_dict = reformed_json_schema.model_dump() + + # Pass 2: the JSONSchema.type is not union-like, + # e.g. 'string', ['string'], ['null', 'string']. + for field_name, field_value in json_schema_dict.items(): + if field_value is None or field_name == 'defs': + continue + if field_name in schema_field_names: + if field_name == 'items' and not field_value: + continue + schema_field_value: 'Schema' = convert_json_schema( + current_json_schema=JSONSchema(**field_value), + root_json_schema_dict=root_json_schema_dict, + api_option=api_option, + raise_error_on_unsupported_field=raise_error_on_unsupported_field, + visited_refs=visited_refs, + ) + setattr(schema, field_name, schema_field_value) + elif field_name in list_schema_field_names: + list_schema_field_value: list['Schema'] = [ + convert_json_schema( + current_json_schema=JSONSchema(**this_field_value), + root_json_schema_dict=root_json_schema_dict, + api_option=api_option, + raise_error_on_unsupported_field=raise_error_on_unsupported_field, + visited_refs=visited_refs, + ) + for this_field_value in field_value + ] + setattr(schema, field_name, list_schema_field_value) + if not schema.type and not is_union_like_type and not schema.any_of: + schema.type = Type('OBJECT') + elif field_name in dict_schema_field_names: + dict_schema_field_value: dict[str, 'Schema'] = { + key: convert_json_schema( + current_json_schema=JSONSchema(**value), + root_json_schema_dict=root_json_schema_dict, + api_option=api_option, + raise_error_on_unsupported_field=raise_error_on_unsupported_field, + visited_refs=visited_refs, + ) + for key, value in field_value.items() + } + setattr(schema, field_name, dict_schema_field_value) + elif field_name == 'type': + non_null_types, nullable = normalize_json_schema_type(field_value) + if nullable: + schema.nullable = True + if non_null_types: + schema.type = Type(non_null_types[0]) + else: + if ( + hasattr(schema, field_name) + and field_name != 'additional_properties' + ): + setattr(schema, field_name, field_value) + + if ( + schema.type == 'ARRAY' + and schema.items + and not schema.items.model_dump(exclude_unset=True) + ): + schema.items = None + + if schema.any_of and len(schema.any_of) == 2: + nullable_part = None + type_part = None + for part in schema.any_of: + # A schema representing `None` will either be of type NULL or just be nullable. + part_dict = part.model_dump(exclude_unset=True) + if part_dict == {'nullable': True} or part_dict == {'type': 'NULL'}: + nullable_part = part + else: + type_part = part + + # If we found both parts, unwrap them into a single schema. + if nullable_part and type_part: + default_value = schema.default + schema = type_part + schema.nullable = True + # Carry the default value over to the unwrapped schema + if default_value is not None: + schema.default = default_value + + if ref: + visited_refs.remove(ref) + return schema + + # This is the initial call to the recursive function. + root_schema_dict = json_schema.model_dump() + return convert_json_schema( + current_json_schema=json_schema, + root_json_schema_dict=root_schema_dict, + api_option=api_option, + raise_error_on_unsupported_field=raise_error_on_unsupported_field, + ) + + +class SchemaDict(TypedDict, total=False): + """Schema is used to define the format of input/output data. + + Represents a select subset of an [OpenAPI 3.0 schema + object](https://spec.openapis.org/oas/v3.0.3#schema-object). More fields may + be added in the future as needed. + """ + + additional_properties: Optional[Any] + """Optional. Can either be a boolean or an object; controls the presence of additional properties.""" + + defs: Optional[dict[str, 'SchemaDict']] + """Optional. A map of definitions for use by `ref` Only allowed at the root of the schema.""" + + ref: Optional[str] + """Optional. Allows indirect references between schema nodes. The value should be a valid reference to a child of the root `defs`. For example, the following schema defines a reference to a schema node named "Pet": type: object properties: pet: ref: #/defs/Pet defs: Pet: type: object properties: name: type: string The value of the "pet" property is a reference to the schema node named "Pet". See details in https://json-schema.org/understanding-json-schema/structuring""" + + any_of: Optional[list['SchemaDict']] + """Optional. The instance must be valid against any (one or more) of the subschemas listed in `any_of`.""" + + default: Optional[Any] + """Optional. Default value to use if the field is not specified.""" + + description: Optional[str] + """Optional. Describes the data. The model uses this field to understand the purpose of the schema and how to use it. It is a best practice to provide a clear and descriptive explanation for the schema and its properties here, rather than in the prompt.""" + + enum: Optional[list[str]] + """Optional. Possible values of the field. This field can be used to restrict a value to a fixed set of values. To mark a field as an enum, set `format` to `enum` and provide the list of possible values in `enum`. For example: 1. To define directions: `{type:STRING, format:enum, enum:["EAST", "NORTH", "SOUTH", "WEST"]}` 2. To define apartment numbers: `{type:INTEGER, format:enum, enum:["101", "201", "301"]}`""" + + example: Optional[Any] + """Optional. Example of an instance of this schema.""" + + format: Optional[str] + """Optional. The format of the data. For `NUMBER` type, format can be `float` or `double`. For `INTEGER` type, format can be `int32` or `int64`. For `STRING` type, format can be `email`, `byte`, `date`, `date-time`, `password`, and other formats to further refine the data type.""" + + items: Optional['SchemaDict'] + """Optional. If type is `ARRAY`, `items` specifies the schema of elements in the array.""" + + max_items: Optional[int] + """Optional. If type is `ARRAY`, `max_items` specifies the maximum number of items in an array.""" + + max_length: Optional[int] + """Optional. If type is `STRING`, `max_length` specifies the maximum length of the string.""" + + max_properties: Optional[int] + """Optional. If type is `OBJECT`, `max_properties` specifies the maximum number of properties that can be provided.""" + + maximum: Optional[float] + """Optional. If type is `INTEGER` or `NUMBER`, `maximum` specifies the maximum allowed value.""" + + min_items: Optional[int] + """Optional. If type is `ARRAY`, `min_items` specifies the minimum number of items in an array.""" + + min_length: Optional[int] + """Optional. If type is `STRING`, `min_length` specifies the minimum length of the string.""" + + min_properties: Optional[int] + """Optional. If type is `OBJECT`, `min_properties` specifies the minimum number of properties that can be provided.""" + + minimum: Optional[float] + """Optional. If type is `INTEGER` or `NUMBER`, `minimum` specifies the minimum allowed value.""" + + nullable: Optional[bool] + """Optional. Indicates if the value of this field can be null.""" + + pattern: Optional[str] + """Optional. If type is `STRING`, `pattern` specifies a regular expression that the string must match.""" + + properties: Optional[dict[str, 'SchemaDict']] + """Optional. If type is `OBJECT`, `properties` is a map of property names to schema definitions for each property of the object.""" + + property_ordering: Optional[list[str]] + """Optional. Order of properties displayed or used where order matters. This is not a standard field in OpenAPI specification, but can be used to control the order of properties.""" + + required: Optional[list[str]] + """Optional. If type is `OBJECT`, `required` lists the names of properties that must be present.""" + + title: Optional[str] + """Optional. Title for the schema.""" + + type: Optional[Type] + """Optional. Data type of the schema field.""" + + +SchemaOrDict = Union[Schema, SchemaDict] + + +class ModelSelectionConfig(_common.BaseModel): + """Config for model selection.""" + + feature_selection_preference: Optional[FeatureSelectionPreference] = Field( + default=None, description="""Options for feature selection preference.""" + ) + + +class ModelSelectionConfigDict(TypedDict, total=False): + """Config for model selection.""" + + feature_selection_preference: Optional[FeatureSelectionPreference] + """Options for feature selection preference.""" + + +ModelSelectionConfigOrDict = Union[ + ModelSelectionConfig, ModelSelectionConfigDict +] + + +class ComputerUse(_common.BaseModel): + """Tool to support computer use.""" + + environment: Optional[Environment] = Field( + default=None, description="""Required. The environment being operated.""" + ) + excluded_predefined_functions: Optional[list[str]] = Field( + default=None, + description="""By default, predefined functions are included in the final model call. + Some of them can be explicitly excluded from being automatically included. + This can serve two purposes: + 1. Using a more restricted / different action space. + 2. Improving the definitions / instructions of predefined functions.""", + ) + + +class ComputerUseDict(TypedDict, total=False): + """Tool to support computer use.""" + + environment: Optional[Environment] + """Required. The environment being operated.""" + + excluded_predefined_functions: Optional[list[str]] + """By default, predefined functions are included in the final model call. + Some of them can be explicitly excluded from being automatically included. + This can serve two purposes: + 1. Using a more restricted / different action space. + 2. Improving the definitions / instructions of predefined functions.""" + + +ComputerUseOrDict = Union[ComputerUse, ComputerUseDict] + + +class ApiKeyConfig(_common.BaseModel): + """Config for authentication with API key. + + This data type is not supported in Gemini API. + """ + + api_key_secret: Optional[str] = Field( + default=None, + description="""Optional. The name of the SecretManager secret version resource storing the API key. Format: `projects/{project}/secrets/{secrete}/versions/{version}` - If both `api_key_secret` and `api_key_string` are specified, this field takes precedence over `api_key_string`. - If specified, the `secretmanager.versions.access` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified resource.""", + ) + api_key_string: Optional[str] = Field( + default=None, + description="""Optional. The API key to be used in the request directly.""", + ) + http_element_location: Optional[HttpElementLocation] = Field( + default=None, description="""Optional. The location of the API key.""" + ) + name: Optional[str] = Field( + default=None, + description="""Optional. The parameter name of the API key. E.g. If the API request is "https://example.com/act?api_key=", "api_key" would be the parameter name.""", + ) + + +class ApiKeyConfigDict(TypedDict, total=False): + """Config for authentication with API key. + + This data type is not supported in Gemini API. + """ + + api_key_secret: Optional[str] + """Optional. The name of the SecretManager secret version resource storing the API key. Format: `projects/{project}/secrets/{secrete}/versions/{version}` - If both `api_key_secret` and `api_key_string` are specified, this field takes precedence over `api_key_string`. - If specified, the `secretmanager.versions.access` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified resource.""" + + api_key_string: Optional[str] + """Optional. The API key to be used in the request directly.""" + + http_element_location: Optional[HttpElementLocation] + """Optional. The location of the API key.""" + + name: Optional[str] + """Optional. The parameter name of the API key. E.g. If the API request is "https://example.com/act?api_key=", "api_key" would be the parameter name.""" + + +ApiKeyConfigOrDict = Union[ApiKeyConfig, ApiKeyConfigDict] + + +class AuthConfigGoogleServiceAccountConfig(_common.BaseModel): + """Config for Google Service Account Authentication. + + This data type is not supported in Gemini API. + """ + + service_account: Optional[str] = Field( + default=None, + description="""Optional. The service account that the extension execution service runs as. - If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified service account. - If not specified, the Vertex AI Extension Service Agent will be used to execute the Extension.""", + ) + + +class AuthConfigGoogleServiceAccountConfigDict(TypedDict, total=False): + """Config for Google Service Account Authentication. + + This data type is not supported in Gemini API. + """ + + service_account: Optional[str] + """Optional. The service account that the extension execution service runs as. - If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified service account. - If not specified, the Vertex AI Extension Service Agent will be used to execute the Extension.""" + + +AuthConfigGoogleServiceAccountConfigOrDict = Union[ + AuthConfigGoogleServiceAccountConfig, + AuthConfigGoogleServiceAccountConfigDict, +] + + +class AuthConfigHttpBasicAuthConfig(_common.BaseModel): + """Config for HTTP Basic Authentication. + + This data type is not supported in Gemini API. + """ + + credential_secret: Optional[str] = Field( + default=None, + description="""Required. The name of the SecretManager secret version resource storing the base64 encoded credentials. Format: `projects/{project}/secrets/{secrete}/versions/{version}` - If specified, the `secretmanager.versions.access` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified resource.""", + ) + + +class AuthConfigHttpBasicAuthConfigDict(TypedDict, total=False): + """Config for HTTP Basic Authentication. + + This data type is not supported in Gemini API. + """ + + credential_secret: Optional[str] + """Required. The name of the SecretManager secret version resource storing the base64 encoded credentials. Format: `projects/{project}/secrets/{secrete}/versions/{version}` - If specified, the `secretmanager.versions.access` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified resource.""" + + +AuthConfigHttpBasicAuthConfigOrDict = Union[ + AuthConfigHttpBasicAuthConfig, AuthConfigHttpBasicAuthConfigDict +] + + +class AuthConfigOauthConfig(_common.BaseModel): + """Config for user oauth. This data type is not supported in Gemini API.""" + + access_token: Optional[str] = Field( + default=None, + description="""Access token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time.""", + ) + service_account: Optional[str] = Field( + default=None, + description="""The service account used to generate access tokens for executing the Extension. - If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the provided service account.""", + ) + + +class AuthConfigOauthConfigDict(TypedDict, total=False): + """Config for user oauth. This data type is not supported in Gemini API.""" + + access_token: Optional[str] + """Access token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time.""" + + service_account: Optional[str] + """The service account used to generate access tokens for executing the Extension. - If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the provided service account.""" + + +AuthConfigOauthConfigOrDict = Union[ + AuthConfigOauthConfig, AuthConfigOauthConfigDict +] + + +class AuthConfigOidcConfig(_common.BaseModel): + """Config for user OIDC auth. + + This data type is not supported in Gemini API. + """ + + id_token: Optional[str] = Field( + default=None, + description="""OpenID Connect formatted ID token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time.""", + ) + service_account: Optional[str] = Field( + default=None, + description="""The service account used to generate an OpenID Connect (OIDC)-compatible JWT token signed by the Google OIDC Provider (accounts.google.com) for extension endpoint (https://cloud.google.com/iam/docs/create-short-lived-credentials-direct#sa-credentials-oidc). - The audience for the token will be set to the URL in the server url defined in the OpenApi spec. - If the service account is provided, the service account should grant `iam.serviceAccounts.getOpenIdToken` permission to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents).""", + ) + + +class AuthConfigOidcConfigDict(TypedDict, total=False): + """Config for user OIDC auth. + + This data type is not supported in Gemini API. + """ + + id_token: Optional[str] + """OpenID Connect formatted ID token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time.""" + + service_account: Optional[str] + """The service account used to generate an OpenID Connect (OIDC)-compatible JWT token signed by the Google OIDC Provider (accounts.google.com) for extension endpoint (https://cloud.google.com/iam/docs/create-short-lived-credentials-direct#sa-credentials-oidc). - The audience for the token will be set to the URL in the server url defined in the OpenApi spec. - If the service account is provided, the service account should grant `iam.serviceAccounts.getOpenIdToken` permission to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents).""" + + +AuthConfigOidcConfigOrDict = Union[ + AuthConfigOidcConfig, AuthConfigOidcConfigDict +] + + +class AuthConfig(_common.BaseModel): + """The authentication config to access the API.""" + + api_key: Optional[str] = Field( + default=None, + description="""The authentication config to access the API. Only API key is supported. This field is not supported in Gemini API.""", + ) + api_key_config: Optional[ApiKeyConfig] = Field( + default=None, description="""Config for API key auth.""" + ) + auth_type: Optional[AuthType] = Field( + default=None, description="""Type of auth scheme.""" + ) + google_service_account_config: Optional[ + AuthConfigGoogleServiceAccountConfig + ] = Field( + default=None, description="""Config for Google Service Account auth.""" + ) + http_basic_auth_config: Optional[AuthConfigHttpBasicAuthConfig] = Field( + default=None, description="""Config for HTTP Basic auth.""" + ) + oauth_config: Optional[AuthConfigOauthConfig] = Field( + default=None, description="""Config for user oauth.""" + ) + oidc_config: Optional[AuthConfigOidcConfig] = Field( + default=None, description="""Config for user OIDC auth.""" + ) + + +class AuthConfigDict(TypedDict, total=False): + """The authentication config to access the API.""" + + api_key: Optional[str] + """The authentication config to access the API. Only API key is supported. This field is not supported in Gemini API.""" + + api_key_config: Optional[ApiKeyConfigDict] + """Config for API key auth.""" + + auth_type: Optional[AuthType] + """Type of auth scheme.""" + + google_service_account_config: Optional[ + AuthConfigGoogleServiceAccountConfigDict + ] + """Config for Google Service Account auth.""" + + http_basic_auth_config: Optional[AuthConfigHttpBasicAuthConfigDict] + """Config for HTTP Basic auth.""" + + oauth_config: Optional[AuthConfigOauthConfigDict] + """Config for user oauth.""" + + oidc_config: Optional[AuthConfigOidcConfigDict] + """Config for user OIDC auth.""" + + +AuthConfigOrDict = Union[AuthConfig, AuthConfigDict] + + +class GoogleMaps(_common.BaseModel): + """Tool to retrieve knowledge from Google Maps.""" + + auth_config: Optional[AuthConfig] = Field( + default=None, + description="""The authentication config to access the API. Only API key is supported. This field is not supported in Gemini API.""", + ) + enable_widget: Optional[bool] = Field( + default=None, + description="""Optional. Whether to return a widget context token in the GroundingMetadata of the response. Developers can use the widget context token to render a Google Maps widget with geospatial context related to the places that the model references in the response.""", + ) + + +class GoogleMapsDict(TypedDict, total=False): + """Tool to retrieve knowledge from Google Maps.""" + + auth_config: Optional[AuthConfigDict] + """The authentication config to access the API. Only API key is supported. This field is not supported in Gemini API.""" + + enable_widget: Optional[bool] + """Optional. Whether to return a widget context token in the GroundingMetadata of the response. Developers can use the widget context token to render a Google Maps widget with geospatial context related to the places that the model references in the response.""" + + +GoogleMapsOrDict = Union[GoogleMaps, GoogleMapsDict] + + +class ApiAuthApiKeyConfig(_common.BaseModel): + """The API secret. This data type is not supported in Gemini API.""" + + api_key_secret_version: Optional[str] = Field( + default=None, + description="""Required. The SecretManager secret version resource name storing API key. e.g. projects/{project}/secrets/{secret}/versions/{version}""", + ) + api_key_string: Optional[str] = Field( + default=None, + description="""The API key string. Either this or `api_key_secret_version` must be set.""", + ) + + +class ApiAuthApiKeyConfigDict(TypedDict, total=False): + """The API secret. This data type is not supported in Gemini API.""" + + api_key_secret_version: Optional[str] + """Required. The SecretManager secret version resource name storing API key. e.g. projects/{project}/secrets/{secret}/versions/{version}""" + + api_key_string: Optional[str] + """The API key string. Either this or `api_key_secret_version` must be set.""" + + +ApiAuthApiKeyConfigOrDict = Union[ApiAuthApiKeyConfig, ApiAuthApiKeyConfigDict] + + +class ApiAuth(_common.BaseModel): + """The generic reusable api auth config. + + Deprecated. Please use AuthConfig (google/cloud/aiplatform/master/auth.proto) + instead. This data type is not supported in Gemini API. + """ + + api_key_config: Optional[ApiAuthApiKeyConfig] = Field( + default=None, description="""The API secret.""" + ) + + +class ApiAuthDict(TypedDict, total=False): + """The generic reusable api auth config. + + Deprecated. Please use AuthConfig (google/cloud/aiplatform/master/auth.proto) + instead. This data type is not supported in Gemini API. + """ + + api_key_config: Optional[ApiAuthApiKeyConfigDict] + """The API secret.""" + + +ApiAuthOrDict = Union[ApiAuth, ApiAuthDict] + + +class ExternalApiElasticSearchParams(_common.BaseModel): + """The search parameters to use for the ELASTIC_SEARCH spec. + + This data type is not supported in Gemini API. + """ + + index: Optional[str] = Field( + default=None, description="""The ElasticSearch index to use.""" + ) + num_hits: Optional[int] = Field( + default=None, + description="""Optional. Number of hits (chunks) to request. When specified, it is passed to Elasticsearch as the `num_hits` param.""", + ) + search_template: Optional[str] = Field( + default=None, description="""The ElasticSearch search template to use.""" + ) + + +class ExternalApiElasticSearchParamsDict(TypedDict, total=False): + """The search parameters to use for the ELASTIC_SEARCH spec. + + This data type is not supported in Gemini API. + """ + + index: Optional[str] + """The ElasticSearch index to use.""" + + num_hits: Optional[int] + """Optional. Number of hits (chunks) to request. When specified, it is passed to Elasticsearch as the `num_hits` param.""" + + search_template: Optional[str] + """The ElasticSearch search template to use.""" + + +ExternalApiElasticSearchParamsOrDict = Union[ + ExternalApiElasticSearchParams, ExternalApiElasticSearchParamsDict +] + + +class ExternalApiSimpleSearchParams(_common.BaseModel): + """The search parameters to use for SIMPLE_SEARCH spec. + + This data type is not supported in Gemini API. + """ + + pass + + +class ExternalApiSimpleSearchParamsDict(TypedDict, total=False): + """The search parameters to use for SIMPLE_SEARCH spec. + + This data type is not supported in Gemini API. + """ + + pass + + +ExternalApiSimpleSearchParamsOrDict = Union[ + ExternalApiSimpleSearchParams, ExternalApiSimpleSearchParamsDict +] + + +class ExternalApi(_common.BaseModel): + """Retrieve from data source powered by external API for grounding. + + The external API is not owned by Google, but need to follow the pre-defined + API spec. This data type is not supported in Gemini API. + """ + + api_auth: Optional[ApiAuth] = Field( + default=None, + description="""The authentication config to access the API. Deprecated. Please use auth_config instead.""", + ) + api_spec: Optional[ApiSpec] = Field( + default=None, + description="""The API spec that the external API implements.""", + ) + auth_config: Optional[AuthConfig] = Field( + default=None, + description="""The authentication config to access the API.""", + ) + elastic_search_params: Optional[ExternalApiElasticSearchParams] = Field( + default=None, description="""Parameters for the elastic search API.""" + ) + endpoint: Optional[str] = Field( + default=None, + description="""The endpoint of the external API. The system will call the API at this endpoint to retrieve the data for grounding. Example: https://acme.com:443/search""", + ) + simple_search_params: Optional[ExternalApiSimpleSearchParams] = Field( + default=None, description="""Parameters for the simple search API.""" + ) + + +class ExternalApiDict(TypedDict, total=False): + """Retrieve from data source powered by external API for grounding. + + The external API is not owned by Google, but need to follow the pre-defined + API spec. This data type is not supported in Gemini API. + """ + + api_auth: Optional[ApiAuthDict] + """The authentication config to access the API. Deprecated. Please use auth_config instead.""" + + api_spec: Optional[ApiSpec] + """The API spec that the external API implements.""" + + auth_config: Optional[AuthConfigDict] + """The authentication config to access the API.""" + + elastic_search_params: Optional[ExternalApiElasticSearchParamsDict] + """Parameters for the elastic search API.""" + + endpoint: Optional[str] + """The endpoint of the external API. The system will call the API at this endpoint to retrieve the data for grounding. Example: https://acme.com:443/search""" + + simple_search_params: Optional[ExternalApiSimpleSearchParamsDict] + """Parameters for the simple search API.""" + + +ExternalApiOrDict = Union[ExternalApi, ExternalApiDict] + + +class VertexAISearchDataStoreSpec(_common.BaseModel): + """Define data stores within engine to filter on in a search call and configurations for those data stores. + + For more information, see + https://cloud.google.com/generative-ai-app-builder/docs/reference/rpc/google.cloud.discoveryengine.v1#datastorespec. + This data type is not supported in Gemini API. + """ + + data_store: Optional[str] = Field( + default=None, + description="""Full resource name of DataStore, such as Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}`""", + ) + filter: Optional[str] = Field( + default=None, + description="""Optional. Filter specification to filter documents in the data store specified by data_store field. For more information on filtering, see [Filtering](https://cloud.google.com/generative-ai-app-builder/docs/filter-search-metadata)""", + ) + + +class VertexAISearchDataStoreSpecDict(TypedDict, total=False): + """Define data stores within engine to filter on in a search call and configurations for those data stores. + + For more information, see + https://cloud.google.com/generative-ai-app-builder/docs/reference/rpc/google.cloud.discoveryengine.v1#datastorespec. + This data type is not supported in Gemini API. + """ + + data_store: Optional[str] + """Full resource name of DataStore, such as Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}`""" + + filter: Optional[str] + """Optional. Filter specification to filter documents in the data store specified by data_store field. For more information on filtering, see [Filtering](https://cloud.google.com/generative-ai-app-builder/docs/filter-search-metadata)""" + + +VertexAISearchDataStoreSpecOrDict = Union[ + VertexAISearchDataStoreSpec, VertexAISearchDataStoreSpecDict +] + + +class VertexAISearch(_common.BaseModel): + """Retrieve from Vertex AI Search datastore or engine for grounding. + + datastore and engine are mutually exclusive. See + https://cloud.google.com/products/agent-builder. This data type is not + supported in Gemini API. + """ + + data_store_specs: Optional[list[VertexAISearchDataStoreSpec]] = Field( + default=None, + description="""Specifications that define the specific DataStores to be searched, along with configurations for those data stores. This is only considered for Engines with multiple data stores. It should only be set if engine is used.""", + ) + datastore: Optional[str] = Field( + default=None, + description="""Optional. Fully-qualified Vertex AI Search data store resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}`""", + ) + engine: Optional[str] = Field( + default=None, + description="""Optional. Fully-qualified Vertex AI Search engine resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/engines/{engine}`""", + ) + filter: Optional[str] = Field( + default=None, + description="""Optional. Filter strings to be passed to the search API.""", + ) + max_results: Optional[int] = Field( + default=None, + description="""Optional. Number of search results to return per query. The default value is 10. The maximumm allowed value is 10.""", + ) + + +class VertexAISearchDict(TypedDict, total=False): + """Retrieve from Vertex AI Search datastore or engine for grounding. + + datastore and engine are mutually exclusive. See + https://cloud.google.com/products/agent-builder. This data type is not + supported in Gemini API. + """ + + data_store_specs: Optional[list[VertexAISearchDataStoreSpecDict]] + """Specifications that define the specific DataStores to be searched, along with configurations for those data stores. This is only considered for Engines with multiple data stores. It should only be set if engine is used.""" + + datastore: Optional[str] + """Optional. Fully-qualified Vertex AI Search data store resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}`""" + + engine: Optional[str] + """Optional. Fully-qualified Vertex AI Search engine resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/engines/{engine}`""" + + filter: Optional[str] + """Optional. Filter strings to be passed to the search API.""" + + max_results: Optional[int] + """Optional. Number of search results to return per query. The default value is 10. The maximumm allowed value is 10.""" + + +VertexAISearchOrDict = Union[VertexAISearch, VertexAISearchDict] + + +class VertexRagStoreRagResource(_common.BaseModel): + """The definition of the Rag resource. + + This data type is not supported in Gemini API. + """ + + rag_corpus: Optional[str] = Field( + default=None, + description="""Optional. RagCorpora resource name. Format: `projects/{project}/locations/{location}/ragCorpora/{rag_corpus}`""", + ) + rag_file_ids: Optional[list[str]] = Field( + default=None, + description="""Optional. rag_file_id. The files should be in the same rag_corpus set in rag_corpus field.""", + ) + + +class VertexRagStoreRagResourceDict(TypedDict, total=False): + """The definition of the Rag resource. + + This data type is not supported in Gemini API. + """ + + rag_corpus: Optional[str] + """Optional. RagCorpora resource name. Format: `projects/{project}/locations/{location}/ragCorpora/{rag_corpus}`""" + + rag_file_ids: Optional[list[str]] + """Optional. rag_file_id. The files should be in the same rag_corpus set in rag_corpus field.""" + + +VertexRagStoreRagResourceOrDict = Union[ + VertexRagStoreRagResource, VertexRagStoreRagResourceDict +] + + +class RagRetrievalConfigFilter(_common.BaseModel): + """Config for filters. This data type is not supported in Gemini API.""" + + metadata_filter: Optional[str] = Field( + default=None, description="""Optional. String for metadata filtering.""" + ) + vector_distance_threshold: Optional[float] = Field( + default=None, + description="""Optional. Only returns contexts with vector distance smaller than the threshold.""", + ) + vector_similarity_threshold: Optional[float] = Field( + default=None, + description="""Optional. Only returns contexts with vector similarity larger than the threshold.""", + ) + + +class RagRetrievalConfigFilterDict(TypedDict, total=False): + """Config for filters. This data type is not supported in Gemini API.""" + + metadata_filter: Optional[str] + """Optional. String for metadata filtering.""" + + vector_distance_threshold: Optional[float] + """Optional. Only returns contexts with vector distance smaller than the threshold.""" + + vector_similarity_threshold: Optional[float] + """Optional. Only returns contexts with vector similarity larger than the threshold.""" + + +RagRetrievalConfigFilterOrDict = Union[ + RagRetrievalConfigFilter, RagRetrievalConfigFilterDict +] + + +class RagRetrievalConfigHybridSearch(_common.BaseModel): + """Config for Hybrid Search. This data type is not supported in Gemini API.""" + + alpha: Optional[float] = Field( + default=None, + description="""Optional. Alpha value controls the weight between dense and sparse vector search results. The range is [0, 1], while 0 means sparse vector search only and 1 means dense vector search only. The default value is 0.5 which balances sparse and dense vector search equally.""", + ) + + +class RagRetrievalConfigHybridSearchDict(TypedDict, total=False): + """Config for Hybrid Search. This data type is not supported in Gemini API.""" + + alpha: Optional[float] + """Optional. Alpha value controls the weight between dense and sparse vector search results. The range is [0, 1], while 0 means sparse vector search only and 1 means dense vector search only. The default value is 0.5 which balances sparse and dense vector search equally.""" + + +RagRetrievalConfigHybridSearchOrDict = Union[ + RagRetrievalConfigHybridSearch, RagRetrievalConfigHybridSearchDict +] + + +class RagRetrievalConfigRankingLlmRanker(_common.BaseModel): + """Config for LlmRanker. This data type is not supported in Gemini API.""" + + model_name: Optional[str] = Field( + default=None, + description="""Optional. The model name used for ranking. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported-models).""", + ) + + +class RagRetrievalConfigRankingLlmRankerDict(TypedDict, total=False): + """Config for LlmRanker. This data type is not supported in Gemini API.""" + + model_name: Optional[str] + """Optional. The model name used for ranking. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported-models).""" + + +RagRetrievalConfigRankingLlmRankerOrDict = Union[ + RagRetrievalConfigRankingLlmRanker, RagRetrievalConfigRankingLlmRankerDict +] + + +class RagRetrievalConfigRankingRankService(_common.BaseModel): + """Config for Rank Service. This data type is not supported in Gemini API.""" + + model_name: Optional[str] = Field( + default=None, + description="""Optional. The model name of the rank service. Format: `semantic-ranker-512@latest`""", + ) + + +class RagRetrievalConfigRankingRankServiceDict(TypedDict, total=False): + """Config for Rank Service. This data type is not supported in Gemini API.""" + + model_name: Optional[str] + """Optional. The model name of the rank service. Format: `semantic-ranker-512@latest`""" + + +RagRetrievalConfigRankingRankServiceOrDict = Union[ + RagRetrievalConfigRankingRankService, + RagRetrievalConfigRankingRankServiceDict, +] + + +class RagRetrievalConfigRanking(_common.BaseModel): + """Config for ranking and reranking. + + This data type is not supported in Gemini API. + """ + + llm_ranker: Optional[RagRetrievalConfigRankingLlmRanker] = Field( + default=None, description="""Optional. Config for LlmRanker.""" + ) + rank_service: Optional[RagRetrievalConfigRankingRankService] = Field( + default=None, description="""Optional. Config for Rank Service.""" + ) + + +class RagRetrievalConfigRankingDict(TypedDict, total=False): + """Config for ranking and reranking. + + This data type is not supported in Gemini API. + """ + + llm_ranker: Optional[RagRetrievalConfigRankingLlmRankerDict] + """Optional. Config for LlmRanker.""" + + rank_service: Optional[RagRetrievalConfigRankingRankServiceDict] + """Optional. Config for Rank Service.""" + + +RagRetrievalConfigRankingOrDict = Union[ + RagRetrievalConfigRanking, RagRetrievalConfigRankingDict +] + + +class RagRetrievalConfig(_common.BaseModel): + """Specifies the context retrieval config. + + This data type is not supported in Gemini API. + """ + + filter: Optional[RagRetrievalConfigFilter] = Field( + default=None, description="""Optional. Config for filters.""" + ) + hybrid_search: Optional[RagRetrievalConfigHybridSearch] = Field( + default=None, description="""Optional. Config for Hybrid Search.""" + ) + ranking: Optional[RagRetrievalConfigRanking] = Field( + default=None, + description="""Optional. Config for ranking and reranking.""", + ) + top_k: Optional[int] = Field( + default=None, + description="""Optional. The number of contexts to retrieve.""", + ) + + +class RagRetrievalConfigDict(TypedDict, total=False): + """Specifies the context retrieval config. + + This data type is not supported in Gemini API. + """ + + filter: Optional[RagRetrievalConfigFilterDict] + """Optional. Config for filters.""" + + hybrid_search: Optional[RagRetrievalConfigHybridSearchDict] + """Optional. Config for Hybrid Search.""" + + ranking: Optional[RagRetrievalConfigRankingDict] + """Optional. Config for ranking and reranking.""" + + top_k: Optional[int] + """Optional. The number of contexts to retrieve.""" + + +RagRetrievalConfigOrDict = Union[RagRetrievalConfig, RagRetrievalConfigDict] + + +class VertexRagStore(_common.BaseModel): + """Retrieve from Vertex RAG Store for grounding. + + This data type is not supported in Gemini API. + """ + + rag_corpora: Optional[list[str]] = Field( + default=None, + description="""Optional. Deprecated. Please use rag_resources instead.""", + ) + rag_resources: Optional[list[VertexRagStoreRagResource]] = Field( + default=None, + description="""Optional. The representation of the rag source. It can be used to specify corpus only or ragfiles. Currently only support one corpus or multiple files from one corpus. In the future we may open up multiple corpora support.""", + ) + rag_retrieval_config: Optional[RagRetrievalConfig] = Field( + default=None, + description="""Optional. The retrieval config for the Rag query.""", + ) + similarity_top_k: Optional[int] = Field( + default=None, + description="""Optional. Number of top k results to return from the selected corpora.""", + ) + store_context: Optional[bool] = Field( + default=None, + description="""Optional. Currently only supported for Gemini Multimodal Live API. In Gemini Multimodal Live API, if `store_context` bool is specified, Gemini will leverage it to automatically memorize the interactions between the client and Gemini, and retrieve context when needed to augment the response generation for users' ongoing and future interactions.""", + ) + vector_distance_threshold: Optional[float] = Field( + default=None, + description="""Optional. Only return results with vector distance smaller than the threshold.""", + ) + + +class VertexRagStoreDict(TypedDict, total=False): + """Retrieve from Vertex RAG Store for grounding. + + This data type is not supported in Gemini API. + """ + + rag_corpora: Optional[list[str]] + """Optional. Deprecated. Please use rag_resources instead.""" + + rag_resources: Optional[list[VertexRagStoreRagResourceDict]] + """Optional. The representation of the rag source. It can be used to specify corpus only or ragfiles. Currently only support one corpus or multiple files from one corpus. In the future we may open up multiple corpora support.""" + + rag_retrieval_config: Optional[RagRetrievalConfigDict] + """Optional. The retrieval config for the Rag query.""" + + similarity_top_k: Optional[int] + """Optional. Number of top k results to return from the selected corpora.""" + + store_context: Optional[bool] + """Optional. Currently only supported for Gemini Multimodal Live API. In Gemini Multimodal Live API, if `store_context` bool is specified, Gemini will leverage it to automatically memorize the interactions between the client and Gemini, and retrieve context when needed to augment the response generation for users' ongoing and future interactions.""" + + vector_distance_threshold: Optional[float] + """Optional. Only return results with vector distance smaller than the threshold.""" + + +VertexRagStoreOrDict = Union[VertexRagStore, VertexRagStoreDict] + + +class Retrieval(_common.BaseModel): + """Defines a retrieval tool that model can call to access external knowledge. + + This data type is not supported in Gemini API. + """ + + disable_attribution: Optional[bool] = Field( + default=None, + description="""Optional. Deprecated. This option is no longer supported.""", + ) + external_api: Optional[ExternalApi] = Field( + default=None, + description="""Use data source powered by external API for grounding.""", + ) + vertex_ai_search: Optional[VertexAISearch] = Field( + default=None, + description="""Set to use data source powered by Vertex AI Search.""", + ) + vertex_rag_store: Optional[VertexRagStore] = Field( + default=None, + description="""Set to use data source powered by Vertex RAG store. User data is uploaded via the VertexRagDataService.""", + ) + + +class RetrievalDict(TypedDict, total=False): + """Defines a retrieval tool that model can call to access external knowledge. + + This data type is not supported in Gemini API. + """ + + disable_attribution: Optional[bool] + """Optional. Deprecated. This option is no longer supported.""" + + external_api: Optional[ExternalApiDict] + """Use data source powered by external API for grounding.""" + + vertex_ai_search: Optional[VertexAISearchDict] + """Set to use data source powered by Vertex AI Search.""" + + vertex_rag_store: Optional[VertexRagStoreDict] + """Set to use data source powered by Vertex RAG store. User data is uploaded via the VertexRagDataService.""" + + +RetrievalOrDict = Union[Retrieval, RetrievalDict] + + +class FileSearch(_common.BaseModel): + """The FileSearch tool that retrieves knowledge from Semantic Retrieval corpora. + + Files are imported to Semantic Retrieval corpora using the ImportFile API. + This data type is not supported in Vertex AI. + """ + + file_search_store_names: Optional[list[str]] = Field( + default=None, + description="""Required. The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`""", + ) + top_k: Optional[int] = Field( + default=None, + description="""Optional. The number of semantic retrieval chunks to retrieve.""", + ) + metadata_filter: Optional[str] = Field( + default=None, + description="""Optional. Metadata filter to apply to the semantic retrieval documents and chunks.""", + ) + + +class FileSearchDict(TypedDict, total=False): + """The FileSearch tool that retrieves knowledge from Semantic Retrieval corpora. + + Files are imported to Semantic Retrieval corpora using the ImportFile API. + This data type is not supported in Vertex AI. + """ + + file_search_store_names: Optional[list[str]] + """Required. The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`""" + + top_k: Optional[int] + """Optional. The number of semantic retrieval chunks to retrieve.""" + + metadata_filter: Optional[str] + """Optional. Metadata filter to apply to the semantic retrieval documents and chunks.""" + + +FileSearchOrDict = Union[FileSearch, FileSearchDict] + + +class WebSearch(_common.BaseModel): + """Standard web search for grounding and related configurations. + + Only text results are returned. + """ + + pass + + +class WebSearchDict(TypedDict, total=False): + """Standard web search for grounding and related configurations. + + Only text results are returned. + """ + + pass + + +WebSearchOrDict = Union[WebSearch, WebSearchDict] + + +class ImageSearch(_common.BaseModel): + """Image search for grounding and related configurations.""" + + pass + + +class ImageSearchDict(TypedDict, total=False): + """Image search for grounding and related configurations.""" + + pass + + +ImageSearchOrDict = Union[ImageSearch, ImageSearchDict] + + +class SearchTypes(_common.BaseModel): + """Different types of search that can be enabled on the GoogleSearch tool.""" + + web_search: Optional[WebSearch] = Field( + default=None, + description="""Optional. Setting this field enables web search. Only text results are returned.""", + ) + image_search: Optional[ImageSearch] = Field( + default=None, + description="""Optional. Setting this field enables image search. Image bytes are returned.""", + ) + + +class SearchTypesDict(TypedDict, total=False): + """Different types of search that can be enabled on the GoogleSearch tool.""" + + web_search: Optional[WebSearchDict] + """Optional. Setting this field enables web search. Only text results are returned.""" + + image_search: Optional[ImageSearchDict] + """Optional. Setting this field enables image search. Image bytes are returned.""" + + +SearchTypesOrDict = Union[SearchTypes, SearchTypesDict] + + +class Interval(_common.BaseModel): + """Represents a time interval, encoded as a Timestamp start (inclusive) and a Timestamp end (exclusive). + + The start must be less than or equal to the end. When the start equals the + end, the interval is empty (matches no time). When both start and end are + unspecified, the interval matches any time. + """ + + end_time: Optional[datetime.datetime] = Field( + default=None, + description="""Optional. Exclusive end of the interval. If specified, a Timestamp matching this interval will have to be before the end.""", + ) + start_time: Optional[datetime.datetime] = Field( + default=None, + description="""Optional. Inclusive start of the interval. If specified, a Timestamp matching this interval will have to be the same or after the start.""", + ) + + +class IntervalDict(TypedDict, total=False): + """Represents a time interval, encoded as a Timestamp start (inclusive) and a Timestamp end (exclusive). + + The start must be less than or equal to the end. When the start equals the + end, the interval is empty (matches no time). When both start and end are + unspecified, the interval matches any time. + """ + + end_time: Optional[datetime.datetime] + """Optional. Exclusive end of the interval. If specified, a Timestamp matching this interval will have to be before the end.""" + + start_time: Optional[datetime.datetime] + """Optional. Inclusive start of the interval. If specified, a Timestamp matching this interval will have to be the same or after the start.""" + + +IntervalOrDict = Union[Interval, IntervalDict] + + +class GoogleSearch(_common.BaseModel): + """GoogleSearch tool type. + + Tool to support Google Search in Model. Powered by Google. + """ + + search_types: Optional[SearchTypes] = Field( + default=None, + description="""Optional. The set of search types to enable. If not set, web search is enabled by default.""", + ) + blocking_confidence: Optional[PhishBlockThreshold] = Field( + default=None, + description="""Optional. Sites with confidence level chosen & above this value will be blocked from the search results. This field is not supported in Gemini API.""", + ) + exclude_domains: Optional[list[str]] = Field( + default=None, + description="""Optional. List of domains to be excluded from the search results. The default limit is 2000 domains. Example: ["amazon.com", "facebook.com"]. This field is not supported in Gemini API.""", + ) + time_range_filter: Optional[Interval] = Field( + default=None, + description="""Optional. Filter search results to a specific time range. If customers set a start time, they must set an end time (and vice versa). This field is not supported in Vertex AI.""", + ) + + +class GoogleSearchDict(TypedDict, total=False): + """GoogleSearch tool type. + + Tool to support Google Search in Model. Powered by Google. + """ + + search_types: Optional[SearchTypesDict] + """Optional. The set of search types to enable. If not set, web search is enabled by default.""" + + blocking_confidence: Optional[PhishBlockThreshold] + """Optional. Sites with confidence level chosen & above this value will be blocked from the search results. This field is not supported in Gemini API.""" + + exclude_domains: Optional[list[str]] + """Optional. List of domains to be excluded from the search results. The default limit is 2000 domains. Example: ["amazon.com", "facebook.com"]. This field is not supported in Gemini API.""" + + time_range_filter: Optional[IntervalDict] + """Optional. Filter search results to a specific time range. If customers set a start time, they must set an end time (and vice versa). This field is not supported in Vertex AI.""" + + +GoogleSearchOrDict = Union[GoogleSearch, GoogleSearchDict] + + +class ToolCodeExecution(_common.BaseModel): + """Tool that executes code generated by the model, and automatically returns the result to the model. + + See also [ExecutableCode]and [CodeExecutionResult] which are input and output + to this tool. This data type is not supported in Gemini API. + """ + + pass + + +class ToolCodeExecutionDict(TypedDict, total=False): + """Tool that executes code generated by the model, and automatically returns the result to the model. + + See also [ExecutableCode]and [CodeExecutionResult] which are input and output + to this tool. This data type is not supported in Gemini API. + """ + + pass + + +ToolCodeExecutionOrDict = Union[ToolCodeExecution, ToolCodeExecutionDict] + + +class EnterpriseWebSearch(_common.BaseModel): + """Tool to search public web data, powered by Vertex AI Search and Sec4 compliance. + + This data type is not supported in Gemini API. + """ + + blocking_confidence: Optional[PhishBlockThreshold] = Field( + default=None, + description="""Optional. Sites with confidence level chosen & above this value will be blocked from the search results.""", + ) + exclude_domains: Optional[list[str]] = Field( + default=None, + description="""Optional. List of domains to be excluded from the search results. The default limit is 2000 domains.""", + ) + + +class EnterpriseWebSearchDict(TypedDict, total=False): + """Tool to search public web data, powered by Vertex AI Search and Sec4 compliance. + + This data type is not supported in Gemini API. + """ + + blocking_confidence: Optional[PhishBlockThreshold] + """Optional. Sites with confidence level chosen & above this value will be blocked from the search results.""" + + exclude_domains: Optional[list[str]] + """Optional. List of domains to be excluded from the search results. The default limit is 2000 domains.""" + + +EnterpriseWebSearchOrDict = Union[EnterpriseWebSearch, EnterpriseWebSearchDict] + + +class FunctionDeclaration(_common.BaseModel): + """Structured representation of a function declaration as defined by the [OpenAPI 3.0 specification](https://spec.openapis.org/oas/v3.0.3). + + Included in this declaration are the function name, description, parameters + and response type. This FunctionDeclaration is a representation of a block of + code that can be used as a `Tool` by the model and executed by the client. + """ + + description: Optional[str] = Field( + default=None, + description="""Optional. Description and purpose of the function. Model uses it to decide how and whether to call the function.""", + ) + name: Optional[str] = Field( + default=None, + description="""Required. The name of the function to call. Must start with a letter or an underscore. Must be a-z, A-Z, 0-9, or contain underscores, dots, colons and dashes, with a maximum length of 64.""", + ) + parameters: Optional[Schema] = Field( + default=None, + description="""Optional. Describes the parameters to this function in JSON Schema Object format. Reflects the Open API 3.03 Parameter Object. string Key: the name of the parameter. Parameter names are case sensitive. Schema Value: the Schema defining the type used for the parameter. For function with no parameters, this can be left unset. Parameter names must start with a letter or an underscore and must only contain chars a-z, A-Z, 0-9, or underscores with a maximum length of 64. Example with 1 required and 1 optional parameter: type: OBJECT properties: param1: type: STRING param2: type: INTEGER required: - param1""", + ) + parameters_json_schema: Optional[Any] = Field( + default=None, + description="""Optional. Describes the parameters to the function in JSON Schema format. The schema must describe an object where the properties are the parameters to the function. For example: ``` { "type": "object", "properties": { "name": { "type": "string" }, "age": { "type": "integer" } }, "additionalProperties": false, "required": ["name", "age"], "propertyOrdering": ["name", "age"] } ``` This field is mutually exclusive with `parameters`.""", + ) + response: Optional[Schema] = Field( + default=None, + description="""Optional. Describes the output from this function in JSON Schema format. Reflects the Open API 3.03 Response Object. The Schema defines the type used for the response value of the function.""", + ) + response_json_schema: Optional[Any] = Field( + default=None, + description="""Optional. Describes the output from this function in JSON Schema format. The value specified by the schema is the response value of the function. This field is mutually exclusive with `response`.""", + ) + behavior: Optional[Behavior] = Field( + default=None, + description="""Optional. Specifies the function Behavior. Currently only supported by the BidiGenerateContent method. This field is not supported in Vertex AI.""", + ) + + @classmethod + def from_callable_with_api_option( + cls, + *, + callable: Callable[..., Any], + api_option: Literal['VERTEX_AI', 'GEMINI_API'] = 'GEMINI_API', + behavior: Optional[Behavior] = None, + ) -> 'FunctionDeclaration': + """Converts a Callable to a FunctionDeclaration based on the API option. + + Supported API option is 'VERTEX_AI' or 'GEMINI_API'. If api_option is unset, + it will default to 'GEMINI_API'. If unsupported api_option is provided, it + will raise ValueError. + """ + supported_api_options = ['VERTEX_AI', 'GEMINI_API'] + if api_option not in supported_api_options: + raise ValueError( + f'Unsupported api_option value: {api_option}. Supported api_option' + f' value is one of: {supported_api_options}.' + ) + from . import _automatic_function_calling_util + + parameters_properties = {} + parameters_json_schema = {} + annotation_under_future = typing.get_type_hints(callable) + try: + for name, param in inspect.signature(callable).parameters.items(): + if param.kind in ( + inspect.Parameter.POSITIONAL_OR_KEYWORD, + inspect.Parameter.KEYWORD_ONLY, + inspect.Parameter.POSITIONAL_ONLY, + ): + param = _automatic_function_calling_util._handle_params_as_deferred_annotations( + param, annotation_under_future, name + ) + schema = ( + _automatic_function_calling_util._parse_schema_from_parameter( + api_option, param, callable.__name__ + ) + ) + parameters_properties[name] = schema + except ValueError: + parameters_properties = {} + for name, param in inspect.signature(callable).parameters.items(): + if param.kind in ( + inspect.Parameter.POSITIONAL_OR_KEYWORD, + inspect.Parameter.KEYWORD_ONLY, + inspect.Parameter.POSITIONAL_ONLY, + ): + try: + param = _automatic_function_calling_util._handle_params_as_deferred_annotations( + param, annotation_under_future, name + ) + param_schema_adapter = pydantic.TypeAdapter( + param.annotation, + config=pydantic.ConfigDict(arbitrary_types_allowed=True), + ) + json_schema_dict = param_schema_adapter.json_schema() + json_schema_dict = _automatic_function_calling_util._add_unevaluated_items_to_fixed_len_tuple_schema( + json_schema_dict + ) + if 'prefixItems' in json_schema_dict: + parameters_json_schema[name] = json_schema_dict + continue + + union_args = typing.get_args(param.annotation) + has_primitive = any( + _automatic_function_calling_util._is_builtin_primitive_or_compound( + arg + ) + for arg in union_args + ) + if ( + '$ref' in json_schema_dict or '$defs' in json_schema_dict + ) and has_primitive: + # This is a complex schema with a primitive (e.g., str | MyModel) + # that is better represented by raw JSON schema. + parameters_json_schema[name] = json_schema_dict + continue + + schema = Schema.from_json_schema( + json_schema=JSONSchema(**json_schema_dict), + api_option=api_option, + ) + if param.default is not inspect.Parameter.empty: + schema.default = param.default + parameters_properties[name] = schema + except Exception as e: + _automatic_function_calling_util._raise_for_unsupported_param( + param, callable.__name__, e + ) + + declaration = FunctionDeclaration( + name=callable.__name__, + description=inspect.cleandoc(callable.__doc__) + if callable.__doc__ + else callable.__doc__, + behavior=behavior, + ) + if parameters_properties: + declaration.parameters = Schema( + type='OBJECT', + properties=parameters_properties, + ) + declaration.parameters.required = ( + _automatic_function_calling_util._get_required_fields( + declaration.parameters + ) + ) + elif parameters_json_schema: + declaration.parameters_json_schema = parameters_json_schema + # TODO: b/421991354 - Remove this check once the bug is fixed. + if api_option == 'GEMINI_API': + return declaration + + return_annotation = inspect.signature(callable).return_annotation + if return_annotation is inspect._empty: + return declaration + + return_value = inspect.Parameter( + 'return_value', + inspect.Parameter.POSITIONAL_OR_KEYWORD, + annotation=return_annotation, + ) + + # This snippet catches the case when type hints are stored as strings + if isinstance(return_value.annotation, str): + return_value = return_value.replace( + annotation=annotation_under_future['return'] + ) + response_schema: Optional[Schema] = None + response_json_schema: Optional[Union[dict[str, Any], Schema]] = {} + try: + response_schema = ( + _automatic_function_calling_util._parse_schema_from_parameter( + api_option, + return_value, + callable.__name__, + ) + ) + if response_schema.any_of is not None: + # To handle any_of, we need to use responseJsonSchema + response_json_schema = response_schema + response_schema = None + except ValueError: + try: + return_value_schema_adapter = pydantic.TypeAdapter( + return_value.annotation, + config=pydantic.ConfigDict(arbitrary_types_allowed=True), + ) + response_json_schema = return_value_schema_adapter.json_schema() + response_json_schema = _automatic_function_calling_util._add_unevaluated_items_to_fixed_len_tuple_schema( + response_json_schema + ) + except Exception as e: + _automatic_function_calling_util._raise_for_unsupported_param( + return_value, callable.__name__, e + ) + + if response_schema: + declaration.response = response_schema + elif response_json_schema: + declaration.response_json_schema = response_json_schema + return declaration + + @classmethod + def from_callable( + cls, + *, + client: 'BaseApiClient', + callable: Callable[..., Any], + behavior: Optional[Behavior] = None, + ) -> 'FunctionDeclaration': + """Converts a Callable to a FunctionDeclaration based on the client. + + Note: For best results prefer + [Google-style + docstring](https://google.github.io/styleguide/pyguide.html#383-functions-and-methods) + when describing arguments. This function does **not** parse argument + descriptions into the property description slots of the resulting structure. + Instead it sends the whole docstring in the top-level function description. + Google-style docstring are closest to what the model is trained on. + """ + if client.vertexai: + return cls.from_callable_with_api_option( + callable=callable, api_option='VERTEX_AI', behavior=behavior + ) + else: + return cls.from_callable_with_api_option( + callable=callable, api_option='GEMINI_API', behavior=behavior + ) + + +class FunctionDeclarationDict(TypedDict, total=False): + """Structured representation of a function declaration as defined by the [OpenAPI 3.0 specification](https://spec.openapis.org/oas/v3.0.3). + + Included in this declaration are the function name, description, parameters + and response type. This FunctionDeclaration is a representation of a block of + code that can be used as a `Tool` by the model and executed by the client. + """ + + description: Optional[str] + """Optional. Description and purpose of the function. Model uses it to decide how and whether to call the function.""" + + name: Optional[str] + """Required. The name of the function to call. Must start with a letter or an underscore. Must be a-z, A-Z, 0-9, or contain underscores, dots, colons and dashes, with a maximum length of 64.""" + + parameters: Optional[SchemaDict] + """Optional. Describes the parameters to this function in JSON Schema Object format. Reflects the Open API 3.03 Parameter Object. string Key: the name of the parameter. Parameter names are case sensitive. Schema Value: the Schema defining the type used for the parameter. For function with no parameters, this can be left unset. Parameter names must start with a letter or an underscore and must only contain chars a-z, A-Z, 0-9, or underscores with a maximum length of 64. Example with 1 required and 1 optional parameter: type: OBJECT properties: param1: type: STRING param2: type: INTEGER required: - param1""" + + parameters_json_schema: Optional[Any] + """Optional. Describes the parameters to the function in JSON Schema format. The schema must describe an object where the properties are the parameters to the function. For example: ``` { "type": "object", "properties": { "name": { "type": "string" }, "age": { "type": "integer" } }, "additionalProperties": false, "required": ["name", "age"], "propertyOrdering": ["name", "age"] } ``` This field is mutually exclusive with `parameters`.""" + + response: Optional[SchemaDict] + """Optional. Describes the output from this function in JSON Schema format. Reflects the Open API 3.03 Response Object. The Schema defines the type used for the response value of the function.""" + + response_json_schema: Optional[Any] + """Optional. Describes the output from this function in JSON Schema format. The value specified by the schema is the response value of the function. This field is mutually exclusive with `response`.""" + + behavior: Optional[Behavior] + """Optional. Specifies the function Behavior. Currently only supported by the BidiGenerateContent method. This field is not supported in Vertex AI.""" + + +FunctionDeclarationOrDict = Union[FunctionDeclaration, FunctionDeclarationDict] + + +class DynamicRetrievalConfig(_common.BaseModel): + """Describes the options to customize dynamic retrieval.""" + + dynamic_threshold: Optional[float] = Field( + default=None, + description="""Optional. The threshold to be used in dynamic retrieval. If not set, a system default value is used.""", + ) + mode: Optional[DynamicRetrievalConfigMode] = Field( + default=None, + description="""The mode of the predictor to be used in dynamic retrieval.""", + ) + + +class DynamicRetrievalConfigDict(TypedDict, total=False): + """Describes the options to customize dynamic retrieval.""" + + dynamic_threshold: Optional[float] + """Optional. The threshold to be used in dynamic retrieval. If not set, a system default value is used.""" + + mode: Optional[DynamicRetrievalConfigMode] + """The mode of the predictor to be used in dynamic retrieval.""" + + +DynamicRetrievalConfigOrDict = Union[ + DynamicRetrievalConfig, DynamicRetrievalConfigDict +] + + +class GoogleSearchRetrieval(_common.BaseModel): + """Tool to retrieve public web data for grounding, powered by Google.""" + + dynamic_retrieval_config: Optional[DynamicRetrievalConfig] = Field( + default=None, + description="""Specifies the dynamic retrieval configuration for the given source.""", + ) + + +class GoogleSearchRetrievalDict(TypedDict, total=False): + """Tool to retrieve public web data for grounding, powered by Google.""" + + dynamic_retrieval_config: Optional[DynamicRetrievalConfigDict] + """Specifies the dynamic retrieval configuration for the given source.""" + + +GoogleSearchRetrievalOrDict = Union[ + GoogleSearchRetrieval, GoogleSearchRetrievalDict +] + + +class ToolParallelAiSearch(_common.BaseModel): + """ParallelAiSearch tool type. + + A tool that uses the Parallel.ai search engine for grounding. This data type + is not supported in Gemini API. + """ + + api_key: Optional[str] = Field( + default=None, + description="""Optional. The API key for ParallelAiSearch. If an API key is not provided, the system will attempt to verify access by checking for an active Parallel.ai subscription through the Google Cloud Marketplace. See https://docs.parallel.ai/search/search-quickstart for more details.""", + ) + custom_configs: Optional[dict[str, Any]] = Field( + default=None, + description="""Optional. Custom configs for ParallelAiSearch. This field can be used to pass any parameter from the Parallel.ai Search API. See the Parallel.ai documentation for the full list of available parameters and their usage: https://docs.parallel.ai/api-reference/search-beta/search Currently only `source_policy`, `excerpts`, `max_results`, `mode`, `fetch_policy` can be set via this field. For example: { "source_policy": { "include_domains": ["google.com", "wikipedia.org"], "exclude_domains": ["example.com"] }, "fetch_policy": { "max_age_seconds": 3600 } }""", + ) + + +class ToolParallelAiSearchDict(TypedDict, total=False): + """ParallelAiSearch tool type. + + A tool that uses the Parallel.ai search engine for grounding. This data type + is not supported in Gemini API. + """ + + api_key: Optional[str] + """Optional. The API key for ParallelAiSearch. If an API key is not provided, the system will attempt to verify access by checking for an active Parallel.ai subscription through the Google Cloud Marketplace. See https://docs.parallel.ai/search/search-quickstart for more details.""" + + custom_configs: Optional[dict[str, Any]] + """Optional. Custom configs for ParallelAiSearch. This field can be used to pass any parameter from the Parallel.ai Search API. See the Parallel.ai documentation for the full list of available parameters and their usage: https://docs.parallel.ai/api-reference/search-beta/search Currently only `source_policy`, `excerpts`, `max_results`, `mode`, `fetch_policy` can be set via this field. For example: { "source_policy": { "include_domains": ["google.com", "wikipedia.org"], "exclude_domains": ["example.com"] }, "fetch_policy": { "max_age_seconds": 3600 } }""" + + +ToolParallelAiSearchOrDict = Union[ + ToolParallelAiSearch, ToolParallelAiSearchDict +] + + +class UrlContext(_common.BaseModel): + """Tool to support URL context.""" + + pass + + +class UrlContextDict(TypedDict, total=False): + """Tool to support URL context.""" + + pass + + +UrlContextOrDict = Union[UrlContext, UrlContextDict] + + +class StreamableHttpTransport(_common.BaseModel): + """A transport that can stream HTTP requests and responses. + + Next ID: 6. This data type is not supported in Vertex AI. + """ + + headers: Optional[dict[str, str]] = Field( + default=None, + description="""Optional: Fields for authentication headers, timeouts, etc., if needed.""", + ) + sse_read_timeout: Optional[str] = Field( + default=None, description="""Timeout for SSE read operations.""" + ) + terminate_on_close: Optional[bool] = Field( + default=None, + description="""Whether to close the client session when the transport closes.""", + ) + timeout: Optional[str] = Field( + default=None, description="""HTTP timeout for regular operations.""" + ) + url: Optional[str] = Field( + default=None, + description="""The full URL for the MCPServer endpoint. Example: "https://api.example.com/mcp".""", + ) + + +class StreamableHttpTransportDict(TypedDict, total=False): + """A transport that can stream HTTP requests and responses. + + Next ID: 6. This data type is not supported in Vertex AI. + """ + + headers: Optional[dict[str, str]] + """Optional: Fields for authentication headers, timeouts, etc., if needed.""" + + sse_read_timeout: Optional[str] + """Timeout for SSE read operations.""" + + terminate_on_close: Optional[bool] + """Whether to close the client session when the transport closes.""" + + timeout: Optional[str] + """HTTP timeout for regular operations.""" + + url: Optional[str] + """The full URL for the MCPServer endpoint. Example: "https://api.example.com/mcp".""" + + +StreamableHttpTransportOrDict = Union[ + StreamableHttpTransport, StreamableHttpTransportDict +] + + +class McpServer(_common.BaseModel): + """A MCPServer is a server that can be called by the model to perform actions. + + It is a server that implements the MCP protocol. Next ID: 5. This data type is + not supported in Vertex AI. + """ + + name: Optional[str] = Field( + default=None, description="""The name of the MCPServer.""" + ) + streamable_http_transport: Optional[StreamableHttpTransport] = Field( + default=None, + description="""A transport that can stream HTTP requests and responses.""", + ) + + +class McpServerDict(TypedDict, total=False): + """A MCPServer is a server that can be called by the model to perform actions. + + It is a server that implements the MCP protocol. Next ID: 5. This data type is + not supported in Vertex AI. + """ + + name: Optional[str] + """The name of the MCPServer.""" + + streamable_http_transport: Optional[StreamableHttpTransportDict] + """A transport that can stream HTTP requests and responses.""" + + +McpServerOrDict = Union[McpServer, McpServerDict] + + +class Tool(_common.BaseModel): + """Tool details of a tool that the model may use to generate a response.""" + + retrieval: Optional[Retrieval] = Field( + default=None, + description="""Optional. Retrieval tool type. System will always execute the provided retrieval tool(s) to get external knowledge to answer the prompt. Retrieval results are presented to the model for generation. This field is not supported in Gemini API.""", + ) + computer_use: Optional[ComputerUse] = Field( + default=None, + description="""Optional. Tool to support the model interacting directly with the + computer. If enabled, it automatically populates computer-use specific + Function Declarations.""", + ) + file_search: Optional[FileSearch] = Field( + default=None, + description="""Optional. FileSearch tool type. Tool to retrieve knowledge from Semantic Retrieval corpora. This field is not supported in Vertex AI.""", + ) + google_search: Optional[GoogleSearch] = Field( + default=None, + description="""Optional. GoogleSearch tool type. Tool to support Google Search in Model. Powered by Google.""", + ) + google_maps: Optional[GoogleMaps] = Field( + default=None, + description="""Optional. Tool that allows grounding the model's response with + geospatial context related to the user's query.""", + ) + code_execution: Optional[ToolCodeExecution] = Field( + default=None, + description="""Optional. CodeExecution tool type. Enables the model to execute code as part of generation.""", + ) + enterprise_web_search: Optional[EnterpriseWebSearch] = Field( + default=None, + description="""Optional. Tool to support searching public web data, powered by Vertex AI Search and Sec4 compliance. This field is not supported in Gemini API.""", + ) + function_declarations: Optional[list[FunctionDeclaration]] = Field( + default=None, + description="""Optional. Function tool type. One or more function declarations to be passed to the model along with the current user query. Model may decide to call a subset of these functions by populating FunctionCall in the response. User should provide a FunctionResponse for each function call in the next turn. Based on the function responses, Model will generate the final response back to the user. Maximum 512 function declarations can be provided.""", + ) + google_search_retrieval: Optional[GoogleSearchRetrieval] = Field( + default=None, + description="""Optional. Specialized retrieval tool that is powered by Google Search.""", + ) + parallel_ai_search: Optional[ToolParallelAiSearch] = Field( + default=None, + description="""Optional. If specified, Vertex AI will use Parallel.ai to search for information to answer user queries. The search results will be grounded on Parallel.ai and presented to the model for response generation. This field is not supported in Gemini API.""", + ) + url_context: Optional[UrlContext] = Field( + default=None, + description="""Optional. Tool to support URL context retrieval.""", + ) + mcp_servers: Optional[list[McpServer]] = Field( + default=None, + description="""Optional. MCP Servers to connect to. This field is not supported in Vertex AI.""", + ) + + +class ToolDict(TypedDict, total=False): + """Tool details of a tool that the model may use to generate a response.""" + + retrieval: Optional[RetrievalDict] + """Optional. Retrieval tool type. System will always execute the provided retrieval tool(s) to get external knowledge to answer the prompt. Retrieval results are presented to the model for generation. This field is not supported in Gemini API.""" + + computer_use: Optional[ComputerUseDict] + """Optional. Tool to support the model interacting directly with the + computer. If enabled, it automatically populates computer-use specific + Function Declarations.""" + + file_search: Optional[FileSearchDict] + """Optional. FileSearch tool type. Tool to retrieve knowledge from Semantic Retrieval corpora. This field is not supported in Vertex AI.""" + + google_search: Optional[GoogleSearchDict] + """Optional. GoogleSearch tool type. Tool to support Google Search in Model. Powered by Google.""" + + google_maps: Optional[GoogleMapsDict] + """Optional. Tool that allows grounding the model's response with + geospatial context related to the user's query.""" + + code_execution: Optional[ToolCodeExecutionDict] + """Optional. CodeExecution tool type. Enables the model to execute code as part of generation.""" + + enterprise_web_search: Optional[EnterpriseWebSearchDict] + """Optional. Tool to support searching public web data, powered by Vertex AI Search and Sec4 compliance. This field is not supported in Gemini API.""" + + function_declarations: Optional[list[FunctionDeclarationDict]] + """Optional. Function tool type. One or more function declarations to be passed to the model along with the current user query. Model may decide to call a subset of these functions by populating FunctionCall in the response. User should provide a FunctionResponse for each function call in the next turn. Based on the function responses, Model will generate the final response back to the user. Maximum 512 function declarations can be provided.""" + + google_search_retrieval: Optional[GoogleSearchRetrievalDict] + """Optional. Specialized retrieval tool that is powered by Google Search.""" + + parallel_ai_search: Optional[ToolParallelAiSearchDict] + """Optional. If specified, Vertex AI will use Parallel.ai to search for information to answer user queries. The search results will be grounded on Parallel.ai and presented to the model for response generation. This field is not supported in Gemini API.""" + + url_context: Optional[UrlContextDict] + """Optional. Tool to support URL context retrieval.""" + + mcp_servers: Optional[list[McpServerDict]] + """Optional. MCP Servers to connect to. This field is not supported in Vertex AI.""" + + +ToolOrDict = Union[Tool, ToolDict] +if _is_mcp_imported: + ToolUnion = Union[Tool, Callable[..., Any], mcp_types.Tool, McpClientSession] + ToolUnionDict = Union[ + ToolDict, Callable[..., Any], mcp_types.Tool, McpClientSession + ] +else: + ToolUnion = Union[Tool, Callable[..., Any]] # type: ignore[misc] + ToolUnionDict = Union[ToolDict, Callable[..., Any]] # type: ignore[misc] + +ToolListUnion = list[ToolUnion] +ToolListUnionDict = list[ToolUnionDict] + +SchemaUnion = Union[ + dict[Any, Any], type, Schema, builtin_types.GenericAlias, VersionedUnionType # type: ignore[valid-type] +] +SchemaUnionDict = Union[SchemaUnion, SchemaDict] + + +class LatLng(_common.BaseModel): + """An object that represents a latitude/longitude pair. + + This is expressed as a pair of doubles to represent degrees latitude and + degrees longitude. Unless specified otherwise, this object must conform to the + + WGS84 standard. Values must be within normalized ranges. + """ + + latitude: Optional[float] = Field( + default=None, + description="""The latitude in degrees. It must be in the range [-90.0, +90.0].""", + ) + longitude: Optional[float] = Field( + default=None, + description="""The longitude in degrees. It must be in the range [-180.0, +180.0]""", + ) + + +class LatLngDict(TypedDict, total=False): + """An object that represents a latitude/longitude pair. + + This is expressed as a pair of doubles to represent degrees latitude and + degrees longitude. Unless specified otherwise, this object must conform to the + + WGS84 standard. Values must be within normalized ranges. + """ + + latitude: Optional[float] + """The latitude in degrees. It must be in the range [-90.0, +90.0].""" + + longitude: Optional[float] + """The longitude in degrees. It must be in the range [-180.0, +180.0]""" + + +LatLngOrDict = Union[LatLng, LatLngDict] + + +class RetrievalConfig(_common.BaseModel): + """Retrieval config.""" + + lat_lng: Optional[LatLng] = Field( + default=None, description="""Optional. The location of the user.""" + ) + language_code: Optional[str] = Field( + default=None, description="""The language code of the user.""" + ) + + +class RetrievalConfigDict(TypedDict, total=False): + """Retrieval config.""" + + lat_lng: Optional[LatLngDict] + """Optional. The location of the user.""" + + language_code: Optional[str] + """The language code of the user.""" + + +RetrievalConfigOrDict = Union[RetrievalConfig, RetrievalConfigDict] + + +class FunctionCallingConfig(_common.BaseModel): + """Function calling config.""" + + allowed_function_names: Optional[list[str]] = Field( + default=None, + description="""Optional. Function names to call. Only set when the Mode is ANY. Function names should match [FunctionDeclaration.name]. With mode set to ANY, model will predict a function call from the set of function names provided.""", + ) + mode: Optional[FunctionCallingConfigMode] = Field( + default=None, description="""Optional. Function calling mode.""" + ) + stream_function_call_arguments: Optional[bool] = Field( + default=None, + description="""Optional. When set to true, arguments of a single function call will be streamed out in multiple parts/contents/responses. Partial parameter results will be returned in the [FunctionCall.partial_args] field. This field is not supported in Gemini API.""", + ) + + +class FunctionCallingConfigDict(TypedDict, total=False): + """Function calling config.""" + + allowed_function_names: Optional[list[str]] + """Optional. Function names to call. Only set when the Mode is ANY. Function names should match [FunctionDeclaration.name]. With mode set to ANY, model will predict a function call from the set of function names provided.""" + + mode: Optional[FunctionCallingConfigMode] + """Optional. Function calling mode.""" + + stream_function_call_arguments: Optional[bool] + """Optional. When set to true, arguments of a single function call will be streamed out in multiple parts/contents/responses. Partial parameter results will be returned in the [FunctionCall.partial_args] field. This field is not supported in Gemini API.""" + + +FunctionCallingConfigOrDict = Union[ + FunctionCallingConfig, FunctionCallingConfigDict +] + + +class ToolConfig(_common.BaseModel): + """Tool config. + + This config is shared for all tools provided in the request. + """ + + retrieval_config: Optional[RetrievalConfig] = Field( + default=None, description="""Optional. Retrieval config.""" + ) + function_calling_config: Optional[FunctionCallingConfig] = Field( + default=None, description="""Optional. Function calling config.""" + ) + include_server_side_tool_invocations: Optional[bool] = Field( + default=None, + description="""If true, the API response will include the server-side tool calls and responses within the `Content` message. This allows clients to observe the server's tool invocations.""", + ) + + +class ToolConfigDict(TypedDict, total=False): + """Tool config. + + This config is shared for all tools provided in the request. + """ + + retrieval_config: Optional[RetrievalConfigDict] + """Optional. Retrieval config.""" + + function_calling_config: Optional[FunctionCallingConfigDict] + """Optional. Function calling config.""" + + include_server_side_tool_invocations: Optional[bool] + """If true, the API response will include the server-side tool calls and responses within the `Content` message. This allows clients to observe the server's tool invocations.""" + + +ToolConfigOrDict = Union[ToolConfig, ToolConfigDict] + + +class VoiceConsentSignature(_common.BaseModel): + """The signature of the voice consent check.""" + + signature: Optional[str] = Field( + default=None, + description="""The signature string. + """, + ) + + +class VoiceConsentSignatureDict(TypedDict, total=False): + """The signature of the voice consent check.""" + + signature: Optional[str] + """The signature string. + """ + + +VoiceConsentSignatureOrDict = Union[ + VoiceConsentSignature, VoiceConsentSignatureDict +] + + +class ReplicatedVoiceConfig(_common.BaseModel): + """The configuration for the replicated voice to use.""" + + mime_type: Optional[str] = Field( + default=None, + description="""The mimetype of the voice sample. The only currently supported + value is `audio/wav`. This represents 16-bit signed little-endian wav + data, with a 24kHz sampling rate. + """, + ) + voice_sample_audio: Optional[bytes] = Field( + default=None, + description="""The sample of the custom voice. + """, + ) + consent_audio: Optional[bytes] = Field( + default=None, + description="""Recorded consent verifying ownership of the voice. This + represents 16-bit signed little-endian wav data, with a 24kHz sampling + rate.""", + ) + voice_consent_signature: Optional[VoiceConsentSignature] = Field( + default=None, + description="""Signature of a previously verified consent audio. This should be + populated with a signature generated by the server for a previous + request containing the consent_audio field. When provided, the + signature is verified instead of the consent_audio field to reduce + latency. Requests will fail if the signature is invalid or expired.""", + ) + + +class ReplicatedVoiceConfigDict(TypedDict, total=False): + """The configuration for the replicated voice to use.""" + + mime_type: Optional[str] + """The mimetype of the voice sample. The only currently supported + value is `audio/wav`. This represents 16-bit signed little-endian wav + data, with a 24kHz sampling rate. + """ + + voice_sample_audio: Optional[bytes] + """The sample of the custom voice. + """ + + consent_audio: Optional[bytes] + """Recorded consent verifying ownership of the voice. This + represents 16-bit signed little-endian wav data, with a 24kHz sampling + rate.""" + + voice_consent_signature: Optional[VoiceConsentSignatureDict] + """Signature of a previously verified consent audio. This should be + populated with a signature generated by the server for a previous + request containing the consent_audio field. When provided, the + signature is verified instead of the consent_audio field to reduce + latency. Requests will fail if the signature is invalid or expired.""" + + +ReplicatedVoiceConfigOrDict = Union[ + ReplicatedVoiceConfig, ReplicatedVoiceConfigDict +] + + +class PrebuiltVoiceConfig(_common.BaseModel): + """Configuration for a prebuilt voice.""" + + voice_name: Optional[str] = Field( + default=None, description="""The name of the prebuilt voice to use.""" + ) + + +class PrebuiltVoiceConfigDict(TypedDict, total=False): + """Configuration for a prebuilt voice.""" + + voice_name: Optional[str] + """The name of the prebuilt voice to use.""" + + +PrebuiltVoiceConfigOrDict = Union[PrebuiltVoiceConfig, PrebuiltVoiceConfigDict] + + +class VoiceConfig(_common.BaseModel): + """The configuration for the voice to use.""" + + replicated_voice_config: Optional[ReplicatedVoiceConfig] = Field( + default=None, + description="""The configuration for a replicated voice, which is a clone of a + user's voice that can be used for speech synthesis. If this is unset, a + default voice is used.""", + ) + prebuilt_voice_config: Optional[PrebuiltVoiceConfig] = Field( + default=None, description="""The configuration for a prebuilt voice.""" + ) + + +class VoiceConfigDict(TypedDict, total=False): + """The configuration for the voice to use.""" + + replicated_voice_config: Optional[ReplicatedVoiceConfigDict] + """The configuration for a replicated voice, which is a clone of a + user's voice that can be used for speech synthesis. If this is unset, a + default voice is used.""" + + prebuilt_voice_config: Optional[PrebuiltVoiceConfigDict] + """The configuration for a prebuilt voice.""" + + +VoiceConfigOrDict = Union[VoiceConfig, VoiceConfigDict] + + +class SpeakerVoiceConfig(_common.BaseModel): + """Configuration for a single speaker in a multi-speaker setup.""" + + speaker: Optional[str] = Field( + default=None, + description="""Required. The name of the speaker. This should be the same as the speaker name used in the prompt.""", + ) + voice_config: Optional[VoiceConfig] = Field( + default=None, + description="""Required. The configuration for the voice of this speaker.""", + ) + + +class SpeakerVoiceConfigDict(TypedDict, total=False): + """Configuration for a single speaker in a multi-speaker setup.""" + + speaker: Optional[str] + """Required. The name of the speaker. This should be the same as the speaker name used in the prompt.""" + + voice_config: Optional[VoiceConfigDict] + """Required. The configuration for the voice of this speaker.""" + + +SpeakerVoiceConfigOrDict = Union[SpeakerVoiceConfig, SpeakerVoiceConfigDict] + + +class MultiSpeakerVoiceConfig(_common.BaseModel): + """Configuration for a multi-speaker text-to-speech request.""" + + speaker_voice_configs: Optional[list[SpeakerVoiceConfig]] = Field( + default=None, + description="""Required. A list of configurations for the voices of the speakers. Exactly two speaker voice configurations must be provided.""", + ) + + +class MultiSpeakerVoiceConfigDict(TypedDict, total=False): + """Configuration for a multi-speaker text-to-speech request.""" + + speaker_voice_configs: Optional[list[SpeakerVoiceConfigDict]] + """Required. A list of configurations for the voices of the speakers. Exactly two speaker voice configurations must be provided.""" + + +MultiSpeakerVoiceConfigOrDict = Union[ + MultiSpeakerVoiceConfig, MultiSpeakerVoiceConfigDict +] + + +class SpeechConfig(_common.BaseModel): + """Config for speech generation and transcription.""" + + voice_config: Optional[VoiceConfig] = Field( + default=None, + description="""The configuration in case of single-voice output.""", + ) + language_code: Optional[str] = Field( + default=None, + description="""Optional. The language code (ISO 639-1) for the speech synthesis.""", + ) + multi_speaker_voice_config: Optional[MultiSpeakerVoiceConfig] = Field( + default=None, + description="""The configuration for a multi-speaker text-to-speech request. This field is mutually exclusive with `voice_config`.""", + ) + + +class SpeechConfigDict(TypedDict, total=False): + """Config for speech generation and transcription.""" + + voice_config: Optional[VoiceConfigDict] + """The configuration in case of single-voice output.""" + + language_code: Optional[str] + """Optional. The language code (ISO 639-1) for the speech synthesis.""" + + multi_speaker_voice_config: Optional[MultiSpeakerVoiceConfigDict] + """The configuration for a multi-speaker text-to-speech request. This field is mutually exclusive with `voice_config`.""" + + +SpeechConfigOrDict = Union[SpeechConfig, SpeechConfigDict] + + +class AutomaticFunctionCallingConfig(_common.BaseModel): + """The configuration for automatic function calling.""" + + disable: Optional[bool] = Field( + default=None, + description="""Whether to disable automatic function calling. + If not set or set to False, will enable automatic function calling. + If set to True, will disable automatic function calling. + """, + ) + maximum_remote_calls: Optional[int] = Field( + default=10, + description="""If automatic function calling is enabled, + maximum number of remote calls for automatic function calling. + This number should be a positive integer. + If not set, SDK will set maximum number of remote calls to 10. + """, + ) + ignore_call_history: Optional[bool] = Field( + default=None, + description="""If automatic function calling is enabled, + whether to ignore call history to the response. + If not set, SDK will set ignore_call_history to false, + and will append the call history to + GenerateContentResponse.automatic_function_calling_history. + """, + ) + + +class AutomaticFunctionCallingConfigDict(TypedDict, total=False): + """The configuration for automatic function calling.""" + + disable: Optional[bool] + """Whether to disable automatic function calling. + If not set or set to False, will enable automatic function calling. + If set to True, will disable automatic function calling. + """ + + maximum_remote_calls: Optional[int] + """If automatic function calling is enabled, + maximum number of remote calls for automatic function calling. + This number should be a positive integer. + If not set, SDK will set maximum number of remote calls to 10. + """ + + ignore_call_history: Optional[bool] + """If automatic function calling is enabled, + whether to ignore call history to the response. + If not set, SDK will set ignore_call_history to false, + and will append the call history to + GenerateContentResponse.automatic_function_calling_history. + """ + + +AutomaticFunctionCallingConfigOrDict = Union[ + AutomaticFunctionCallingConfig, AutomaticFunctionCallingConfigDict +] + + +class ThinkingConfig(_common.BaseModel): + """The thinking features configuration.""" + + include_thoughts: Optional[bool] = Field( + default=None, + description="""Indicates whether to include thoughts in the response. If true, thoughts are returned only if the model supports thought and thoughts are available. + """, + ) + thinking_budget: Optional[int] = Field( + default=None, + description="""Indicates the thinking budget in tokens. 0 is DISABLED. -1 is AUTOMATIC. The default values and allowed ranges are model dependent. + """, + ) + thinking_level: Optional[ThinkingLevel] = Field( + default=None, + description="""Optional. The number of thoughts tokens that the model should generate.""", + ) + + +class ThinkingConfigDict(TypedDict, total=False): + """The thinking features configuration.""" + + include_thoughts: Optional[bool] + """Indicates whether to include thoughts in the response. If true, thoughts are returned only if the model supports thought and thoughts are available. + """ + + thinking_budget: Optional[int] + """Indicates the thinking budget in tokens. 0 is DISABLED. -1 is AUTOMATIC. The default values and allowed ranges are model dependent. + """ + + thinking_level: Optional[ThinkingLevel] + """Optional. The number of thoughts tokens that the model should generate.""" + + +ThinkingConfigOrDict = Union[ThinkingConfig, ThinkingConfigDict] + + +class ImageConfigImageOutputOptions(_common.BaseModel): + """The image output format for generated images. + + This data type is not supported in Gemini API. + """ + + compression_quality: Optional[int] = Field( + default=None, + description="""Optional. The compression quality of the output image.""", + ) + mime_type: Optional[str] = Field( + default=None, + description="""Optional. The image format that the output should be saved as.""", + ) + + +class ImageConfigImageOutputOptionsDict(TypedDict, total=False): + """The image output format for generated images. + + This data type is not supported in Gemini API. + """ + + compression_quality: Optional[int] + """Optional. The compression quality of the output image.""" + + mime_type: Optional[str] + """Optional. The image format that the output should be saved as.""" + + +ImageConfigImageOutputOptionsOrDict = Union[ + ImageConfigImageOutputOptions, ImageConfigImageOutputOptionsDict +] + + +class ImageConfig(_common.BaseModel): + """The image generation configuration to be used in GenerateContentConfig.""" + + aspect_ratio: Optional[str] = Field( + default=None, + description="""Aspect ratio of the generated images. Supported values are + "1:1", "2:3", "3:2", "3:4", "4:3", "9:16", "16:9", and "21:9".""", + ) + image_size: Optional[str] = Field( + default=None, + description="""Optional. Specifies the size of generated images. Supported + values are `1K`, `2K`, `4K`. If not specified, the model will use default + value `1K`.""", + ) + person_generation: Optional[str] = Field( + default=None, + description="""Controls the generation of people. Supported values are: + ALLOW_ALL, ALLOW_ADULT, ALLOW_NONE.""", + ) + prominent_people: Optional[ProminentPeople] = Field( + default=None, + description="""Optional. Controls whether prominent people (celebrities) generation is allowed. If used with personGeneration, personGeneration enum would take precedence. For instance, if ALLOW_NONE is set, all person generation would be blocked. If this field is unspecified, the default behavior is to allow prominent people. This field is not supported in Gemini API.""", + ) + output_mime_type: Optional[str] = Field( + default=None, + description="""MIME type of the generated image. This field is not + supported in Gemini API.""", + ) + output_compression_quality: Optional[int] = Field( + default=None, + description="""Compression quality of the generated image (for + ``image/jpeg`` only). This field is not supported in Gemini API.""", + ) + image_output_options: Optional[ImageConfigImageOutputOptions] = Field( + default=None, + description="""Optional. The image output format for generated images. This field is not supported in Gemini API.""", + ) + + +class ImageConfigDict(TypedDict, total=False): + """The image generation configuration to be used in GenerateContentConfig.""" + + aspect_ratio: Optional[str] + """Aspect ratio of the generated images. Supported values are + "1:1", "2:3", "3:2", "3:4", "4:3", "9:16", "16:9", and "21:9".""" + + image_size: Optional[str] + """Optional. Specifies the size of generated images. Supported + values are `1K`, `2K`, `4K`. If not specified, the model will use default + value `1K`.""" + + person_generation: Optional[str] + """Controls the generation of people. Supported values are: + ALLOW_ALL, ALLOW_ADULT, ALLOW_NONE.""" + + prominent_people: Optional[ProminentPeople] + """Optional. Controls whether prominent people (celebrities) generation is allowed. If used with personGeneration, personGeneration enum would take precedence. For instance, if ALLOW_NONE is set, all person generation would be blocked. If this field is unspecified, the default behavior is to allow prominent people. This field is not supported in Gemini API.""" + + output_mime_type: Optional[str] + """MIME type of the generated image. This field is not + supported in Gemini API.""" + + output_compression_quality: Optional[int] + """Compression quality of the generated image (for + ``image/jpeg`` only). This field is not supported in Gemini API.""" + + image_output_options: Optional[ImageConfigImageOutputOptionsDict] + """Optional. The image output format for generated images. This field is not supported in Gemini API.""" + + +ImageConfigOrDict = Union[ImageConfig, ImageConfigDict] + + +class FileStatus(_common.BaseModel): + """Status of a File that uses a common error model.""" + + details: Optional[list[dict[str, Any]]] = Field( + default=None, + description="""A list of messages that carry the error details. There is a common set of message types for APIs to use.""", + ) + message: Optional[str] = Field( + default=None, + description="""A list of messages that carry the error details. There is a common set of message types for APIs to use.""", + ) + code: Optional[int] = Field( + default=None, description="""The status code. 0 for OK, 1 for CANCELLED""" + ) + + +class FileStatusDict(TypedDict, total=False): + """Status of a File that uses a common error model.""" + + details: Optional[list[dict[str, Any]]] + """A list of messages that carry the error details. There is a common set of message types for APIs to use.""" + + message: Optional[str] + """A list of messages that carry the error details. There is a common set of message types for APIs to use.""" + + code: Optional[int] + """The status code. 0 for OK, 1 for CANCELLED""" + + +FileStatusOrDict = Union[FileStatus, FileStatusDict] + + +class File(_common.BaseModel): + """A file uploaded to the API.""" + + name: Optional[str] = Field( + default=None, + description="""The `File` resource name. The ID (name excluding the "files/" prefix) can contain up to 40 characters that are lowercase alphanumeric or dashes (-). The ID cannot start or end with a dash. If the name is empty on create, a unique name will be generated. Example: `files/123-456`""", + ) + display_name: Optional[str] = Field( + default=None, + description="""Optional. The human-readable display name for the `File`. The display name must be no more than 512 characters in length, including spaces. Example: 'Welcome Image'""", + ) + mime_type: Optional[str] = Field( + default=None, description="""Output only. MIME type of the file.""" + ) + size_bytes: Optional[int] = Field( + default=None, description="""Output only. Size of the file in bytes.""" + ) + create_time: Optional[datetime.datetime] = Field( + default=None, + description="""Output only. The timestamp of when the `File` was created.""", + ) + expiration_time: Optional[datetime.datetime] = Field( + default=None, + description="""Output only. The timestamp of when the `File` will be deleted. Only set if the `File` is scheduled to expire.""", + ) + update_time: Optional[datetime.datetime] = Field( + default=None, + description="""Output only. The timestamp of when the `File` was last updated.""", + ) + sha256_hash: Optional[str] = Field( + default=None, + description="""Output only. SHA-256 hash of the uploaded bytes. The hash value is encoded in base64 format.""", + ) + uri: Optional[str] = Field( + default=None, description="""Output only. The URI of the `File`.""" + ) + download_uri: Optional[str] = Field( + default=None, + description="""Output only. The URI of the `File`, only set for downloadable (generated) files.""", + ) + state: Optional[FileState] = Field( + default=None, description="""Output only. Processing state of the File.""" + ) + source: Optional[FileSource] = Field( + default=None, description="""Output only. The source of the `File`.""" + ) + video_metadata: Optional[dict[str, Any]] = Field( + default=None, description="""Output only. Metadata for a video.""" + ) + error: Optional[FileStatus] = Field( + default=None, + description="""Output only. Error status if File processing failed.""", + ) + + +class FileDict(TypedDict, total=False): + """A file uploaded to the API.""" + + name: Optional[str] + """The `File` resource name. The ID (name excluding the "files/" prefix) can contain up to 40 characters that are lowercase alphanumeric or dashes (-). The ID cannot start or end with a dash. If the name is empty on create, a unique name will be generated. Example: `files/123-456`""" + + display_name: Optional[str] + """Optional. The human-readable display name for the `File`. The display name must be no more than 512 characters in length, including spaces. Example: 'Welcome Image'""" + + mime_type: Optional[str] + """Output only. MIME type of the file.""" + + size_bytes: Optional[int] + """Output only. Size of the file in bytes.""" + + create_time: Optional[datetime.datetime] + """Output only. The timestamp of when the `File` was created.""" + + expiration_time: Optional[datetime.datetime] + """Output only. The timestamp of when the `File` will be deleted. Only set if the `File` is scheduled to expire.""" + + update_time: Optional[datetime.datetime] + """Output only. The timestamp of when the `File` was last updated.""" + + sha256_hash: Optional[str] + """Output only. SHA-256 hash of the uploaded bytes. The hash value is encoded in base64 format.""" + + uri: Optional[str] + """Output only. The URI of the `File`.""" + + download_uri: Optional[str] + """Output only. The URI of the `File`, only set for downloadable (generated) files.""" + + state: Optional[FileState] + """Output only. Processing state of the File.""" + + source: Optional[FileSource] + """Output only. The source of the `File`.""" + + video_metadata: Optional[dict[str, Any]] + """Output only. Metadata for a video.""" + + error: Optional[FileStatusDict] + """Output only. Error status if File processing failed.""" + + +FileOrDict = Union[File, FileDict] + + +if _is_pillow_image_imported: + PartUnion = Union[str, PIL_Image, File, Part] +else: + PartUnion = Union[str, File, Part] # type: ignore[misc] + + +if _is_pillow_image_imported: + PartUnionDict = Union[str, PIL_Image, File, FileDict, Part, PartDict] +else: + PartUnionDict = Union[str, File, FileDict, Part, PartDict] # type: ignore[misc] + + +ContentUnion = Union[Content, PartUnion, list[PartUnion]] + + +ContentUnionDict = Union[ + Content, ContentDict, PartUnionDict, list[PartUnionDict] +] + + +class GenerationConfigRoutingConfigAutoRoutingMode(_common.BaseModel): + """The configuration for automated routing. + + When automated routing is specified, the routing will be determined by the + pretrained routing model and customer provided model routing preference. This + data type is not supported in Gemini API. + """ + + model_routing_preference: Optional[ + Literal['UNKNOWN', 'PRIORITIZE_QUALITY', 'BALANCED', 'PRIORITIZE_COST'] + ] = Field(default=None, description="""The model routing preference.""") + + +class GenerationConfigRoutingConfigAutoRoutingModeDict(TypedDict, total=False): + """The configuration for automated routing. + + When automated routing is specified, the routing will be determined by the + pretrained routing model and customer provided model routing preference. This + data type is not supported in Gemini API. + """ + + model_routing_preference: Optional[ + Literal['UNKNOWN', 'PRIORITIZE_QUALITY', 'BALANCED', 'PRIORITIZE_COST'] + ] + """The model routing preference.""" + + +GenerationConfigRoutingConfigAutoRoutingModeOrDict = Union[ + GenerationConfigRoutingConfigAutoRoutingMode, + GenerationConfigRoutingConfigAutoRoutingModeDict, +] + + +class GenerationConfigRoutingConfigManualRoutingMode(_common.BaseModel): + """The configuration for manual routing. + + When manual routing is specified, the model will be selected based on the + model name provided. This data type is not supported in Gemini API. + """ + + model_name: Optional[str] = Field( + default=None, + description="""The name of the model to use. Only public LLM models are accepted.""", + ) + + +class GenerationConfigRoutingConfigManualRoutingModeDict( + TypedDict, total=False +): + """The configuration for manual routing. + + When manual routing is specified, the model will be selected based on the + model name provided. This data type is not supported in Gemini API. + """ + + model_name: Optional[str] + """The name of the model to use. Only public LLM models are accepted.""" + + +GenerationConfigRoutingConfigManualRoutingModeOrDict = Union[ + GenerationConfigRoutingConfigManualRoutingMode, + GenerationConfigRoutingConfigManualRoutingModeDict, +] + + +class GenerationConfigRoutingConfig(_common.BaseModel): + """The configuration for routing the request to a specific model. + + This can be used to control which model is used for the generation, either + automatically or by specifying a model name. This data type is not supported + in Gemini API. + """ + + auto_mode: Optional[GenerationConfigRoutingConfigAutoRoutingMode] = Field( + default=None, + description="""In this mode, the model is selected automatically based on the content of the request.""", + ) + manual_mode: Optional[GenerationConfigRoutingConfigManualRoutingMode] = Field( + default=None, + description="""In this mode, the model is specified manually.""", + ) + + +class GenerationConfigRoutingConfigDict(TypedDict, total=False): + """The configuration for routing the request to a specific model. + + This can be used to control which model is used for the generation, either + automatically or by specifying a model name. This data type is not supported + in Gemini API. + """ + + auto_mode: Optional[GenerationConfigRoutingConfigAutoRoutingModeDict] + """In this mode, the model is selected automatically based on the content of the request.""" + + manual_mode: Optional[GenerationConfigRoutingConfigManualRoutingModeDict] + """In this mode, the model is specified manually.""" + + +GenerationConfigRoutingConfigOrDict = Union[ + GenerationConfigRoutingConfig, GenerationConfigRoutingConfigDict +] + + +class SafetySetting(_common.BaseModel): + """A safety setting that affects the safety-blocking behavior. + + A SafetySetting consists of a harm category and a threshold for that category. + """ + + category: Optional[HarmCategory] = Field( + default=None, description="""Required. The harm category to be blocked.""" + ) + method: Optional[HarmBlockMethod] = Field( + default=None, + description="""Optional. The method for blocking content. If not specified, the default behavior is to use the probability score. This field is not supported in Gemini API.""", + ) + threshold: Optional[HarmBlockThreshold] = Field( + default=None, + description="""Required. The threshold for blocking content. If the harm probability exceeds this threshold, the content will be blocked.""", + ) + + +class SafetySettingDict(TypedDict, total=False): + """A safety setting that affects the safety-blocking behavior. + + A SafetySetting consists of a harm category and a threshold for that category. + """ + + category: Optional[HarmCategory] + """Required. The harm category to be blocked.""" + + method: Optional[HarmBlockMethod] + """Optional. The method for blocking content. If not specified, the default behavior is to use the probability score. This field is not supported in Gemini API.""" + + threshold: Optional[HarmBlockThreshold] + """Required. The threshold for blocking content. If the harm probability exceeds this threshold, the content will be blocked.""" + + +SafetySettingOrDict = Union[SafetySetting, SafetySettingDict] + + +SpeechConfigUnion = Union[str, SpeechConfig] + + +SpeechConfigUnionDict = Union[str, SpeechConfig, SpeechConfigDict] + + +class ModelArmorConfig(_common.BaseModel): + """Configuration for Model Armor. + + Model Armor is a Google Cloud service that provides safety and security + filtering for prompts and responses. It helps protect your AI applications + from risks such as harmful content, sensitive data leakage, and prompt + injection attacks. This data type is not supported in Gemini API. + """ + + prompt_template_name: Optional[str] = Field( + default=None, + description="""Optional. The resource name of the Model Armor template to use for prompt screening. A Model Armor template is a set of customized filters and thresholds that define how Model Armor screens content. If specified, Model Armor will use this template to check the user's prompt for safety and security risks before it is sent to the model. The name must be in the format `projects/{project}/locations/{location}/templates/{template}`.""", + ) + response_template_name: Optional[str] = Field( + default=None, + description="""Optional. The resource name of the Model Armor template to use for response screening. A Model Armor template is a set of customized filters and thresholds that define how Model Armor screens content. If specified, Model Armor will use this template to check the model's response for safety and security risks before it is returned to the user. The name must be in the format `projects/{project}/locations/{location}/templates/{template}`.""", + ) + + +class ModelArmorConfigDict(TypedDict, total=False): + """Configuration for Model Armor. + + Model Armor is a Google Cloud service that provides safety and security + filtering for prompts and responses. It helps protect your AI applications + from risks such as harmful content, sensitive data leakage, and prompt + injection attacks. This data type is not supported in Gemini API. + """ + + prompt_template_name: Optional[str] + """Optional. The resource name of the Model Armor template to use for prompt screening. A Model Armor template is a set of customized filters and thresholds that define how Model Armor screens content. If specified, Model Armor will use this template to check the user's prompt for safety and security risks before it is sent to the model. The name must be in the format `projects/{project}/locations/{location}/templates/{template}`.""" + + response_template_name: Optional[str] + """Optional. The resource name of the Model Armor template to use for response screening. A Model Armor template is a set of customized filters and thresholds that define how Model Armor screens content. If specified, Model Armor will use this template to check the model's response for safety and security risks before it is returned to the user. The name must be in the format `projects/{project}/locations/{location}/templates/{template}`.""" + + +ModelArmorConfigOrDict = Union[ModelArmorConfig, ModelArmorConfigDict] + + +class GenerateContentConfig(_common.BaseModel): + """Optional model configuration parameters. + + For more information, see `Content generation parameters + `_. + """ + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + should_return_http_response: Optional[bool] = Field( + default=None, + description=""" If true, the raw HTTP response will be returned in the 'sdk_http_response' field.""", + ) + system_instruction: Optional[ContentUnion] = Field( + default=None, + description="""Instructions for the model to steer it toward better performance. + For example, "Answer as concisely as possible" or "Don't use technical + terms in your response". + """, + ) + temperature: Optional[float] = Field( + default=None, + description="""Value that controls the degree of randomness in token selection. + Lower temperatures are good for prompts that require a less open-ended or + creative response, while higher temperatures can lead to more diverse or + creative results. + """, + ) + top_p: Optional[float] = Field( + default=None, + description="""Tokens are selected from the most to least probable until the sum + of their probabilities equals this value. Use a lower value for less + random responses and a higher value for more random responses. + """, + ) + top_k: Optional[float] = Field( + default=None, + description="""For each token selection step, the ``top_k`` tokens with the + highest probabilities are sampled. Then tokens are further filtered based + on ``top_p`` with the final token selected using temperature sampling. Use + a lower number for less random responses and a higher number for more + random responses. + """, + ) + candidate_count: Optional[int] = Field( + default=None, + description="""Number of response variations to return. + """, + ) + max_output_tokens: Optional[int] = Field( + default=None, + description="""Maximum number of tokens that can be generated in the response. + """, + ) + stop_sequences: Optional[list[str]] = Field( + default=None, + description="""List of strings that tells the model to stop generating text if one + of the strings is encountered in the response. + """, + ) + response_logprobs: Optional[bool] = Field( + default=None, + description="""Whether to return the log probabilities of the tokens that were + chosen by the model at each step. + """, + ) + logprobs: Optional[int] = Field( + default=None, + description="""Number of top candidate tokens to return the log probabilities for + at each generation step. + """, + ) + presence_penalty: Optional[float] = Field( + default=None, + description="""Positive values penalize tokens that already appear in the + generated text, increasing the probability of generating more diverse + content. + """, + ) + frequency_penalty: Optional[float] = Field( + default=None, + description="""Positive values penalize tokens that repeatedly appear in the + generated text, increasing the probability of generating more diverse + content. + """, + ) + seed: Optional[int] = Field( + default=None, + description="""When ``seed`` is fixed to a specific number, the model makes a best + effort to provide the same response for repeated requests. By default, a + random number is used. + """, + ) + response_mime_type: Optional[str] = Field( + default=None, + description="""Output response mimetype of the generated candidate text. + Supported mimetype: + - `text/plain`: (default) Text output. + - `application/json`: JSON response in the candidates. + The model needs to be prompted to output the appropriate response type, + otherwise the behavior is undefined. + """, + ) + response_schema: Optional[SchemaUnion] = Field( + default=None, + description="""The `Schema` object allows the definition of input and output data types. + These types can be objects, but also primitives and arrays. + Represents a select subset of an [OpenAPI 3.0 schema + object](https://spec.openapis.org/oas/v3.0.3#schema). + If set, a compatible response_mime_type must also be set. + Compatible mimetypes: `application/json`: Schema for JSON response. + + If `response_schema` doesn't process your schema correctly, try using + `response_json_schema` instead. + """, + ) + response_json_schema: Optional[Any] = Field( + default=None, + description="""Optional. Output schema of the generated response. + This is an alternative to `response_schema` that accepts [JSON + Schema](https://json-schema.org/). If set, `response_schema` must be + omitted, but `response_mime_type` is required. While the full JSON Schema + may be sent, not all features are supported. Specifically, only the + following properties are supported: - `$id` - `$defs` - `$ref` - `$anchor` + - `type` - `format` - `title` - `description` - `enum` (for strings and + numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` - + `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) - + `properties` - `additionalProperties` - `required` The non-standard + `propertyOrdering` property may also be set. Cyclic references are + unrolled to a limited degree and, as such, may only be used within + non-required properties. (Nullable properties are not sufficient.) If + `$ref` is set on a sub-schema, no other properties, except for than those + starting as a `$`, may be set.""", + ) + routing_config: Optional[GenerationConfigRoutingConfig] = Field( + default=None, + description="""Configuration for model router requests. + """, + ) + model_selection_config: Optional[ModelSelectionConfig] = Field( + default=None, + description="""Configuration for model selection. + """, + ) + safety_settings: Optional[list[SafetySetting]] = Field( + default=None, + description="""Safety settings in the request to block unsafe content in the + response. + """, + ) + tools: Optional[ToolListUnion] = Field( + default=None, + description="""Code that enables the system to interact with external systems to + perform an action outside of the knowledge and scope of the model. + """, + ) + tool_config: Optional[ToolConfig] = Field( + default=None, + description="""Associates model output to a specific function call. + """, + ) + labels: Optional[dict[str, str]] = Field( + default=None, + description="""Labels with user-defined metadata to break down billed charges.""", + ) + cached_content: Optional[str] = Field( + default=None, + description="""Resource name of a context cache that can be used in subsequent + requests. + """, + ) + response_modalities: Optional[list[str]] = Field( + default=None, + description="""The requested modalities of the response. Represents the set of + modalities that the model can return. + """, + ) + media_resolution: Optional[MediaResolution] = Field( + default=None, + description="""If specified, the media resolution specified will be used. + """, + ) + speech_config: Optional[SpeechConfigUnion] = Field( + default=None, + description="""The speech generation configuration. + """, + ) + audio_timestamp: Optional[bool] = Field( + default=None, + description="""If enabled, audio timestamp will be included in the request to the + model. + """, + ) + automatic_function_calling: Optional[AutomaticFunctionCallingConfig] = Field( + default=None, + description="""The configuration for automatic function calling. + """, + ) + thinking_config: Optional[ThinkingConfig] = Field( + default=None, + description="""The thinking features configuration. + """, + ) + image_config: Optional[ImageConfig] = Field( + default=None, + description="""The image generation configuration. + """, + ) + enable_enhanced_civic_answers: Optional[bool] = Field( + default=None, + description="""Enables enhanced civic answers. It may not be available for all + models. This field is not supported in Vertex AI. + """, + ) + model_armor_config: Optional[ModelArmorConfig] = Field( + default=None, + description="""Settings for prompt and response sanitization using the Model Armor + service. If supplied, safety_settings must not be supplied. + """, + ) + service_tier: Optional[ServiceTier] = Field( + default=None, + description="""The service tier to use for the request. For example, ServiceTier.FLEX.""", + ) + + @pydantic.field_validator('response_schema', mode='before') + @classmethod + def _convert_literal_to_enum(cls, value: Any) -> Union[Any, EnumMeta]: + if typing.get_origin(value) is typing.Literal: + enum_vals = typing.get_args(value) + if not all(isinstance(arg, str) for arg in enum_vals): + # This doesn't stop execution, it tells pydantic to raise a ValidationError + # when the class is instantiated with an unsupported Literal + raise ValueError(f'Literal type {value} must be a list of strings.') + # The title 'PlaceholderLiteralEnum' is removed from the generated Schema + # before sending the request + return Enum('PlaceholderLiteralEnum', {s: s for s in enum_vals}) + return value + + @pydantic.field_validator('image_config', mode='before') + @classmethod + def _check_image_config_type(cls, value: Any) -> Any: + if isinstance(value, GenerateImagesConfig): + raise ValueError( + 'image_config must be an instance of ImageConfig or compatible dict.' + ) + return value + + +class GenerateContentConfigDict(TypedDict, total=False): + """Optional model configuration parameters. + + For more information, see `Content generation parameters + `_. + """ + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + should_return_http_response: Optional[bool] + """ If true, the raw HTTP response will be returned in the 'sdk_http_response' field.""" + + system_instruction: Optional[ContentUnionDict] + """Instructions for the model to steer it toward better performance. + For example, "Answer as concisely as possible" or "Don't use technical + terms in your response". + """ + + temperature: Optional[float] + """Value that controls the degree of randomness in token selection. + Lower temperatures are good for prompts that require a less open-ended or + creative response, while higher temperatures can lead to more diverse or + creative results. + """ + + top_p: Optional[float] + """Tokens are selected from the most to least probable until the sum + of their probabilities equals this value. Use a lower value for less + random responses and a higher value for more random responses. + """ + + top_k: Optional[float] + """For each token selection step, the ``top_k`` tokens with the + highest probabilities are sampled. Then tokens are further filtered based + on ``top_p`` with the final token selected using temperature sampling. Use + a lower number for less random responses and a higher number for more + random responses. + """ + + candidate_count: Optional[int] + """Number of response variations to return. + """ + + max_output_tokens: Optional[int] + """Maximum number of tokens that can be generated in the response. + """ + + stop_sequences: Optional[list[str]] + """List of strings that tells the model to stop generating text if one + of the strings is encountered in the response. + """ + + response_logprobs: Optional[bool] + """Whether to return the log probabilities of the tokens that were + chosen by the model at each step. + """ + + logprobs: Optional[int] + """Number of top candidate tokens to return the log probabilities for + at each generation step. + """ + + presence_penalty: Optional[float] + """Positive values penalize tokens that already appear in the + generated text, increasing the probability of generating more diverse + content. + """ + + frequency_penalty: Optional[float] + """Positive values penalize tokens that repeatedly appear in the + generated text, increasing the probability of generating more diverse + content. + """ + + seed: Optional[int] + """When ``seed`` is fixed to a specific number, the model makes a best + effort to provide the same response for repeated requests. By default, a + random number is used. + """ + + response_mime_type: Optional[str] + """Output response mimetype of the generated candidate text. + Supported mimetype: + - `text/plain`: (default) Text output. + - `application/json`: JSON response in the candidates. + The model needs to be prompted to output the appropriate response type, + otherwise the behavior is undefined. + """ + + response_schema: Optional[SchemaUnionDict] + """The `Schema` object allows the definition of input and output data types. + These types can be objects, but also primitives and arrays. + Represents a select subset of an [OpenAPI 3.0 schema + object](https://spec.openapis.org/oas/v3.0.3#schema). + If set, a compatible response_mime_type must also be set. + Compatible mimetypes: `application/json`: Schema for JSON response. + + If `response_schema` doesn't process your schema correctly, try using + `response_json_schema` instead. + """ + + response_json_schema: Optional[Any] + """Optional. Output schema of the generated response. + This is an alternative to `response_schema` that accepts [JSON + Schema](https://json-schema.org/). If set, `response_schema` must be + omitted, but `response_mime_type` is required. While the full JSON Schema + may be sent, not all features are supported. Specifically, only the + following properties are supported: - `$id` - `$defs` - `$ref` - `$anchor` + - `type` - `format` - `title` - `description` - `enum` (for strings and + numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` - + `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) - + `properties` - `additionalProperties` - `required` The non-standard + `propertyOrdering` property may also be set. Cyclic references are + unrolled to a limited degree and, as such, may only be used within + non-required properties. (Nullable properties are not sufficient.) If + `$ref` is set on a sub-schema, no other properties, except for than those + starting as a `$`, may be set.""" + + routing_config: Optional[GenerationConfigRoutingConfigDict] + """Configuration for model router requests. + """ + + model_selection_config: Optional[ModelSelectionConfigDict] + """Configuration for model selection. + """ + + safety_settings: Optional[list[SafetySettingDict]] + """Safety settings in the request to block unsafe content in the + response. + """ + + tools: Optional[ToolListUnionDict] + """Code that enables the system to interact with external systems to + perform an action outside of the knowledge and scope of the model. + """ + + tool_config: Optional[ToolConfigDict] + """Associates model output to a specific function call. + """ + + labels: Optional[dict[str, str]] + """Labels with user-defined metadata to break down billed charges.""" + + cached_content: Optional[str] + """Resource name of a context cache that can be used in subsequent + requests. + """ + + response_modalities: Optional[list[str]] + """The requested modalities of the response. Represents the set of + modalities that the model can return. + """ + + media_resolution: Optional[MediaResolution] + """If specified, the media resolution specified will be used. + """ + + speech_config: Optional[SpeechConfigUnionDict] + """The speech generation configuration. + """ + + audio_timestamp: Optional[bool] + """If enabled, audio timestamp will be included in the request to the + model. + """ + + automatic_function_calling: Optional[AutomaticFunctionCallingConfigDict] + """The configuration for automatic function calling. + """ + + thinking_config: Optional[ThinkingConfigDict] + """The thinking features configuration. + """ + + image_config: Optional[ImageConfigDict] + """The image generation configuration. + """ + + enable_enhanced_civic_answers: Optional[bool] + """Enables enhanced civic answers. It may not be available for all + models. This field is not supported in Vertex AI. + """ + + model_armor_config: Optional[ModelArmorConfigDict] + """Settings for prompt and response sanitization using the Model Armor + service. If supplied, safety_settings must not be supplied. + """ + + service_tier: Optional[ServiceTier] + """The service tier to use for the request. For example, ServiceTier.FLEX.""" + + +GenerateContentConfigOrDict = Union[ + GenerateContentConfig, GenerateContentConfigDict +] + + +ContentListUnion = Union[ContentUnion, list[ContentUnion]] + + +ContentListUnionDict = Union[ContentUnionDict, list[ContentUnionDict]] + + +class _GenerateContentParameters(_common.BaseModel): + """Config for models.generate_content parameters.""" + + model: Optional[str] = Field( + default=None, + description="""ID of the model to use. For a list of models, see `Google models + `_.""", + ) + contents: Optional[ContentListUnion] = Field( + default=None, + description="""Content of the request. + """, + ) + config: Optional[GenerateContentConfig] = Field( + default=None, + description="""Configuration that contains optional model parameters. + """, + ) + + +class _GenerateContentParametersDict(TypedDict, total=False): + """Config for models.generate_content parameters.""" + + model: Optional[str] + """ID of the model to use. For a list of models, see `Google models + `_.""" + + contents: Optional[ContentListUnionDict] + """Content of the request. + """ + + config: Optional[GenerateContentConfigDict] + """Configuration that contains optional model parameters. + """ + + +_GenerateContentParametersOrDict = Union[ + _GenerateContentParameters, _GenerateContentParametersDict +] + + +class HttpResponse(_common.BaseModel): + """A wrapper class for the http response.""" + + headers: Optional[dict[str, str]] = Field( + default=None, + description="""Used to retain the processed HTTP headers in the response.""", + ) + body: Optional[str] = Field( + default=None, + description="""The raw HTTP response body, in JSON format.""", + ) + + +class HttpResponseDict(TypedDict, total=False): + """A wrapper class for the http response.""" + + headers: Optional[dict[str, str]] + """Used to retain the processed HTTP headers in the response.""" + + body: Optional[str] + """The raw HTTP response body, in JSON format.""" + + +HttpResponseOrDict = Union[HttpResponse, HttpResponseDict] + + +class GoogleTypeDate(_common.BaseModel): + """Represents a whole or partial calendar date, such as a birthday. + + The time of day and time zone are either specified elsewhere or are + insignificant. The date is relative to the Gregorian Calendar. This can + represent one of the following: * A full date, with non-zero year, month, and + day values. * A month and day, with a zero year (for example, an anniversary). + * A year on its own, with a zero month and a zero day. * A year and month, + with a zero day (for example, a credit card expiration date). Related types: * + google.type.TimeOfDay * google.type.DateTime * google.protobuf.Timestamp. This + data type is not supported in Gemini API. + """ + + day: Optional[int] = Field( + default=None, + description="""Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant.""", + ) + month: Optional[int] = Field( + default=None, + description="""Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day.""", + ) + year: Optional[int] = Field( + default=None, + description="""Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year.""", + ) + + +class GoogleTypeDateDict(TypedDict, total=False): + """Represents a whole or partial calendar date, such as a birthday. + + The time of day and time zone are either specified elsewhere or are + insignificant. The date is relative to the Gregorian Calendar. This can + represent one of the following: * A full date, with non-zero year, month, and + day values. * A month and day, with a zero year (for example, an anniversary). + * A year on its own, with a zero month and a zero day. * A year and month, + with a zero day (for example, a credit card expiration date). Related types: * + google.type.TimeOfDay * google.type.DateTime * google.protobuf.Timestamp. This + data type is not supported in Gemini API. + """ + + day: Optional[int] + """Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant.""" + + month: Optional[int] + """Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day.""" + + year: Optional[int] + """Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year.""" + + +GoogleTypeDateOrDict = Union[GoogleTypeDate, GoogleTypeDateDict] + + +class Citation(_common.BaseModel): + """A citation for a piece of generatedcontent. + + This data type is not supported in Gemini API. + """ + + end_index: Optional[int] = Field( + default=None, + description="""Output only. The end index of the citation in the content.""", + ) + license: Optional[str] = Field( + default=None, + description="""Output only. The license of the source of the citation.""", + ) + publication_date: Optional[GoogleTypeDate] = Field( + default=None, + description="""Output only. The publication date of the source of the citation.""", + ) + start_index: Optional[int] = Field( + default=None, + description="""Output only. The start index of the citation in the content.""", + ) + title: Optional[str] = Field( + default=None, + description="""Output only. The title of the source of the citation.""", + ) + uri: Optional[str] = Field( + default=None, + description="""Output only. The URI of the source of the citation.""", + ) + + +class CitationDict(TypedDict, total=False): + """A citation for a piece of generatedcontent. + + This data type is not supported in Gemini API. + """ + + end_index: Optional[int] + """Output only. The end index of the citation in the content.""" + + license: Optional[str] + """Output only. The license of the source of the citation.""" + + publication_date: Optional[GoogleTypeDateDict] + """Output only. The publication date of the source of the citation.""" + + start_index: Optional[int] + """Output only. The start index of the citation in the content.""" + + title: Optional[str] + """Output only. The title of the source of the citation.""" + + uri: Optional[str] + """Output only. The URI of the source of the citation.""" + + +CitationOrDict = Union[Citation, CitationDict] + + +class CitationMetadata(_common.BaseModel): + """Citation information when the model quotes another source.""" + + citations: Optional[list[Citation]] = Field( + default=None, + description="""Contains citation information when the model directly quotes, at + length, from another source. Can include traditional websites and code + repositories. + """, + ) + + @model_validator(mode='before') + @classmethod + def _rename_citation_sources(cls, data: Any) -> Any: + if isinstance(data, dict) and 'citationSources' in data: + data['citations'] = data.pop('citationSources') + return data + + +MetricUnion = Union['Metric', 'UnifiedMetric'] +MetricUnionDict = Union['MetricDict', 'UnifiedMetricDict'] + + +class CitationMetadataDict(TypedDict, total=False): + """Citation information when the model quotes another source.""" + + citations: Optional[list[CitationDict]] + """Contains citation information when the model directly quotes, at + length, from another source. Can include traditional websites and code + repositories. + """ + + +CitationMetadataOrDict = Union[CitationMetadata, CitationMetadataDict] + + +class GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution(_common.BaseModel): + """Author attribution for a photo or review.""" + + display_name: Optional[str] = Field( + default=None, description="""Name of the author of the Photo or Review.""" + ) + photo_uri: Optional[str] = Field( + default=None, + description="""Profile photo URI of the author of the Photo or Review.""", + ) + uri: Optional[str] = Field( + default=None, description="""URI of the author of the Photo or Review.""" + ) + + +class GroundingChunkMapsPlaceAnswerSourcesAuthorAttributionDict( + TypedDict, total=False +): + """Author attribution for a photo or review.""" + + display_name: Optional[str] + """Name of the author of the Photo or Review.""" + + photo_uri: Optional[str] + """Profile photo URI of the author of the Photo or Review.""" + + uri: Optional[str] + """URI of the author of the Photo or Review.""" + + +GroundingChunkMapsPlaceAnswerSourcesAuthorAttributionOrDict = Union[ + GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution, + GroundingChunkMapsPlaceAnswerSourcesAuthorAttributionDict, +] + + +class GroundingChunkMapsPlaceAnswerSourcesReviewSnippet(_common.BaseModel): + """Encapsulates a review snippet.""" + + author_attribution: Optional[ + GroundingChunkMapsPlaceAnswerSourcesAuthorAttribution + ] = Field(default=None, description="""This review's author.""") + flag_content_uri: Optional[str] = Field( + default=None, + description="""A link where users can flag a problem with the review.""", + ) + google_maps_uri: Optional[str] = Field( + default=None, description="""A link to show the review on Google Maps.""" + ) + relative_publish_time_description: Optional[str] = Field( + default=None, + description="""A string of formatted recent time, expressing the review time relative to the current time in a form appropriate for the language and country.""", + ) + review: Optional[str] = Field( + default=None, + description="""A reference representing this place review which may be used to look up this place review again.""", + ) + review_id: Optional[str] = Field( + default=None, description="""Id of the review referencing the place.""" + ) + title: Optional[str] = Field( + default=None, description="""Title of the review.""" + ) + + +class GroundingChunkMapsPlaceAnswerSourcesReviewSnippetDict( + TypedDict, total=False +): + """Encapsulates a review snippet.""" + + author_attribution: Optional[ + GroundingChunkMapsPlaceAnswerSourcesAuthorAttributionDict + ] + """This review's author.""" + + flag_content_uri: Optional[str] + """A link where users can flag a problem with the review.""" + + google_maps_uri: Optional[str] + """A link to show the review on Google Maps.""" + + relative_publish_time_description: Optional[str] + """A string of formatted recent time, expressing the review time relative to the current time in a form appropriate for the language and country.""" + + review: Optional[str] + """A reference representing this place review which may be used to look up this place review again.""" + + review_id: Optional[str] + """Id of the review referencing the place.""" + + title: Optional[str] + """Title of the review.""" + + +GroundingChunkMapsPlaceAnswerSourcesReviewSnippetOrDict = Union[ + GroundingChunkMapsPlaceAnswerSourcesReviewSnippet, + GroundingChunkMapsPlaceAnswerSourcesReviewSnippetDict, +] + + +class GroundingChunkMapsPlaceAnswerSources(_common.BaseModel): + """The sources that were used to generate the place answer. + + This includes review snippets and photos that were used to generate the + answer, as well as URIs to flag content. + """ + + review_snippet: Optional[ + list[GroundingChunkMapsPlaceAnswerSourcesReviewSnippet] + ] = Field( + default=None, + description="""Snippets of reviews that were used to generate the answer.""", + ) + flag_content_uri: Optional[str] = Field( + default=None, + description="""A link where users can flag a problem with the generated answer.""", + ) + review_snippets: Optional[ + list[GroundingChunkMapsPlaceAnswerSourcesReviewSnippet] + ] = Field( + default=None, + description="""Snippets of reviews that were used to generate the answer.""", + ) + + +class GroundingChunkMapsPlaceAnswerSourcesDict(TypedDict, total=False): + """The sources that were used to generate the place answer. + + This includes review snippets and photos that were used to generate the + answer, as well as URIs to flag content. + """ + + review_snippet: Optional[ + list[GroundingChunkMapsPlaceAnswerSourcesReviewSnippetDict] + ] + """Snippets of reviews that were used to generate the answer.""" + + flag_content_uri: Optional[str] + """A link where users can flag a problem with the generated answer.""" + + review_snippets: Optional[ + list[GroundingChunkMapsPlaceAnswerSourcesReviewSnippetDict] + ] + """Snippets of reviews that were used to generate the answer.""" + + +GroundingChunkMapsPlaceAnswerSourcesOrDict = Union[ + GroundingChunkMapsPlaceAnswerSources, + GroundingChunkMapsPlaceAnswerSourcesDict, +] + + +class GroundingChunkMapsRoute(_common.BaseModel): + """Route information from Google Maps. + + This data type is not supported in Gemini API. + """ + + distance_meters: Optional[int] = Field( + default=None, + description="""The total distance of the route, in meters.""", + ) + duration: Optional[str] = Field( + default=None, description="""The total duration of the route.""" + ) + encoded_polyline: Optional[str] = Field( + default=None, + description="""An encoded polyline of the route. See https://developers.google.com/maps/documentation/utilities/polylinealgorithm""", + ) + + +class GroundingChunkMapsRouteDict(TypedDict, total=False): + """Route information from Google Maps. + + This data type is not supported in Gemini API. + """ + + distance_meters: Optional[int] + """The total distance of the route, in meters.""" + + duration: Optional[str] + """The total duration of the route.""" + + encoded_polyline: Optional[str] + """An encoded polyline of the route. See https://developers.google.com/maps/documentation/utilities/polylinealgorithm""" + + +GroundingChunkMapsRouteOrDict = Union[ + GroundingChunkMapsRoute, GroundingChunkMapsRouteDict +] + + +class GroundingChunkMaps(_common.BaseModel): + """A `Maps` chunk is a piece of evidence that comes from Google Maps. + + It contains information about a place, such as its name, address, and reviews. + This is used to provide the user with rich, location-based information. + """ + + place_answer_sources: Optional[GroundingChunkMapsPlaceAnswerSources] = Field( + default=None, + description="""The sources that were used to generate the place answer. + + This includes review snippets and photos that were used to generate the + answer, as well as URIs to flag content.""", + ) + place_id: Optional[str] = Field( + default=None, + description="""This Place's resource name, in `places/{place_id}` format. + + This can be used to look up the place in the Google Maps API.""", + ) + text: Optional[str] = Field( + default=None, description="""The text of the place answer.""" + ) + title: Optional[str] = Field( + default=None, description="""The title of the place.""" + ) + uri: Optional[str] = Field( + default=None, description="""The URI of the place.""" + ) + route: Optional[GroundingChunkMapsRoute] = Field( + default=None, description="""Output only. Route information.""" + ) + + +class GroundingChunkMapsDict(TypedDict, total=False): + """A `Maps` chunk is a piece of evidence that comes from Google Maps. + + It contains information about a place, such as its name, address, and reviews. + This is used to provide the user with rich, location-based information. + """ + + place_answer_sources: Optional[GroundingChunkMapsPlaceAnswerSourcesDict] + """The sources that were used to generate the place answer. + + This includes review snippets and photos that were used to generate the + answer, as well as URIs to flag content.""" + + place_id: Optional[str] + """This Place's resource name, in `places/{place_id}` format. + + This can be used to look up the place in the Google Maps API.""" + + text: Optional[str] + """The text of the place answer.""" + + title: Optional[str] + """The title of the place.""" + + uri: Optional[str] + """The URI of the place.""" + + route: Optional[GroundingChunkMapsRouteDict] + """Output only. Route information.""" + + +GroundingChunkMapsOrDict = Union[GroundingChunkMaps, GroundingChunkMapsDict] + + +class GroundingChunkImage(_common.BaseModel): + """An `Image` chunk is a piece of evidence that comes from an image search result. + + It contains the URI of the image search result and the URI of the image. This + is used to provide the user with a link to the source of the information. + """ + + source_uri: Optional[str] = Field( + default=None, description="""The URI of the image search result page.""" + ) + image_uri: Optional[str] = Field( + default=None, description="""The URI of the image.""" + ) + title: Optional[str] = Field( + default=None, description="""The title of the image search result page.""" + ) + domain: Optional[str] = Field( + default=None, + description="""The domain of the image search result page.""", + ) + + +class GroundingChunkImageDict(TypedDict, total=False): + """An `Image` chunk is a piece of evidence that comes from an image search result. + + It contains the URI of the image search result and the URI of the image. This + is used to provide the user with a link to the source of the information. + """ + + source_uri: Optional[str] + """The URI of the image search result page.""" + + image_uri: Optional[str] + """The URI of the image.""" + + title: Optional[str] + """The title of the image search result page.""" + + domain: Optional[str] + """The domain of the image search result page.""" + + +GroundingChunkImageOrDict = Union[GroundingChunkImage, GroundingChunkImageDict] + + +class RagChunkPageSpan(_common.BaseModel): + """Represents where the chunk starts and ends in the document. + + This data type is not supported in Gemini API. + """ + + first_page: Optional[int] = Field( + default=None, + description="""Page where chunk starts in the document. Inclusive. 1-indexed.""", + ) + last_page: Optional[int] = Field( + default=None, + description="""Page where chunk ends in the document. Inclusive. 1-indexed.""", + ) + + +class RagChunkPageSpanDict(TypedDict, total=False): + """Represents where the chunk starts and ends in the document. + + This data type is not supported in Gemini API. + """ + + first_page: Optional[int] + """Page where chunk starts in the document. Inclusive. 1-indexed.""" + + last_page: Optional[int] + """Page where chunk ends in the document. Inclusive. 1-indexed.""" + + +RagChunkPageSpanOrDict = Union[RagChunkPageSpan, RagChunkPageSpanDict] + + +class RagChunk(_common.BaseModel): + """A RagChunk includes the content of a chunk of a RagFile, and associated metadata. + + This data type is not supported in Gemini API. + """ + + page_span: Optional[RagChunkPageSpan] = Field( + default=None, + description="""If populated, represents where the chunk starts and ends in the document.""", + ) + text: Optional[str] = Field( + default=None, description="""The content of the chunk.""" + ) + + +class RagChunkDict(TypedDict, total=False): + """A RagChunk includes the content of a chunk of a RagFile, and associated metadata. + + This data type is not supported in Gemini API. + """ + + page_span: Optional[RagChunkPageSpanDict] + """If populated, represents where the chunk starts and ends in the document.""" + + text: Optional[str] + """The content of the chunk.""" + + +RagChunkOrDict = Union[RagChunk, RagChunkDict] + + +class GroundingChunkStringList(_common.BaseModel): + """A list of string values. This data type is not supported in Vertex AI.""" + + values: Optional[list[str]] = Field( + default=None, description="""The string values of the list.""" + ) + + +class GroundingChunkStringListDict(TypedDict, total=False): + """A list of string values. This data type is not supported in Vertex AI.""" + + values: Optional[list[str]] + """The string values of the list.""" + + +GroundingChunkStringListOrDict = Union[ + GroundingChunkStringList, GroundingChunkStringListDict +] + + +class GroundingChunkCustomMetadata(_common.BaseModel): + """User provided metadata about the GroundingFact. + + This data type is not supported in Vertex AI. + """ + + key: Optional[str] = Field( + default=None, description="""The key of the metadata.""" + ) + numeric_value: Optional[float] = Field( + default=None, + description="""Optional. The numeric value of the metadata. The expected range for this value depends on the specific `key` used.""", + ) + string_list_value: Optional[GroundingChunkStringList] = Field( + default=None, + description="""Optional. A list of string values for the metadata.""", + ) + string_value: Optional[str] = Field( + default=None, + description="""Optional. The string value of the metadata.""", + ) + + +class GroundingChunkCustomMetadataDict(TypedDict, total=False): + """User provided metadata about the GroundingFact. + + This data type is not supported in Vertex AI. + """ + + key: Optional[str] + """The key of the metadata.""" + + numeric_value: Optional[float] + """Optional. The numeric value of the metadata. The expected range for this value depends on the specific `key` used.""" + + string_list_value: Optional[GroundingChunkStringListDict] + """Optional. A list of string values for the metadata.""" + + string_value: Optional[str] + """Optional. The string value of the metadata.""" + + +GroundingChunkCustomMetadataOrDict = Union[ + GroundingChunkCustomMetadata, GroundingChunkCustomMetadataDict +] + + +class GroundingChunkRetrievedContext(_common.BaseModel): + """Context retrieved from a data source to ground the model's response. + + This is used when a retrieval tool fetches information from a user-provided + corpus or a public dataset. + """ + + document_name: Optional[str] = Field( + default=None, + description="""Output only. The full resource name of the referenced Vertex AI Search document. This is used to identify the specific document that was retrieved. The format is `projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document}`. This field is not supported in Gemini API.""", + ) + rag_chunk: Optional[RagChunk] = Field( + default=None, + description="""Additional context for a Retrieval-Augmented Generation (RAG) retrieval result. This is populated only when the RAG retrieval tool is used. This field is not supported in Gemini API.""", + ) + text: Optional[str] = Field( + default=None, description="""The content of the retrieved data source.""" + ) + title: Optional[str] = Field( + default=None, description="""The title of the retrieved data source.""" + ) + uri: Optional[str] = Field( + default=None, description="""The URI of the retrieved data source.""" + ) + custom_metadata: Optional[list[GroundingChunkCustomMetadata]] = Field( + default=None, + description="""Optional. User-provided metadata about the retrieved context. This field is not supported in Vertex AI.""", + ) + file_search_store: Optional[str] = Field( + default=None, + description="""Optional. Name of the `FileSearchStore` containing the document. Example: `fileSearchStores/123`. This field is not supported in Vertex AI.""", + ) + + +class GroundingChunkRetrievedContextDict(TypedDict, total=False): + """Context retrieved from a data source to ground the model's response. + + This is used when a retrieval tool fetches information from a user-provided + corpus or a public dataset. + """ + + document_name: Optional[str] + """Output only. The full resource name of the referenced Vertex AI Search document. This is used to identify the specific document that was retrieved. The format is `projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}/documents/{document}`. This field is not supported in Gemini API.""" + + rag_chunk: Optional[RagChunkDict] + """Additional context for a Retrieval-Augmented Generation (RAG) retrieval result. This is populated only when the RAG retrieval tool is used. This field is not supported in Gemini API.""" + + text: Optional[str] + """The content of the retrieved data source.""" + + title: Optional[str] + """The title of the retrieved data source.""" + + uri: Optional[str] + """The URI of the retrieved data source.""" + + custom_metadata: Optional[list[GroundingChunkCustomMetadataDict]] + """Optional. User-provided metadata about the retrieved context. This field is not supported in Vertex AI.""" + + file_search_store: Optional[str] + """Optional. Name of the `FileSearchStore` containing the document. Example: `fileSearchStores/123`. This field is not supported in Vertex AI.""" + + +GroundingChunkRetrievedContextOrDict = Union[ + GroundingChunkRetrievedContext, GroundingChunkRetrievedContextDict +] + + +class GroundingChunkWeb(_common.BaseModel): + """A `Web` chunk is a piece of evidence that comes from a web page. + + It contains the URI of the web page, the title of the page, and the domain of + the page. This is used to provide the user with a link to the source of the + information. + """ + + domain: Optional[str] = Field( + default=None, + description="""The domain of the web page that contains the evidence. This can be used to filter out low-quality sources. This field is not supported in Gemini API.""", + ) + title: Optional[str] = Field( + default=None, + description="""The title of the web page that contains the evidence.""", + ) + uri: Optional[str] = Field( + default=None, + description="""The URI of the web page that contains the evidence.""", + ) + + +class GroundingChunkWebDict(TypedDict, total=False): + """A `Web` chunk is a piece of evidence that comes from a web page. + + It contains the URI of the web page, the title of the page, and the domain of + the page. This is used to provide the user with a link to the source of the + information. + """ + + domain: Optional[str] + """The domain of the web page that contains the evidence. This can be used to filter out low-quality sources. This field is not supported in Gemini API.""" + + title: Optional[str] + """The title of the web page that contains the evidence.""" + + uri: Optional[str] + """The URI of the web page that contains the evidence.""" + + +GroundingChunkWebOrDict = Union[GroundingChunkWeb, GroundingChunkWebDict] + + +class GroundingChunk(_common.BaseModel): + """A piece of evidence that supports a claim made by the model. + + This is used to show a citation for a claim made by the model. When grounding + is enabled, the model returns a `GroundingChunk` that contains a reference to + the source of the information. + """ + + image: Optional[GroundingChunkImage] = Field( + default=None, + description="""A grounding chunk from an image search result. See the `Image` message for details.""", + ) + maps: Optional[GroundingChunkMaps] = Field( + default=None, + description="""A `Maps` chunk is a piece of evidence that comes from Google Maps. + + It contains information about a place, such as its name, address, and + reviews. This is used to provide the user with rich, location-based + information.""", + ) + retrieved_context: Optional[GroundingChunkRetrievedContext] = Field( + default=None, + description="""A grounding chunk from a data source retrieved by a retrieval tool, such as Vertex AI Search. See the `RetrievedContext` message for details""", + ) + web: Optional[GroundingChunkWeb] = Field( + default=None, + description="""A grounding chunk from a web page, typically from Google Search. See the `Web` message for details.""", + ) + + +class GroundingChunkDict(TypedDict, total=False): + """A piece of evidence that supports a claim made by the model. + + This is used to show a citation for a claim made by the model. When grounding + is enabled, the model returns a `GroundingChunk` that contains a reference to + the source of the information. + """ + + image: Optional[GroundingChunkImageDict] + """A grounding chunk from an image search result. See the `Image` message for details.""" + + maps: Optional[GroundingChunkMapsDict] + """A `Maps` chunk is a piece of evidence that comes from Google Maps. + + It contains information about a place, such as its name, address, and + reviews. This is used to provide the user with rich, location-based + information.""" + + retrieved_context: Optional[GroundingChunkRetrievedContextDict] + """A grounding chunk from a data source retrieved by a retrieval tool, such as Vertex AI Search. See the `RetrievedContext` message for details""" + + web: Optional[GroundingChunkWebDict] + """A grounding chunk from a web page, typically from Google Search. See the `Web` message for details.""" + + +GroundingChunkOrDict = Union[GroundingChunk, GroundingChunkDict] + + +class Segment(_common.BaseModel): + """Segment of the content this support belongs to.""" + + start_index: Optional[int] = Field( + default=None, + description="""Output only. Start index in the given Part, measured in bytes. + + Offset from the start of the Part, inclusive, starting at zero.""", + ) + end_index: Optional[int] = Field( + default=None, + description="""Output only. End index in the given Part, measured in bytes. + + Offset from the start of the Part, exclusive, starting at zero.""", + ) + part_index: Optional[int] = Field( + default=None, + description="""Output only. The index of a Part object within its parent + Content object.""", + ) + text: Optional[str] = Field( + default=None, + description="""Output only. The text corresponding to the segment from the + response.""", + ) + + +class SegmentDict(TypedDict, total=False): + """Segment of the content this support belongs to.""" + + start_index: Optional[int] + """Output only. Start index in the given Part, measured in bytes. + + Offset from the start of the Part, inclusive, starting at zero.""" + + end_index: Optional[int] + """Output only. End index in the given Part, measured in bytes. + + Offset from the start of the Part, exclusive, starting at zero.""" + + part_index: Optional[int] + """Output only. The index of a Part object within its parent + Content object.""" + + text: Optional[str] + """Output only. The text corresponding to the segment from the + response.""" + + +SegmentOrDict = Union[Segment, SegmentDict] + + +class GroundingSupport(_common.BaseModel): + """Grounding support.""" + + confidence_scores: Optional[list[float]] = Field( + default=None, + description="""Confidence score of the support references. + + Ranges from 0 to 1. 1 is the most confident. This list must have the + same size as the grounding_chunk_indices.""", + ) + grounding_chunk_indices: Optional[list[int]] = Field( + default=None, + description="""A list of indices (into 'grounding_chunk') specifying the + citations associated with the claim. For instance [1,3,4] means that + grounding_chunk[1], grounding_chunk[3], grounding_chunk[4] are the + retrieved content attributed to the claim.""", + ) + segment: Optional[Segment] = Field( + default=None, + description="""Segment of the content this support belongs to.""", + ) + rendered_parts: Optional[list[int]] = Field( + default=None, + description="""Indices into the `rendered_parts` field of the `GroundingMetadata` message. These indices specify which rendered parts are associated with this support message.""", + ) + + +class GroundingSupportDict(TypedDict, total=False): + """Grounding support.""" + + confidence_scores: Optional[list[float]] + """Confidence score of the support references. + + Ranges from 0 to 1. 1 is the most confident. This list must have the + same size as the grounding_chunk_indices.""" + + grounding_chunk_indices: Optional[list[int]] + """A list of indices (into 'grounding_chunk') specifying the + citations associated with the claim. For instance [1,3,4] means that + grounding_chunk[1], grounding_chunk[3], grounding_chunk[4] are the + retrieved content attributed to the claim.""" + + segment: Optional[SegmentDict] + """Segment of the content this support belongs to.""" + + rendered_parts: Optional[list[int]] + """Indices into the `rendered_parts` field of the `GroundingMetadata` message. These indices specify which rendered parts are associated with this support message.""" + + +GroundingSupportOrDict = Union[GroundingSupport, GroundingSupportDict] + + +class RetrievalMetadata(_common.BaseModel): + """Metadata returned to client when grounding is enabled.""" + + google_search_dynamic_retrieval_score: Optional[float] = Field( + default=None, + description="""Optional. Score indicating how likely information from google + search could help answer the prompt. The score is in the range [0, 1], + where 0 is the least likely and 1 is the most likely. This score is only + populated when google search grounding and dynamic retrieval is enabled. + It will be compared to the threshold to determine whether to trigger + Google search.""", + ) + + +class RetrievalMetadataDict(TypedDict, total=False): + """Metadata returned to client when grounding is enabled.""" + + google_search_dynamic_retrieval_score: Optional[float] + """Optional. Score indicating how likely information from google + search could help answer the prompt. The score is in the range [0, 1], + where 0 is the least likely and 1 is the most likely. This score is only + populated when google search grounding and dynamic retrieval is enabled. + It will be compared to the threshold to determine whether to trigger + Google search.""" + + +RetrievalMetadataOrDict = Union[RetrievalMetadata, RetrievalMetadataDict] + + +class SearchEntryPoint(_common.BaseModel): + """The entry point used to search for grounding sources.""" + + rendered_content: Optional[str] = Field( + default=None, + description="""Optional. Web content snippet that can be embedded in a web page + or an app webview.""", + ) + sdk_blob: Optional[bytes] = Field( + default=None, + description="""Optional. JSON representing array of tuples.""", + ) + + +class SearchEntryPointDict(TypedDict, total=False): + """The entry point used to search for grounding sources.""" + + rendered_content: Optional[str] + """Optional. Web content snippet that can be embedded in a web page + or an app webview.""" + + sdk_blob: Optional[bytes] + """Optional. JSON representing array of tuples.""" + + +SearchEntryPointOrDict = Union[SearchEntryPoint, SearchEntryPointDict] + + +class GroundingMetadataSourceFlaggingUri(_common.BaseModel): + """A URI that can be used to flag a place or review for inappropriate content. + + This is populated only when the grounding source is Google Maps. This data + type is not supported in Gemini API. + """ + + flag_content_uri: Optional[str] = Field( + default=None, + description="""The URI that can be used to flag the content.""", + ) + source_id: Optional[str] = Field( + default=None, description="""The ID of the place or review.""" + ) + + +class GroundingMetadataSourceFlaggingUriDict(TypedDict, total=False): + """A URI that can be used to flag a place or review for inappropriate content. + + This is populated only when the grounding source is Google Maps. This data + type is not supported in Gemini API. + """ + + flag_content_uri: Optional[str] + """The URI that can be used to flag the content.""" + + source_id: Optional[str] + """The ID of the place or review.""" + + +GroundingMetadataSourceFlaggingUriOrDict = Union[ + GroundingMetadataSourceFlaggingUri, GroundingMetadataSourceFlaggingUriDict +] + + +class GroundingMetadata(_common.BaseModel): + """Information for various kinds of grounding.""" + + image_search_queries: Optional[list[str]] = Field( + default=None, + description="""Optional. The image search queries that were used to generate the content. This field is populated only when the grounding source is Google Search with the Image Search search_type enabled.""", + ) + grounding_chunks: Optional[list[GroundingChunk]] = Field( + default=None, + description="""A list of supporting references retrieved from the grounding + source. This field is populated when the grounding source is Google + Search, Vertex AI Search, or Google Maps. + """, + ) + grounding_supports: Optional[list[GroundingSupport]] = Field( + default=None, description="""List of grounding support.""" + ) + retrieval_metadata: Optional[RetrievalMetadata] = Field( + default=None, + description="""Metadata related to retrieval in the grounding flow.""", + ) + search_entry_point: Optional[SearchEntryPoint] = Field( + default=None, + description="""Optional. Google search entry for the following-up web + searches.""", + ) + web_search_queries: Optional[list[str]] = Field( + default=None, + description="""Web search queries for the following-up web search.""", + ) + google_maps_widget_context_token: Optional[str] = Field( + default=None, + description="""Optional. Output only. A token that can be used to render a Google Maps widget with the contextual data. This field is populated only when the grounding source is Google Maps.""", + ) + retrieval_queries: Optional[list[str]] = Field( + default=None, + description="""Optional. The queries that were executed by the retrieval tools. This field is populated only when the grounding source is a retrieval tool, such as Vertex AI Search. This field is not supported in Gemini API.""", + ) + source_flagging_uris: Optional[list[GroundingMetadataSourceFlaggingUri]] = ( + Field( + default=None, + description="""Optional. Output only. A list of URIs that can be used to flag a place or review for inappropriate content. This field is populated only when the grounding source is Google Maps. This field is not supported in Gemini API.""", + ) + ) + + +class GroundingMetadataDict(TypedDict, total=False): + """Information for various kinds of grounding.""" + + image_search_queries: Optional[list[str]] + """Optional. The image search queries that were used to generate the content. This field is populated only when the grounding source is Google Search with the Image Search search_type enabled.""" + + grounding_chunks: Optional[list[GroundingChunkDict]] + """A list of supporting references retrieved from the grounding + source. This field is populated when the grounding source is Google + Search, Vertex AI Search, or Google Maps. + """ + + grounding_supports: Optional[list[GroundingSupportDict]] + """List of grounding support.""" + + retrieval_metadata: Optional[RetrievalMetadataDict] + """Metadata related to retrieval in the grounding flow.""" + + search_entry_point: Optional[SearchEntryPointDict] + """Optional. Google search entry for the following-up web + searches.""" + + web_search_queries: Optional[list[str]] + """Web search queries for the following-up web search.""" + + google_maps_widget_context_token: Optional[str] + """Optional. Output only. A token that can be used to render a Google Maps widget with the contextual data. This field is populated only when the grounding source is Google Maps.""" + + retrieval_queries: Optional[list[str]] + """Optional. The queries that were executed by the retrieval tools. This field is populated only when the grounding source is a retrieval tool, such as Vertex AI Search. This field is not supported in Gemini API.""" + + source_flagging_uris: Optional[list[GroundingMetadataSourceFlaggingUriDict]] + """Optional. Output only. A list of URIs that can be used to flag a place or review for inappropriate content. This field is populated only when the grounding source is Google Maps. This field is not supported in Gemini API.""" + + +GroundingMetadataOrDict = Union[GroundingMetadata, GroundingMetadataDict] + + +class LogprobsResultCandidate(_common.BaseModel): + """A single token and its associated log probability.""" + + log_probability: Optional[float] = Field( + default=None, + description="""The log probability of this token. A higher value indicates that the model was more confident in this token. The log probability can be used to assess the relative likelihood of different tokens and to identify when the model is uncertain.""", + ) + token: Optional[str] = Field( + default=None, description="""The token's string representation.""" + ) + token_id: Optional[int] = Field( + default=None, + description="""The token's numerical ID. While the `token` field provides the string representation of the token, the `token_id` is the numerical representation that the model uses internally. This can be useful for developers who want to build custom logic based on the model's vocabulary.""", + ) + + +class LogprobsResultCandidateDict(TypedDict, total=False): + """A single token and its associated log probability.""" + + log_probability: Optional[float] + """The log probability of this token. A higher value indicates that the model was more confident in this token. The log probability can be used to assess the relative likelihood of different tokens and to identify when the model is uncertain.""" + + token: Optional[str] + """The token's string representation.""" + + token_id: Optional[int] + """The token's numerical ID. While the `token` field provides the string representation of the token, the `token_id` is the numerical representation that the model uses internally. This can be useful for developers who want to build custom logic based on the model's vocabulary.""" + + +LogprobsResultCandidateOrDict = Union[ + LogprobsResultCandidate, LogprobsResultCandidateDict +] + + +class LogprobsResultTopCandidates(_common.BaseModel): + """A list of the top candidate tokens and their log probabilities at each decoding step. + + This can be used to see what other tokens the model considered. + """ + + candidates: Optional[list[LogprobsResultCandidate]] = Field( + default=None, + description="""The list of candidate tokens, sorted by log probability in descending order.""", + ) + + +class LogprobsResultTopCandidatesDict(TypedDict, total=False): + """A list of the top candidate tokens and their log probabilities at each decoding step. + + This can be used to see what other tokens the model considered. + """ + + candidates: Optional[list[LogprobsResultCandidateDict]] + """The list of candidate tokens, sorted by log probability in descending order.""" + + +LogprobsResultTopCandidatesOrDict = Union[ + LogprobsResultTopCandidates, LogprobsResultTopCandidatesDict +] + + +class LogprobsResult(_common.BaseModel): + """The log probabilities of the tokens generated by the model. + + This is useful for understanding the model's confidence in its predictions and + for debugging. For example, you can use log probabilities to identify when the + model is making a less confident prediction or to explore alternative + responses that the model considered. A low log probability can also indicate + that the model is "hallucinating" or generating factually incorrect + information. + """ + + chosen_candidates: Optional[list[LogprobsResultCandidate]] = Field( + default=None, + description="""A list of the chosen candidate tokens at each decoding step. The length of this list is equal to the total number of decoding steps. Note that the chosen candidate might not be in `top_candidates`.""", + ) + top_candidates: Optional[list[LogprobsResultTopCandidates]] = Field( + default=None, + description="""A list of the top candidate tokens at each decoding step. The length of this list is equal to the total number of decoding steps.""", + ) + log_probability_sum: Optional[float] = Field( + default=None, + description="""Sum of log probabilities for all tokens. This field is not supported in Vertex AI.""", + ) + + +class LogprobsResultDict(TypedDict, total=False): + """The log probabilities of the tokens generated by the model. + + This is useful for understanding the model's confidence in its predictions and + for debugging. For example, you can use log probabilities to identify when the + model is making a less confident prediction or to explore alternative + responses that the model considered. A low log probability can also indicate + that the model is "hallucinating" or generating factually incorrect + information. + """ + + chosen_candidates: Optional[list[LogprobsResultCandidateDict]] + """A list of the chosen candidate tokens at each decoding step. The length of this list is equal to the total number of decoding steps. Note that the chosen candidate might not be in `top_candidates`.""" + + top_candidates: Optional[list[LogprobsResultTopCandidatesDict]] + """A list of the top candidate tokens at each decoding step. The length of this list is equal to the total number of decoding steps.""" + + log_probability_sum: Optional[float] + """Sum of log probabilities for all tokens. This field is not supported in Vertex AI.""" + + +LogprobsResultOrDict = Union[LogprobsResult, LogprobsResultDict] + + +class SafetyRating(_common.BaseModel): + """A safety rating for a piece of content. + + The safety rating contains the harm category and the harm probability level. + """ + + blocked: Optional[bool] = Field( + default=None, + description="""Output only. Indicates whether the content was blocked because of this rating.""", + ) + category: Optional[HarmCategory] = Field( + default=None, + description="""Output only. The harm category of this rating.""", + ) + overwritten_threshold: Optional[HarmBlockThreshold] = Field( + default=None, + description="""Output only. The overwritten threshold for the safety category of Gemini 2.0 image out. If minors are detected in the output image, the threshold of each safety category will be overwritten if user sets a lower threshold. This field is not supported in Gemini API.""", + ) + probability: Optional[HarmProbability] = Field( + default=None, + description="""Output only. The probability of harm for this category.""", + ) + probability_score: Optional[float] = Field( + default=None, + description="""Output only. The probability score of harm for this category. This field is not supported in Gemini API.""", + ) + severity: Optional[HarmSeverity] = Field( + default=None, + description="""Output only. The severity of harm for this category. This field is not supported in Gemini API.""", + ) + severity_score: Optional[float] = Field( + default=None, + description="""Output only. The severity score of harm for this category. This field is not supported in Gemini API.""", + ) + + +class SafetyRatingDict(TypedDict, total=False): + """A safety rating for a piece of content. + + The safety rating contains the harm category and the harm probability level. + """ + + blocked: Optional[bool] + """Output only. Indicates whether the content was blocked because of this rating.""" + + category: Optional[HarmCategory] + """Output only. The harm category of this rating.""" + + overwritten_threshold: Optional[HarmBlockThreshold] + """Output only. The overwritten threshold for the safety category of Gemini 2.0 image out. If minors are detected in the output image, the threshold of each safety category will be overwritten if user sets a lower threshold. This field is not supported in Gemini API.""" + + probability: Optional[HarmProbability] + """Output only. The probability of harm for this category.""" + + probability_score: Optional[float] + """Output only. The probability score of harm for this category. This field is not supported in Gemini API.""" + + severity: Optional[HarmSeverity] + """Output only. The severity of harm for this category. This field is not supported in Gemini API.""" + + severity_score: Optional[float] + """Output only. The severity score of harm for this category. This field is not supported in Gemini API.""" + + +SafetyRatingOrDict = Union[SafetyRating, SafetyRatingDict] + + +class UrlMetadata(_common.BaseModel): + """The metadata for a single URL retrieval.""" + + retrieved_url: Optional[str] = Field( + default=None, description="""The URL retrieved by the tool.""" + ) + url_retrieval_status: Optional[UrlRetrievalStatus] = Field( + default=None, description="""The status of the URL retrieval.""" + ) + + +class UrlMetadataDict(TypedDict, total=False): + """The metadata for a single URL retrieval.""" + + retrieved_url: Optional[str] + """The URL retrieved by the tool.""" + + url_retrieval_status: Optional[UrlRetrievalStatus] + """The status of the URL retrieval.""" + + +UrlMetadataOrDict = Union[UrlMetadata, UrlMetadataDict] + + +class UrlContextMetadata(_common.BaseModel): + """Metadata returned when the model uses the `url_context` tool to get information from a user-provided URL.""" + + url_metadata: Optional[list[UrlMetadata]] = Field( + default=None, + description="""Output only. A list of URL metadata, with one entry for each URL retrieved by the tool.""", + ) + + +class UrlContextMetadataDict(TypedDict, total=False): + """Metadata returned when the model uses the `url_context` tool to get information from a user-provided URL.""" + + url_metadata: Optional[list[UrlMetadataDict]] + """Output only. A list of URL metadata, with one entry for each URL retrieved by the tool.""" + + +UrlContextMetadataOrDict = Union[UrlContextMetadata, UrlContextMetadataDict] + + +class Candidate(_common.BaseModel): + """A response candidate generated from the model.""" + + content: Optional[Content] = Field( + default=None, + description="""Contains the multi-part content of the response. + """, + ) + citation_metadata: Optional[CitationMetadata] = Field( + default=None, + description="""Source attribution of the generated content. + """, + ) + finish_message: Optional[str] = Field( + default=None, + description="""Describes the reason the model stopped generating tokens. + """, + ) + token_count: Optional[int] = Field( + default=None, + description="""Number of tokens for this candidate. + """, + ) + finish_reason: Optional[FinishReason] = Field( + default=None, + description="""The reason why the model stopped generating tokens. + If empty, the model has not stopped generating the tokens. + """, + ) + grounding_metadata: Optional[GroundingMetadata] = Field( + default=None, + description="""Output only. Metadata returned when grounding is enabled. It + contains the sources used to ground the generated content. + """, + ) + avg_logprobs: Optional[float] = Field( + default=None, + description="""Output only. The average log probability of the tokens in this candidate. This is a length-normalized score that can be used to compare the quality of candidates of different lengths. A higher average log probability suggests a more confident and coherent response.""", + ) + index: Optional[int] = Field( + default=None, + description="""Output only. The 0-based index of this candidate in the list of generated responses. This is useful for distinguishing between multiple candidates when `candidate_count` > 1.""", + ) + logprobs_result: Optional[LogprobsResult] = Field( + default=None, + description="""Output only. The detailed log probability information for the tokens in this candidate. This is useful for debugging, understanding model uncertainty, and identifying potential "hallucinations".""", + ) + safety_ratings: Optional[list[SafetyRating]] = Field( + default=None, + description="""Output only. A list of ratings for the safety of a response candidate. There is at most one rating per category.""", + ) + url_context_metadata: Optional[UrlContextMetadata] = Field( + default=None, + description="""Output only. Metadata returned when the model uses the `url_context` tool to get information from a user-provided URL.""", + ) + + +class CandidateDict(TypedDict, total=False): + """A response candidate generated from the model.""" + + content: Optional[ContentDict] + """Contains the multi-part content of the response. + """ + + citation_metadata: Optional[CitationMetadataDict] + """Source attribution of the generated content. + """ + + finish_message: Optional[str] + """Describes the reason the model stopped generating tokens. + """ + + token_count: Optional[int] + """Number of tokens for this candidate. + """ + + finish_reason: Optional[FinishReason] + """The reason why the model stopped generating tokens. + If empty, the model has not stopped generating the tokens. + """ + + grounding_metadata: Optional[GroundingMetadataDict] + """Output only. Metadata returned when grounding is enabled. It + contains the sources used to ground the generated content. + """ + + avg_logprobs: Optional[float] + """Output only. The average log probability of the tokens in this candidate. This is a length-normalized score that can be used to compare the quality of candidates of different lengths. A higher average log probability suggests a more confident and coherent response.""" + + index: Optional[int] + """Output only. The 0-based index of this candidate in the list of generated responses. This is useful for distinguishing between multiple candidates when `candidate_count` > 1.""" + + logprobs_result: Optional[LogprobsResultDict] + """Output only. The detailed log probability information for the tokens in this candidate. This is useful for debugging, understanding model uncertainty, and identifying potential "hallucinations".""" + + safety_ratings: Optional[list[SafetyRatingDict]] + """Output only. A list of ratings for the safety of a response candidate. There is at most one rating per category.""" + + url_context_metadata: Optional[UrlContextMetadataDict] + """Output only. Metadata returned when the model uses the `url_context` tool to get information from a user-provided URL.""" + + +CandidateOrDict = Union[Candidate, CandidateDict] + + +class GenerateContentResponsePromptFeedback(_common.BaseModel): + """Content filter results for a prompt sent in the request. + + Note: This is sent only in the first stream chunk and only if no candidates + were generated due to content violations. + """ + + block_reason: Optional[BlockedReason] = Field( + default=None, + description="""Output only. The reason why the prompt was blocked.""", + ) + block_reason_message: Optional[str] = Field( + default=None, + description="""Output only. A readable message that explains the reason why the prompt was blocked. This field is not supported in Gemini API.""", + ) + safety_ratings: Optional[list[SafetyRating]] = Field( + default=None, + description="""Output only. A list of safety ratings for the prompt. There is one rating per category.""", + ) + + +class GenerateContentResponsePromptFeedbackDict(TypedDict, total=False): + """Content filter results for a prompt sent in the request. + + Note: This is sent only in the first stream chunk and only if no candidates + were generated due to content violations. + """ + + block_reason: Optional[BlockedReason] + """Output only. The reason why the prompt was blocked.""" + + block_reason_message: Optional[str] + """Output only. A readable message that explains the reason why the prompt was blocked. This field is not supported in Gemini API.""" + + safety_ratings: Optional[list[SafetyRatingDict]] + """Output only. A list of safety ratings for the prompt. There is one rating per category.""" + + +GenerateContentResponsePromptFeedbackOrDict = Union[ + GenerateContentResponsePromptFeedback, + GenerateContentResponsePromptFeedbackDict, +] + + +class ModalityTokenCount(_common.BaseModel): + """Represents token counting info for a single modality.""" + + modality: Optional[MediaModality] = Field( + default=None, + description="""The modality associated with this token count.""", + ) + token_count: Optional[int] = Field( + default=None, + description="""The number of tokens counted for this modality.""", + ) + + +class ModalityTokenCountDict(TypedDict, total=False): + """Represents token counting info for a single modality.""" + + modality: Optional[MediaModality] + """The modality associated with this token count.""" + + token_count: Optional[int] + """The number of tokens counted for this modality.""" + + +ModalityTokenCountOrDict = Union[ModalityTokenCount, ModalityTokenCountDict] + + +class GenerateContentResponseUsageMetadata(_common.BaseModel): + """Usage metadata about the content generation request and response. + + This message provides a detailed breakdown of token usage and other relevant + metrics. This data type is not supported in Gemini API. + """ + + cache_tokens_details: Optional[list[ModalityTokenCount]] = Field( + default=None, + description="""Output only. A detailed breakdown of the token count for each modality in the cached content.""", + ) + cached_content_token_count: Optional[int] = Field( + default=None, + description="""Output only. The number of tokens in the cached content that was used for this request.""", + ) + candidates_token_count: Optional[int] = Field( + default=None, + description="""The total number of tokens in the generated candidates.""", + ) + candidates_tokens_details: Optional[list[ModalityTokenCount]] = Field( + default=None, + description="""Output only. A detailed breakdown of the token count for each modality in the generated candidates.""", + ) + prompt_token_count: Optional[int] = Field( + default=None, + description="""The total number of tokens in the prompt. This includes any text, images, or other media provided in the request. When `cached_content` is set, this also includes the number of tokens in the cached content.""", + ) + prompt_tokens_details: Optional[list[ModalityTokenCount]] = Field( + default=None, + description="""Output only. A detailed breakdown of the token count for each modality in the prompt.""", + ) + thoughts_token_count: Optional[int] = Field( + default=None, + description="""Output only. The number of tokens that were part of the model's generated "thoughts" output, if applicable.""", + ) + tool_use_prompt_token_count: Optional[int] = Field( + default=None, + description="""Output only. The number of tokens in the results from tool executions, which are provided back to the model as input, if applicable.""", + ) + tool_use_prompt_tokens_details: Optional[list[ModalityTokenCount]] = Field( + default=None, + description="""Output only. A detailed breakdown by modality of the token counts from the results of tool executions, which are provided back to the model as input.""", + ) + total_token_count: Optional[int] = Field( + default=None, + description="""The total number of tokens for the entire request. This is the sum of `prompt_token_count`, `candidates_token_count`, `tool_use_prompt_token_count`, and `thoughts_token_count`.""", + ) + traffic_type: Optional[TrafficType] = Field( + default=None, + description="""Output only. The traffic type for this request.""", + ) + + +class GenerateContentResponseUsageMetadataDict(TypedDict, total=False): + """Usage metadata about the content generation request and response. + + This message provides a detailed breakdown of token usage and other relevant + metrics. This data type is not supported in Gemini API. + """ + + cache_tokens_details: Optional[list[ModalityTokenCountDict]] + """Output only. A detailed breakdown of the token count for each modality in the cached content.""" + + cached_content_token_count: Optional[int] + """Output only. The number of tokens in the cached content that was used for this request.""" + + candidates_token_count: Optional[int] + """The total number of tokens in the generated candidates.""" + + candidates_tokens_details: Optional[list[ModalityTokenCountDict]] + """Output only. A detailed breakdown of the token count for each modality in the generated candidates.""" + + prompt_token_count: Optional[int] + """The total number of tokens in the prompt. This includes any text, images, or other media provided in the request. When `cached_content` is set, this also includes the number of tokens in the cached content.""" + + prompt_tokens_details: Optional[list[ModalityTokenCountDict]] + """Output only. A detailed breakdown of the token count for each modality in the prompt.""" + + thoughts_token_count: Optional[int] + """Output only. The number of tokens that were part of the model's generated "thoughts" output, if applicable.""" + + tool_use_prompt_token_count: Optional[int] + """Output only. The number of tokens in the results from tool executions, which are provided back to the model as input, if applicable.""" + + tool_use_prompt_tokens_details: Optional[list[ModalityTokenCountDict]] + """Output only. A detailed breakdown by modality of the token counts from the results of tool executions, which are provided back to the model as input.""" + + total_token_count: Optional[int] + """The total number of tokens for the entire request. This is the sum of `prompt_token_count`, `candidates_token_count`, `tool_use_prompt_token_count`, and `thoughts_token_count`.""" + + traffic_type: Optional[TrafficType] + """Output only. The traffic type for this request.""" + + +GenerateContentResponseUsageMetadataOrDict = Union[ + GenerateContentResponseUsageMetadata, + GenerateContentResponseUsageMetadataDict, +] + + +class ModelStatus(_common.BaseModel): + """The status of the underlying model. + + This is used to indicate the stage of the underlying model and the retirement + time if applicable. This data type is not supported in Vertex AI. + """ + + message: Optional[str] = Field( + default=None, description="""A message explaining the model status.""" + ) + model_stage: Optional[ModelStage] = Field( + default=None, description="""The stage of the underlying model.""" + ) + retirement_time: Optional[datetime.datetime] = Field( + default=None, + description="""The time at which the model will be retired.""", + ) + + +class ModelStatusDict(TypedDict, total=False): + """The status of the underlying model. + + This is used to indicate the stage of the underlying model and the retirement + time if applicable. This data type is not supported in Vertex AI. + """ + + message: Optional[str] + """A message explaining the model status.""" + + model_stage: Optional[ModelStage] + """The stage of the underlying model.""" + + retirement_time: Optional[datetime.datetime] + """The time at which the model will be retired.""" + + +ModelStatusOrDict = Union[ModelStatus, ModelStatusDict] + + +class GenerateContentResponse(_common.BaseModel): + """Response message for PredictionService.GenerateContent.""" + + sdk_http_response: Optional[HttpResponse] = Field( + default=None, description="""Used to retain the full HTTP response.""" + ) + candidates: Optional[list[Candidate]] = Field( + default=None, + description="""Response variations returned by the model. + """, + ) + create_time: Optional[datetime.datetime] = Field( + default=None, + description="""Timestamp when the request is made to the server. + """, + ) + model_version: Optional[str] = Field( + default=None, + description="""Output only. The model version used to generate the response.""", + ) + prompt_feedback: Optional[GenerateContentResponsePromptFeedback] = Field( + default=None, + description="""Output only. Content filter results for a prompt sent in the request. Note: Sent only in the first stream chunk. Only happens when no candidates were generated due to content violations.""", + ) + response_id: Optional[str] = Field( + default=None, + description="""Output only. response_id is used to identify each response. It is the encoding of the event_id.""", + ) + usage_metadata: Optional[GenerateContentResponseUsageMetadata] = Field( + default=None, description="""Usage metadata about the response(s).""" + ) + model_status: Optional[ModelStatus] = Field( + default=None, + description="""Output only. The current model status of this model. This field is not supported in Vertex AI.""", + ) + automatic_function_calling_history: Optional[list[Content]] = None + parsed: Optional[Union[pydantic.BaseModel, dict[Any, Any], Enum]] = Field( + default=None, + description="""First candidate from the parsed response if response_schema is provided. Not available for streaming.""", + ) + + def _get_text(self) -> Optional[str]: + """Returns the concatenation of all text parts in the response. + + This is an internal method that allows customizing or disabling the warning + message. + + Returns: + The concatenation of all text parts in the response. + """ + if ( + not self.candidates + or not self.candidates[0].content + or not self.candidates[0].content.parts + ): + return None + global _response_text_warning_logged + if len(self.candidates) > 1 and not _response_text_warning_logged: + logger.warning( + f'there are {len(self.candidates)} candidates, returning text result' + ' from the first candidate. Access response.candidates directly to' + ' get the result from other candidates.' + ) + _response_text_warning_logged = True + text = '' + any_text_part_text = False + non_text_parts = [] + for part in self.candidates[0].content.parts: + for field_name, field_value in part.model_dump( + exclude={'text', 'thought', 'thought_signature'} + ).items(): + if field_value is not None: + non_text_parts.append(field_name) + if isinstance(part.text, str): + if isinstance(part.thought, bool) and part.thought: + continue + any_text_part_text = True + text += part.text + global _response_text_non_text_warning_logged + if non_text_parts and not _response_text_non_text_warning_logged: + logger.warning( + 'Warning: there are non-text parts in the response:' + f' {non_text_parts}, returning concatenated text result' + ' from text parts. Check the full candidates.content.parts accessor' + ' to get the full model response.' + ) + _response_text_non_text_warning_logged = True + # part.text == '' is different from part.text is None + return text if any_text_part_text else None + + @property + def parts(self) -> Optional[list[Part]]: + """Returns the content-parts in the response. + + If there are multiple candidates, returns the parts from only the first one. + """ + if ( + not self.candidates + or self.candidates[0].content is None + or self.candidates[0].content.parts is None + ): + return None + global _response_parts_warning_logged + if len(self.candidates) > 1 and not _response_parts_warning_logged: + logger.warning( + 'Warning: there are multiple candidates in the response, returning' + ' parts from the first one.' + ) + _response_parts_warning_logged = True + + return self.candidates[0].content.parts + + @property + def text(self) -> Optional[str]: + """Returns the concatenation of all text parts in the response. + + If there are multiple candidates, returns the text from only the first one. + If there are non-text parts in the response, this returns only the text + parts. + """ + return self._get_text() + + @property + def function_calls(self) -> Optional[list[FunctionCall]]: + """Returns the list of function calls in the response. + + If there are multiple candidates, this returns the function calls from only + the + first one. + """ + if ( + not self.candidates + or not self.candidates[0].content + or not self.candidates[0].content.parts + ): + return None + global _response_function_calls_warning_logged + if len(self.candidates) > 1 and not _response_function_calls_warning_logged: + logger.warning( + 'Warning: there are multiple candidates in the response, returning' + ' function calls from the first one.' + ) + _response_function_calls_warning_logged = True + function_calls = [ + part.function_call + for part in self.candidates[0].content.parts + if part.function_call is not None + ] + + return function_calls if function_calls else None + + @property + def executable_code(self) -> Optional[str]: + """Returns the executable code in the response. + + If there are multiple candidates, this returns the executable code from only + the + first one. + """ + if ( + not self.candidates + or not self.candidates[0].content + or not self.candidates[0].content.parts + ): + return None + global _response_executable_code_warning_logged + if ( + len(self.candidates) > 1 + and not _response_executable_code_warning_logged + ): + logging.warning( + 'Warning: there are multiple candidates in the response, returning' + ' executable code from the first one.' + ) + _response_executable_code_warning_logged = True + for part in self.candidates[0].content.parts: + if part.executable_code is not None: + return part.executable_code.code + return None + + @property + def code_execution_result(self) -> Optional[str]: + """Returns the code execution result in the response. + + If there are multiple candidates, this returns the code execution result + from only the + first one. + """ + if ( + not self.candidates + or not self.candidates[0].content + or not self.candidates[0].content.parts + ): + return None + global _response_code_execution_warning_logged + if len(self.candidates) > 1 and not _response_code_execution_warning_logged: + logging.warning( + 'Warning: there are multiple candidates in the response, returning' + ' code execution result from the first one.' + ) + _response_code_execution_warning_logged = True + for part in self.candidates[0].content.parts: + if part.code_execution_result is not None: + return part.code_execution_result.output + return None + + @classmethod + def _from_response( + cls: typing.Type[T], + *, + response: dict[str, object], + kwargs: dict[str, object], + ) -> T: + result = super()._from_response(response=response, kwargs=kwargs) + + # Handles response schema. + response_schema = _common.get_value_by_path( + kwargs, ['config', 'response_schema'] + ) + # Handles response_json_schema. Backend will throw error if both + # response_schema and response_json_schema are set. + if response_schema is None: + response_schema = _common.get_value_by_path( + kwargs, ['config', 'response_json_schema'] + ) + if ( + inspect.isclass(response_schema) + and not ( + isinstance(response_schema, builtin_types.GenericAlias) + ) # Needed for Python 3.9 and 3.10 + and issubclass(response_schema, pydantic.BaseModel) + ): + # Pydantic schema. + try: + result_text = result._get_text() + if result_text is not None: + result.parsed = response_schema.model_validate_json(result_text) + # may not be a valid json per stream response + except pydantic.ValidationError: + pass + except json.decoder.JSONDecodeError: + pass + elif ( + isinstance(response_schema, EnumMeta) and result._get_text() is not None + ): + # Enum with "application/json" returns response in double quotes. + result_text = result._get_text() + if result_text is None: + raise ValueError('Response is empty.') + enum_value = result_text.replace('"', '') + try: + result.parsed = response_schema(enum_value) + if ( + hasattr(response_schema, '__name__') + and response_schema.__name__ == 'PlaceholderLiteralEnum' + ): + result.parsed = str(response_schema(enum_value).name) # type: ignore + except ValueError: + pass + elif isinstance(response_schema, builtin_types.GenericAlias) or isinstance( + response_schema, type + ): + + class Placeholder(pydantic.BaseModel): + placeholder: response_schema # type: ignore[valid-type] + + try: + result_text = result._get_text() + if result_text is not None: + parsed = {'placeholder': json.loads(result_text)} + placeholder = Placeholder.model_validate(parsed) + result.parsed = placeholder.placeholder + except json.decoder.JSONDecodeError: + pass + except pydantic.ValidationError: + pass + + elif isinstance(response_schema, dict) or isinstance( + response_schema, Schema + ): + # With just the Schema, we don't know what pydantic model the user would + # want the result converted to. So just return json. + # JSON schema. + try: + result_text = result._get_text() + if result_text is not None: + result.parsed = json.loads(result_text) + # may not be a valid json per stream response + except json.decoder.JSONDecodeError: + pass + elif typing.get_origin(response_schema) in _UNION_TYPES: + # Union schema. + union_types = typing.get_args(response_schema) + for union_type in union_types: + if issubclass(union_type, pydantic.BaseModel): + try: + result_text = result._get_text() + if result_text is not None: + + class Placeholder(pydantic.BaseModel): # type: ignore[no-redef] + placeholder: response_schema # type: ignore[valid-type] + + parsed = {'placeholder': json.loads(result_text)} + placeholder = Placeholder.model_validate(parsed) + result.parsed = placeholder.placeholder + except json.decoder.JSONDecodeError: + pass + except pydantic.ValidationError: + pass + else: + try: + result_text = result._get_text() + if result_text is not None: + result.parsed = json.loads(result_text) + # may not be a valid json per stream response + except json.decoder.JSONDecodeError: + pass + + return result + + +class GenerateContentResponseDict(TypedDict, total=False): + """Response message for PredictionService.GenerateContent.""" + + sdk_http_response: Optional[HttpResponseDict] + """Used to retain the full HTTP response.""" + + candidates: Optional[list[CandidateDict]] + """Response variations returned by the model. + """ + + create_time: Optional[datetime.datetime] + """Timestamp when the request is made to the server. + """ + + model_version: Optional[str] + """Output only. The model version used to generate the response.""" + + prompt_feedback: Optional[GenerateContentResponsePromptFeedbackDict] + """Output only. Content filter results for a prompt sent in the request. Note: Sent only in the first stream chunk. Only happens when no candidates were generated due to content violations.""" + + response_id: Optional[str] + """Output only. response_id is used to identify each response. It is the encoding of the event_id.""" + + usage_metadata: Optional[GenerateContentResponseUsageMetadataDict] + """Usage metadata about the response(s).""" + + model_status: Optional[ModelStatusDict] + """Output only. The current model status of this model. This field is not supported in Vertex AI.""" + + +GenerateContentResponseOrDict = Union[ + GenerateContentResponse, GenerateContentResponseDict +] + + +class EmbedContentConfig(_common.BaseModel): + """Optional parameters for the embed_content method.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + task_type: Optional[str] = Field( + default=None, + description="""Type of task for which the embedding will be used. + """, + ) + title: Optional[str] = Field( + default=None, + description="""Title for the text. Only applicable when TaskType is + `RETRIEVAL_DOCUMENT`. + """, + ) + output_dimensionality: Optional[int] = Field( + default=None, + description="""Reduced dimension for the output embedding. If set, + excessive values in the output embedding are truncated from the end. + Supported by newer models since 2024 only. You cannot set this value if + using the earlier model (`models/embedding-001`). + """, + ) + mime_type: Optional[str] = Field( + default=None, + description="""Vertex API only. The MIME type of the input. + """, + ) + auto_truncate: Optional[bool] = Field( + default=None, + description="""Vertex API only. Whether to silently truncate inputs longer than + the max sequence length. If this option is set to false, oversized inputs + will lead to an INVALID_ARGUMENT error, similar to other text APIs. + """, + ) + document_ocr: Optional[bool] = Field( + default=None, + description="""Vertex API only. Whether to enable OCR for document content. + Only applicable to Gemini Embedding 2 models. + """, + ) + audio_track_extraction: Optional[bool] = Field( + default=None, + description="""Vertex API only. Whether to extract audio from video content. + Only applicable to Gemini Embedding 2 models. + """, + ) + + +class EmbedContentConfigDict(TypedDict, total=False): + """Optional parameters for the embed_content method.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + task_type: Optional[str] + """Type of task for which the embedding will be used. + """ + + title: Optional[str] + """Title for the text. Only applicable when TaskType is + `RETRIEVAL_DOCUMENT`. + """ + + output_dimensionality: Optional[int] + """Reduced dimension for the output embedding. If set, + excessive values in the output embedding are truncated from the end. + Supported by newer models since 2024 only. You cannot set this value if + using the earlier model (`models/embedding-001`). + """ + + mime_type: Optional[str] + """Vertex API only. The MIME type of the input. + """ + + auto_truncate: Optional[bool] + """Vertex API only. Whether to silently truncate inputs longer than + the max sequence length. If this option is set to false, oversized inputs + will lead to an INVALID_ARGUMENT error, similar to other text APIs. + """ + + document_ocr: Optional[bool] + """Vertex API only. Whether to enable OCR for document content. + Only applicable to Gemini Embedding 2 models. + """ + + audio_track_extraction: Optional[bool] + """Vertex API only. Whether to extract audio from video content. + Only applicable to Gemini Embedding 2 models. + """ + + +EmbedContentConfigOrDict = Union[EmbedContentConfig, EmbedContentConfigDict] + + +class _EmbedContentParametersPrivate(_common.BaseModel): + """Parameters for the _embed_content method.""" + + model: Optional[str] = Field( + default=None, + description="""ID of the model to use. For a list of models, see `Google models + `_.""", + ) + contents: Optional[ContentListUnion] = Field( + default=None, + description="""The content to embed. Only the `parts.text` fields will be counted. + """, + ) + content: Optional[ContentUnion] = Field( + default=None, + description="""The single content to embed. Only the `parts.text` fields will be counted. + """, + ) + embedding_api_type: Optional[EmbeddingApiType] = Field( + default=None, + description="""The Vertex embedding API to use. + """, + ) + config: Optional[EmbedContentConfig] = Field( + default=None, + description="""Configuration that contains optional parameters. + """, + ) + + +class _EmbedContentParametersPrivateDict(TypedDict, total=False): + """Parameters for the _embed_content method.""" + + model: Optional[str] + """ID of the model to use. For a list of models, see `Google models + `_.""" + + contents: Optional[ContentListUnionDict] + """The content to embed. Only the `parts.text` fields will be counted. + """ + + content: Optional[ContentUnionDict] + """The single content to embed. Only the `parts.text` fields will be counted. + """ + + embedding_api_type: Optional[EmbeddingApiType] + """The Vertex embedding API to use. + """ + + config: Optional[EmbedContentConfigDict] + """Configuration that contains optional parameters. + """ + + +_EmbedContentParametersPrivateOrDict = Union[ + _EmbedContentParametersPrivate, _EmbedContentParametersPrivateDict +] + + +class ContentEmbeddingStatistics(_common.BaseModel): + """Statistics of the input text associated with the result of content embedding.""" + + truncated: Optional[bool] = Field( + default=None, + description="""Vertex API only. If the input text was truncated due to having + a length longer than the allowed maximum input. + """, + ) + token_count: Optional[float] = Field( + default=None, + description="""Vertex API only. Number of tokens of the input text. + """, + ) + + +class ContentEmbeddingStatisticsDict(TypedDict, total=False): + """Statistics of the input text associated with the result of content embedding.""" + + truncated: Optional[bool] + """Vertex API only. If the input text was truncated due to having + a length longer than the allowed maximum input. + """ + + token_count: Optional[float] + """Vertex API only. Number of tokens of the input text. + """ + + +ContentEmbeddingStatisticsOrDict = Union[ + ContentEmbeddingStatistics, ContentEmbeddingStatisticsDict +] + + +class ContentEmbedding(_common.BaseModel): + """The embedding generated from an input content.""" + + values: Optional[list[float]] = Field( + default=None, + description="""A list of floats representing an embedding. + """, + ) + statistics: Optional[ContentEmbeddingStatistics] = Field( + default=None, + description="""Vertex API only. Statistics of the input text associated with this + embedding. + """, + ) + + +class ContentEmbeddingDict(TypedDict, total=False): + """The embedding generated from an input content.""" + + values: Optional[list[float]] + """A list of floats representing an embedding. + """ + + statistics: Optional[ContentEmbeddingStatisticsDict] + """Vertex API only. Statistics of the input text associated with this + embedding. + """ + + +ContentEmbeddingOrDict = Union[ContentEmbedding, ContentEmbeddingDict] + + +class EmbedContentMetadata(_common.BaseModel): + """Request-level metadata for the Vertex Embed Content API.""" + + billable_character_count: Optional[int] = Field( + default=None, + description="""Vertex API only. The total number of billable characters included + in the request. + """, + ) + + +class EmbedContentMetadataDict(TypedDict, total=False): + """Request-level metadata for the Vertex Embed Content API.""" + + billable_character_count: Optional[int] + """Vertex API only. The total number of billable characters included + in the request. + """ + + +EmbedContentMetadataOrDict = Union[ + EmbedContentMetadata, EmbedContentMetadataDict +] + + +class EmbedContentResponse(_common.BaseModel): + """Response for the embed_content method.""" + + sdk_http_response: Optional[HttpResponse] = Field( + default=None, description="""Used to retain the full HTTP response.""" + ) + embeddings: Optional[list[ContentEmbedding]] = Field( + default=None, + description="""The embeddings for each request, in the same order as provided in + the batch request. + """, + ) + metadata: Optional[EmbedContentMetadata] = Field( + default=None, + description="""Vertex API only. Metadata about the request. + """, + ) + + +class EmbedContentResponseDict(TypedDict, total=False): + """Response for the embed_content method.""" + + sdk_http_response: Optional[HttpResponseDict] + """Used to retain the full HTTP response.""" + + embeddings: Optional[list[ContentEmbeddingDict]] + """The embeddings for each request, in the same order as provided in + the batch request. + """ + + metadata: Optional[EmbedContentMetadataDict] + """Vertex API only. Metadata about the request. + """ + + +EmbedContentResponseOrDict = Union[ + EmbedContentResponse, EmbedContentResponseDict +] + + +class GenerateImagesConfig(_common.BaseModel): + """The config for generating an images.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + output_gcs_uri: Optional[str] = Field( + default=None, + description="""Cloud Storage URI used to store the generated images.""", + ) + negative_prompt: Optional[str] = Field( + default=None, + description="""Description of what to discourage in the generated images.""", + ) + number_of_images: Optional[int] = Field( + default=None, description="""Number of images to generate.""" + ) + aspect_ratio: Optional[str] = Field( + default=None, + description="""Aspect ratio of the generated images. Supported values are + "1:1", "3:4", "4:3", "9:16", and "16:9".""", + ) + guidance_scale: Optional[float] = Field( + default=None, + description="""Controls how much the model adheres to the text prompt. Large + values increase output and prompt alignment, but may compromise image + quality.""", + ) + seed: Optional[int] = Field( + default=None, + description="""Random seed for image generation. This is not available when + ``add_watermark`` is set to true.""", + ) + safety_filter_level: Optional[SafetyFilterLevel] = Field( + default=None, description="""Filter level for safety filtering.""" + ) + person_generation: Optional[PersonGeneration] = Field( + default=None, description="""Allows generation of people by the model.""" + ) + include_safety_attributes: Optional[bool] = Field( + default=None, + description="""Whether to report the safety scores of each generated image and + the positive prompt in the response.""", + ) + include_rai_reason: Optional[bool] = Field( + default=None, + description="""Whether to include the Responsible AI filter reason if the image + is filtered out of the response.""", + ) + language: Optional[ImagePromptLanguage] = Field( + default=None, description="""Language of the text in the prompt.""" + ) + output_mime_type: Optional[str] = Field( + default=None, description="""MIME type of the generated image.""" + ) + output_compression_quality: Optional[int] = Field( + default=None, + description="""Compression quality of the generated image (for ``image/jpeg`` + only).""", + ) + add_watermark: Optional[bool] = Field( + default=None, + description="""Whether to add a watermark to the generated images.""", + ) + labels: Optional[dict[str, str]] = Field( + default=None, + description="""User specified labels to track billing usage.""", + ) + image_size: Optional[str] = Field( + default=None, + description="""The size of the largest dimension of the generated image. + Supported sizes are 1K and 2K (not supported for Imagen 3 models).""", + ) + enhance_prompt: Optional[bool] = Field( + default=None, description="""Whether to use the prompt rewriting logic.""" + ) + + +class GenerateImagesConfigDict(TypedDict, total=False): + """The config for generating an images.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + output_gcs_uri: Optional[str] + """Cloud Storage URI used to store the generated images.""" + + negative_prompt: Optional[str] + """Description of what to discourage in the generated images.""" + + number_of_images: Optional[int] + """Number of images to generate.""" + + aspect_ratio: Optional[str] + """Aspect ratio of the generated images. Supported values are + "1:1", "3:4", "4:3", "9:16", and "16:9".""" + + guidance_scale: Optional[float] + """Controls how much the model adheres to the text prompt. Large + values increase output and prompt alignment, but may compromise image + quality.""" + + seed: Optional[int] + """Random seed for image generation. This is not available when + ``add_watermark`` is set to true.""" + + safety_filter_level: Optional[SafetyFilterLevel] + """Filter level for safety filtering.""" + + person_generation: Optional[PersonGeneration] + """Allows generation of people by the model.""" + + include_safety_attributes: Optional[bool] + """Whether to report the safety scores of each generated image and + the positive prompt in the response.""" + + include_rai_reason: Optional[bool] + """Whether to include the Responsible AI filter reason if the image + is filtered out of the response.""" + + language: Optional[ImagePromptLanguage] + """Language of the text in the prompt.""" + + output_mime_type: Optional[str] + """MIME type of the generated image.""" + + output_compression_quality: Optional[int] + """Compression quality of the generated image (for ``image/jpeg`` + only).""" + + add_watermark: Optional[bool] + """Whether to add a watermark to the generated images.""" + + labels: Optional[dict[str, str]] + """User specified labels to track billing usage.""" + + image_size: Optional[str] + """The size of the largest dimension of the generated image. + Supported sizes are 1K and 2K (not supported for Imagen 3 models).""" + + enhance_prompt: Optional[bool] + """Whether to use the prompt rewriting logic.""" + + +GenerateImagesConfigOrDict = Union[ + GenerateImagesConfig, GenerateImagesConfigDict +] + + +class _GenerateImagesParameters(_common.BaseModel): + """The parameters for generating images.""" + + model: Optional[str] = Field( + default=None, + description="""ID of the model to use. For a list of models, see `Google models + `_.""", + ) + prompt: Optional[str] = Field( + default=None, + description="""Text prompt that typically describes the images to output. + """, + ) + config: Optional[GenerateImagesConfig] = Field( + default=None, + description="""Configuration for generating images. + """, + ) + + +class _GenerateImagesParametersDict(TypedDict, total=False): + """The parameters for generating images.""" + + model: Optional[str] + """ID of the model to use. For a list of models, see `Google models + `_.""" + + prompt: Optional[str] + """Text prompt that typically describes the images to output. + """ + + config: Optional[GenerateImagesConfigDict] + """Configuration for generating images. + """ + + +_GenerateImagesParametersOrDict = Union[ + _GenerateImagesParameters, _GenerateImagesParametersDict +] + + +class Image(_common.BaseModel): + """An image.""" + + gcs_uri: Optional[str] = Field( + default=None, + description="""The Cloud Storage URI of the image. ``Image`` can contain a value + for this field or the ``image_bytes`` field but not both.""", + ) + image_bytes: Optional[bytes] = Field( + default=None, + description="""The image bytes data. ``Image`` can contain a value for this field + or the ``gcs_uri`` field but not both.""", + ) + mime_type: Optional[str] = Field( + default=None, description="""The MIME type of the image.""" + ) + + _loaded_image: Optional['PIL_Image'] = None + + """Image.""" + + @classmethod + def from_file( + cls, *, location: str, mime_type: Optional[str] = None + ) -> 'Image': + """Lazy-loads an image from a local file or Google Cloud Storage. + + Args: + location: The local path or Google Cloud Storage URI from which to load + the image. + mime_type: The MIME type of the image. If not provided, the MIME type + will be automatically determined. + + Returns: + A loaded image as an `Image` object. + """ + import urllib + import pathlib + import mimetypes + + parsed_url = urllib.parse.urlparse(location) + if ( + parsed_url.scheme == 'https' + and parsed_url.netloc == 'storage.googleapis.com' + ): + parsed_url = parsed_url._replace( + scheme='gs', + netloc='', + path=f'/{urllib.parse.unquote(parsed_url.path)}', + ) + location = urllib.parse.urlunparse(parsed_url) + + if parsed_url.scheme == 'gs': + return cls(gcs_uri=location) + + # Load image from local path + image_bytes = pathlib.Path(location).read_bytes() + + if not mime_type: + mime_type, _ = mimetypes.guess_type(location) + image = cls(image_bytes=image_bytes, mime_type=mime_type) + return image + + def show(self) -> None: + """Shows the image. + + This method only works in a notebook environment. + """ + in_notebook = 'ipykernel' in sys.modules + if in_notebook: + try: + from IPython import display as IPython_display + except ImportError: + IPython_display = None + + if IPython_display: + IPython_display.display(self._pil_image) + else: + img = self._pil_image + if img is not None: + img.show() + + @property + def _pil_image(self) -> Optional['PIL_Image']: + PIL_Image: Optional[builtin_types.ModuleType] + try: + from PIL import Image as PIL_Image + except ImportError: + PIL_Image = None + import io + + if self._loaded_image is None: + if not PIL_Image: + raise RuntimeError( + 'The PIL module is not available. Please install the Pillow' + ' package. `pip install pillow`' + ) + if self.image_bytes is None: + raise ValueError('The image bytes are not set.') + self._loaded_image = PIL_Image.open(io.BytesIO(self.image_bytes)) + return self._loaded_image + + def save(self, location: str) -> None: + """Saves the image to a file. + + Args: + location: Local path where to save the image. + """ + import pathlib + + if self.image_bytes is None: + raise ValueError('The image bytes are not set.') + pathlib.Path(location).write_bytes(self.image_bytes) + + +JOB_STATES_SUCCEEDED_VERTEX = [ + 'JOB_STATE_SUCCEEDED', +] + +JOB_STATES_SUCCEEDED_MLDEV = [ + 'ACTIVE', +] + +JOB_STATES_SUCCEEDED = JOB_STATES_SUCCEEDED_VERTEX + JOB_STATES_SUCCEEDED_MLDEV + + +JOB_STATES_ENDED_VERTEX = [ + 'JOB_STATE_SUCCEEDED', + 'JOB_STATE_FAILED', + 'JOB_STATE_CANCELLED', + 'JOB_STATE_EXPIRED', +] + +JOB_STATES_ENDED_MLDEV = [ + 'ACTIVE', + 'FAILED', +] + +JOB_STATES_ENDED = JOB_STATES_ENDED_VERTEX + JOB_STATES_ENDED_MLDEV + + +class ImageDict(TypedDict, total=False): + """An image.""" + + gcs_uri: Optional[str] + """The Cloud Storage URI of the image. ``Image`` can contain a value + for this field or the ``image_bytes`` field but not both.""" + + image_bytes: Optional[bytes] + """The image bytes data. ``Image`` can contain a value for this field + or the ``gcs_uri`` field but not both.""" + + mime_type: Optional[str] + """The MIME type of the image.""" + + +ImageOrDict = Union[Image, ImageDict] + + +class SafetyAttributes(_common.BaseModel): + """Safety attributes of a GeneratedImage or the user-provided prompt.""" + + categories: Optional[list[str]] = Field( + default=None, description="""List of RAI categories.""" + ) + scores: Optional[list[float]] = Field( + default=None, description="""List of scores of each categories.""" + ) + content_type: Optional[str] = Field( + default=None, description="""Internal use only.""" + ) + + +class SafetyAttributesDict(TypedDict, total=False): + """Safety attributes of a GeneratedImage or the user-provided prompt.""" + + categories: Optional[list[str]] + """List of RAI categories.""" + + scores: Optional[list[float]] + """List of scores of each categories.""" + + content_type: Optional[str] + """Internal use only.""" + + +SafetyAttributesOrDict = Union[SafetyAttributes, SafetyAttributesDict] + + +class GeneratedImage(_common.BaseModel): + """An output image.""" + + image: Optional[Image] = Field( + default=None, description="""The output image data.""" + ) + rai_filtered_reason: Optional[str] = Field( + default=None, + description="""Responsible AI filter reason if the image is filtered out of the + response.""", + ) + safety_attributes: Optional[SafetyAttributes] = Field( + default=None, + description="""Safety attributes of the image. Lists of RAI categories and their + scores of each content.""", + ) + enhanced_prompt: Optional[str] = Field( + default=None, + description="""The rewritten prompt used for the image generation if the prompt + enhancer is enabled.""", + ) + + +class GeneratedImageDict(TypedDict, total=False): + """An output image.""" + + image: Optional[ImageDict] + """The output image data.""" + + rai_filtered_reason: Optional[str] + """Responsible AI filter reason if the image is filtered out of the + response.""" + + safety_attributes: Optional[SafetyAttributesDict] + """Safety attributes of the image. Lists of RAI categories and their + scores of each content.""" + + enhanced_prompt: Optional[str] + """The rewritten prompt used for the image generation if the prompt + enhancer is enabled.""" + + +GeneratedImageOrDict = Union[GeneratedImage, GeneratedImageDict] + + +class GenerateImagesResponse(_common.BaseModel): + """The output images response.""" + + sdk_http_response: Optional[HttpResponse] = Field( + default=None, description="""Used to retain the full HTTP response.""" + ) + generated_images: Optional[list[GeneratedImage]] = Field( + default=None, description="""List of generated images.""" + ) + positive_prompt_safety_attributes: Optional[SafetyAttributes] = Field( + default=None, + description="""Safety attributes of the positive prompt. Only populated if + ``include_safety_attributes`` is set to True.""", + ) + + @property + def images(self) -> list[Optional[Image]]: + """Returns the list of all generated images. + + A convenience method for accessing the images. Some attributes of the + generated image are only available through the ``GeneratedImage`` object. + """ + if not self.generated_images: + return [] + return [generated_image.image for generated_image in self.generated_images] + + +class GenerateImagesResponseDict(TypedDict, total=False): + """The output images response.""" + + sdk_http_response: Optional[HttpResponseDict] + """Used to retain the full HTTP response.""" + + generated_images: Optional[list[GeneratedImageDict]] + """List of generated images.""" + + positive_prompt_safety_attributes: Optional[SafetyAttributesDict] + """Safety attributes of the positive prompt. Only populated if + ``include_safety_attributes`` is set to True.""" + + +GenerateImagesResponseOrDict = Union[ + GenerateImagesResponse, GenerateImagesResponseDict +] + + +class MaskReferenceConfig(_common.BaseModel): + """Configuration for a Mask reference image.""" + + mask_mode: Optional[MaskReferenceMode] = Field( + default=None, + description="""Prompts the model to generate a mask instead of you needing to + provide one (unless MASK_MODE_USER_PROVIDED is used).""", + ) + segmentation_classes: Optional[list[int]] = Field( + default=None, + description="""A list of up to 5 class ids to use for semantic segmentation. + Automatically creates an image mask based on specific objects.""", + ) + mask_dilation: Optional[float] = Field( + default=None, + description="""Dilation percentage of the mask provided. + Float between 0 and 1.""", + ) + + +class MaskReferenceConfigDict(TypedDict, total=False): + """Configuration for a Mask reference image.""" + + mask_mode: Optional[MaskReferenceMode] + """Prompts the model to generate a mask instead of you needing to + provide one (unless MASK_MODE_USER_PROVIDED is used).""" + + segmentation_classes: Optional[list[int]] + """A list of up to 5 class ids to use for semantic segmentation. + Automatically creates an image mask based on specific objects.""" + + mask_dilation: Optional[float] + """Dilation percentage of the mask provided. + Float between 0 and 1.""" + + +MaskReferenceConfigOrDict = Union[MaskReferenceConfig, MaskReferenceConfigDict] + + +class ControlReferenceConfig(_common.BaseModel): + """Configuration for a Control reference image.""" + + control_type: Optional[ControlReferenceType] = Field( + default=None, + description="""The type of control reference image to use.""", + ) + enable_control_image_computation: Optional[bool] = Field( + default=None, + description="""Defaults to False. When set to True, the control image will be + computed by the model based on the control type. When set to False, + the control image must be provided by the user.""", + ) + + +class ControlReferenceConfigDict(TypedDict, total=False): + """Configuration for a Control reference image.""" + + control_type: Optional[ControlReferenceType] + """The type of control reference image to use.""" + + enable_control_image_computation: Optional[bool] + """Defaults to False. When set to True, the control image will be + computed by the model based on the control type. When set to False, + the control image must be provided by the user.""" + + +ControlReferenceConfigOrDict = Union[ + ControlReferenceConfig, ControlReferenceConfigDict +] + + +class StyleReferenceConfig(_common.BaseModel): + """Configuration for a Style reference image.""" + + style_description: Optional[str] = Field( + default=None, + description="""A text description of the style to use for the generated image.""", + ) + + +class StyleReferenceConfigDict(TypedDict, total=False): + """Configuration for a Style reference image.""" + + style_description: Optional[str] + """A text description of the style to use for the generated image.""" + + +StyleReferenceConfigOrDict = Union[ + StyleReferenceConfig, StyleReferenceConfigDict +] + + +class SubjectReferenceConfig(_common.BaseModel): + """Configuration for a Subject reference image.""" + + subject_type: Optional[SubjectReferenceType] = Field( + default=None, + description="""The subject type of a subject reference image.""", + ) + subject_description: Optional[str] = Field( + default=None, description="""Subject description for the image.""" + ) + + +class SubjectReferenceConfigDict(TypedDict, total=False): + """Configuration for a Subject reference image.""" + + subject_type: Optional[SubjectReferenceType] + """The subject type of a subject reference image.""" + + subject_description: Optional[str] + """Subject description for the image.""" + + +SubjectReferenceConfigOrDict = Union[ + SubjectReferenceConfig, SubjectReferenceConfigDict +] + + +class _ReferenceImageAPI(_common.BaseModel): + """Private class that represents a Reference image that is sent to API.""" + + reference_image: Optional[Image] = Field( + default=None, + description="""The reference image for the editing operation.""", + ) + reference_id: Optional[int] = Field( + default=None, description="""The id of the reference image.""" + ) + reference_type: Optional[str] = Field( + default=None, + description="""The type of the reference image. Only set by the SDK.""", + ) + mask_image_config: Optional[MaskReferenceConfig] = Field( + default=None, + description="""Configuration for the mask reference image.""", + ) + control_image_config: Optional[ControlReferenceConfig] = Field( + default=None, + description="""Configuration for the control reference image.""", + ) + style_image_config: Optional[StyleReferenceConfig] = Field( + default=None, + description="""Configuration for the style reference image.""", + ) + subject_image_config: Optional[SubjectReferenceConfig] = Field( + default=None, + description="""Configuration for the subject reference image.""", + ) + + +class _ReferenceImageAPIDict(TypedDict, total=False): + """Private class that represents a Reference image that is sent to API.""" + + reference_image: Optional[ImageDict] + """The reference image for the editing operation.""" + + reference_id: Optional[int] + """The id of the reference image.""" + + reference_type: Optional[str] + """The type of the reference image. Only set by the SDK.""" + + mask_image_config: Optional[MaskReferenceConfigDict] + """Configuration for the mask reference image.""" + + control_image_config: Optional[ControlReferenceConfigDict] + """Configuration for the control reference image.""" + + style_image_config: Optional[StyleReferenceConfigDict] + """Configuration for the style reference image.""" + + subject_image_config: Optional[SubjectReferenceConfigDict] + """Configuration for the subject reference image.""" + + +_ReferenceImageAPIOrDict = Union[_ReferenceImageAPI, _ReferenceImageAPIDict] + + +class EditImageConfig(_common.BaseModel): + """Configuration for editing an image.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + output_gcs_uri: Optional[str] = Field( + default=None, + description="""Cloud Storage URI used to store the generated images.""", + ) + negative_prompt: Optional[str] = Field( + default=None, + description="""Description of what to discourage in the generated images.""", + ) + number_of_images: Optional[int] = Field( + default=None, description="""Number of images to generate.""" + ) + aspect_ratio: Optional[str] = Field( + default=None, + description="""Aspect ratio of the generated images. Supported values are + "1:1", "3:4", "4:3", "9:16", and "16:9".""", + ) + guidance_scale: Optional[float] = Field( + default=None, + description="""Controls how much the model adheres to the text prompt. Large + values increase output and prompt alignment, but may compromise image + quality.""", + ) + seed: Optional[int] = Field( + default=None, + description="""Random seed for image generation. This is not available when + ``add_watermark`` is set to true.""", + ) + safety_filter_level: Optional[SafetyFilterLevel] = Field( + default=None, description="""Filter level for safety filtering.""" + ) + person_generation: Optional[PersonGeneration] = Field( + default=None, description="""Allows generation of people by the model.""" + ) + include_safety_attributes: Optional[bool] = Field( + default=None, + description="""Whether to report the safety scores of each generated image and + the positive prompt in the response.""", + ) + include_rai_reason: Optional[bool] = Field( + default=None, + description="""Whether to include the Responsible AI filter reason if the image + is filtered out of the response.""", + ) + language: Optional[ImagePromptLanguage] = Field( + default=None, description="""Language of the text in the prompt.""" + ) + output_mime_type: Optional[str] = Field( + default=None, description="""MIME type of the generated image.""" + ) + output_compression_quality: Optional[int] = Field( + default=None, + description="""Compression quality of the generated image (for ``image/jpeg`` + only).""", + ) + add_watermark: Optional[bool] = Field( + default=None, + description="""Whether to add a watermark to the generated images.""", + ) + labels: Optional[dict[str, str]] = Field( + default=None, + description="""User specified labels to track billing usage.""", + ) + edit_mode: Optional[EditMode] = Field( + default=None, + description="""Describes the editing mode for the request.""", + ) + base_steps: Optional[int] = Field( + default=None, + description="""The number of sampling steps. A higher value has better image + quality, while a lower value has better latency.""", + ) + + +class EditImageConfigDict(TypedDict, total=False): + """Configuration for editing an image.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + output_gcs_uri: Optional[str] + """Cloud Storage URI used to store the generated images.""" + + negative_prompt: Optional[str] + """Description of what to discourage in the generated images.""" + + number_of_images: Optional[int] + """Number of images to generate.""" + + aspect_ratio: Optional[str] + """Aspect ratio of the generated images. Supported values are + "1:1", "3:4", "4:3", "9:16", and "16:9".""" + + guidance_scale: Optional[float] + """Controls how much the model adheres to the text prompt. Large + values increase output and prompt alignment, but may compromise image + quality.""" + + seed: Optional[int] + """Random seed for image generation. This is not available when + ``add_watermark`` is set to true.""" + + safety_filter_level: Optional[SafetyFilterLevel] + """Filter level for safety filtering.""" + + person_generation: Optional[PersonGeneration] + """Allows generation of people by the model.""" + + include_safety_attributes: Optional[bool] + """Whether to report the safety scores of each generated image and + the positive prompt in the response.""" + + include_rai_reason: Optional[bool] + """Whether to include the Responsible AI filter reason if the image + is filtered out of the response.""" + + language: Optional[ImagePromptLanguage] + """Language of the text in the prompt.""" + + output_mime_type: Optional[str] + """MIME type of the generated image.""" + + output_compression_quality: Optional[int] + """Compression quality of the generated image (for ``image/jpeg`` + only).""" + + add_watermark: Optional[bool] + """Whether to add a watermark to the generated images.""" + + labels: Optional[dict[str, str]] + """User specified labels to track billing usage.""" + + edit_mode: Optional[EditMode] + """Describes the editing mode for the request.""" + + base_steps: Optional[int] + """The number of sampling steps. A higher value has better image + quality, while a lower value has better latency.""" + + +EditImageConfigOrDict = Union[EditImageConfig, EditImageConfigDict] + + +class _EditImageParameters(_common.BaseModel): + """Parameters for the request to edit an image.""" + + model: Optional[str] = Field( + default=None, description="""The model to use.""" + ) + prompt: Optional[str] = Field( + default=None, + description="""A text description of the edit to apply to the image.""", + ) + reference_images: Optional[list[_ReferenceImageAPI]] = Field( + default=None, description="""The reference images for editing.""" + ) + config: Optional[EditImageConfig] = Field( + default=None, description="""Configuration for editing.""" + ) + + +class _EditImageParametersDict(TypedDict, total=False): + """Parameters for the request to edit an image.""" + + model: Optional[str] + """The model to use.""" + + prompt: Optional[str] + """A text description of the edit to apply to the image.""" + + reference_images: Optional[list[_ReferenceImageAPIDict]] + """The reference images for editing.""" + + config: Optional[EditImageConfigDict] + """Configuration for editing.""" + + +_EditImageParametersOrDict = Union[ + _EditImageParameters, _EditImageParametersDict +] + + +class EditImageResponse(_common.BaseModel): + """Response for the request to edit an image.""" + + sdk_http_response: Optional[HttpResponse] = Field( + default=None, description="""Used to retain the full HTTP response.""" + ) + generated_images: Optional[list[GeneratedImage]] = Field( + default=None, description="""Generated images.""" + ) + + +class EditImageResponseDict(TypedDict, total=False): + """Response for the request to edit an image.""" + + sdk_http_response: Optional[HttpResponseDict] + """Used to retain the full HTTP response.""" + + generated_images: Optional[list[GeneratedImageDict]] + """Generated images.""" + + +EditImageResponseOrDict = Union[EditImageResponse, EditImageResponseDict] + + +class _UpscaleImageAPIConfig(_common.BaseModel): + """Internal API config for UpscaleImage. + + These fields require default values sent to the API which are not intended + to be modifiable or exposed to users in the SDK method. + """ + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + output_gcs_uri: Optional[str] = Field( + default=None, + description="""Cloud Storage URI used to store the generated images.""", + ) + safety_filter_level: Optional[SafetyFilterLevel] = Field( + default=None, description="""Filter level for safety filtering.""" + ) + person_generation: Optional[PersonGeneration] = Field( + default=None, description="""Allows generation of people by the model.""" + ) + include_rai_reason: Optional[bool] = Field( + default=None, + description="""Whether to include a reason for filtered-out images in the + response.""", + ) + output_mime_type: Optional[str] = Field( + default=None, + description="""The image format that the output should be saved as.""", + ) + output_compression_quality: Optional[int] = Field( + default=None, + description="""The level of compression. Only applicable if the + ``output_mime_type`` is ``image/jpeg``.""", + ) + enhance_input_image: Optional[bool] = Field( + default=None, + description="""Whether to add an image enhancing step before upscaling. + It is expected to suppress the noise and JPEG compression artifacts + from the input image.""", + ) + image_preservation_factor: Optional[float] = Field( + default=None, + description="""With a higher image preservation factor, the original image + pixels are more respected. With a lower image preservation factor, the + output image will have be more different from the input image, but + with finer details and less noise.""", + ) + labels: Optional[dict[str, str]] = Field( + default=None, + description="""User specified labels to track billing usage.""", + ) + number_of_images: Optional[int] = Field(default=None, description="""""") + mode: Optional[str] = Field(default=None, description="""""") + + +class _UpscaleImageAPIConfigDict(TypedDict, total=False): + """Internal API config for UpscaleImage. + + These fields require default values sent to the API which are not intended + to be modifiable or exposed to users in the SDK method. + """ + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + output_gcs_uri: Optional[str] + """Cloud Storage URI used to store the generated images.""" + + safety_filter_level: Optional[SafetyFilterLevel] + """Filter level for safety filtering.""" + + person_generation: Optional[PersonGeneration] + """Allows generation of people by the model.""" + + include_rai_reason: Optional[bool] + """Whether to include a reason for filtered-out images in the + response.""" + + output_mime_type: Optional[str] + """The image format that the output should be saved as.""" + + output_compression_quality: Optional[int] + """The level of compression. Only applicable if the + ``output_mime_type`` is ``image/jpeg``.""" + + enhance_input_image: Optional[bool] + """Whether to add an image enhancing step before upscaling. + It is expected to suppress the noise and JPEG compression artifacts + from the input image.""" + + image_preservation_factor: Optional[float] + """With a higher image preservation factor, the original image + pixels are more respected. With a lower image preservation factor, the + output image will have be more different from the input image, but + with finer details and less noise.""" + + labels: Optional[dict[str, str]] + """User specified labels to track billing usage.""" + + number_of_images: Optional[int] + """""" + + mode: Optional[str] + """""" + + +_UpscaleImageAPIConfigOrDict = Union[ + _UpscaleImageAPIConfig, _UpscaleImageAPIConfigDict +] + + +class _UpscaleImageAPIParameters(_common.BaseModel): + """API parameters for UpscaleImage.""" + + model: Optional[str] = Field( + default=None, description="""The model to use.""" + ) + image: Optional[Image] = Field( + default=None, description="""The input image to upscale.""" + ) + upscale_factor: Optional[str] = Field( + default=None, + description="""The factor to upscale the image (x2 or x4).""", + ) + config: Optional[_UpscaleImageAPIConfig] = Field( + default=None, description="""Configuration for upscaling.""" + ) + + +class _UpscaleImageAPIParametersDict(TypedDict, total=False): + """API parameters for UpscaleImage.""" + + model: Optional[str] + """The model to use.""" + + image: Optional[ImageDict] + """The input image to upscale.""" + + upscale_factor: Optional[str] + """The factor to upscale the image (x2 or x4).""" + + config: Optional[_UpscaleImageAPIConfigDict] + """Configuration for upscaling.""" + + +_UpscaleImageAPIParametersOrDict = Union[ + _UpscaleImageAPIParameters, _UpscaleImageAPIParametersDict +] + + +class UpscaleImageResponse(_common.BaseModel): + + sdk_http_response: Optional[HttpResponse] = Field( + default=None, description="""Used to retain the full HTTP response.""" + ) + generated_images: Optional[list[GeneratedImage]] = Field( + default=None, description="""Generated images.""" + ) + + +class UpscaleImageResponseDict(TypedDict, total=False): + + sdk_http_response: Optional[HttpResponseDict] + """Used to retain the full HTTP response.""" + + generated_images: Optional[list[GeneratedImageDict]] + """Generated images.""" + + +UpscaleImageResponseOrDict = Union[ + UpscaleImageResponse, UpscaleImageResponseDict +] + + +class ProductImage(_common.BaseModel): + """An image of the product.""" + + product_image: Optional[Image] = Field( + default=None, + description="""An image of the product to be recontextualized.""", + ) + + +class ProductImageDict(TypedDict, total=False): + """An image of the product.""" + + product_image: Optional[ImageDict] + """An image of the product to be recontextualized.""" + + +ProductImageOrDict = Union[ProductImage, ProductImageDict] + + +class RecontextImageSource(_common.BaseModel): + """A set of source input(s) for image recontextualization.""" + + prompt: Optional[str] = Field( + default=None, + description="""A text prompt for guiding the model during image + recontextualization. Not supported for Virtual Try-On.""", + ) + person_image: Optional[Image] = Field( + default=None, + description="""Image of the person or subject who will be wearing the + product(s).""", + ) + product_images: Optional[list[ProductImage]] = Field( + default=None, description="""A list of product images.""" + ) + + +class RecontextImageSourceDict(TypedDict, total=False): + """A set of source input(s) for image recontextualization.""" + + prompt: Optional[str] + """A text prompt for guiding the model during image + recontextualization. Not supported for Virtual Try-On.""" + + person_image: Optional[ImageDict] + """Image of the person or subject who will be wearing the + product(s).""" + + product_images: Optional[list[ProductImageDict]] + """A list of product images.""" + + +RecontextImageSourceOrDict = Union[ + RecontextImageSource, RecontextImageSourceDict +] + + +class RecontextImageConfig(_common.BaseModel): + """Configuration for recontextualizing an image.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + number_of_images: Optional[int] = Field( + default=None, description="""Number of images to generate.""" + ) + base_steps: Optional[int] = Field( + default=None, + description="""The number of sampling steps. A higher value has better image + quality, while a lower value has better latency.""", + ) + output_gcs_uri: Optional[str] = Field( + default=None, + description="""Cloud Storage URI used to store the generated images.""", + ) + seed: Optional[int] = Field( + default=None, description="""Random seed for image generation.""" + ) + safety_filter_level: Optional[SafetyFilterLevel] = Field( + default=None, description="""Filter level for safety filtering.""" + ) + person_generation: Optional[PersonGeneration] = Field( + default=None, + description="""Whether allow to generate person images, and restrict to specific + ages.""", + ) + add_watermark: Optional[bool] = Field( + default=None, + description="""Whether to add a SynthID watermark to the generated images.""", + ) + output_mime_type: Optional[str] = Field( + default=None, description="""MIME type of the generated image.""" + ) + output_compression_quality: Optional[int] = Field( + default=None, + description="""Compression quality of the generated image (for ``image/jpeg`` + only).""", + ) + enhance_prompt: Optional[bool] = Field( + default=None, description="""Whether to use the prompt rewriting logic.""" + ) + labels: Optional[dict[str, str]] = Field( + default=None, + description="""User specified labels to track billing usage.""", + ) + + +class RecontextImageConfigDict(TypedDict, total=False): + """Configuration for recontextualizing an image.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + number_of_images: Optional[int] + """Number of images to generate.""" + + base_steps: Optional[int] + """The number of sampling steps. A higher value has better image + quality, while a lower value has better latency.""" + + output_gcs_uri: Optional[str] + """Cloud Storage URI used to store the generated images.""" + + seed: Optional[int] + """Random seed for image generation.""" + + safety_filter_level: Optional[SafetyFilterLevel] + """Filter level for safety filtering.""" + + person_generation: Optional[PersonGeneration] + """Whether allow to generate person images, and restrict to specific + ages.""" + + add_watermark: Optional[bool] + """Whether to add a SynthID watermark to the generated images.""" + + output_mime_type: Optional[str] + """MIME type of the generated image.""" + + output_compression_quality: Optional[int] + """Compression quality of the generated image (for ``image/jpeg`` + only).""" + + enhance_prompt: Optional[bool] + """Whether to use the prompt rewriting logic.""" + + labels: Optional[dict[str, str]] + """User specified labels to track billing usage.""" + + +RecontextImageConfigOrDict = Union[ + RecontextImageConfig, RecontextImageConfigDict +] + + +class _RecontextImageParameters(_common.BaseModel): + """The parameters for recontextualizing an image.""" + + model: Optional[str] = Field( + default=None, + description="""ID of the model to use. For a list of models, see `Google models + `_.""", + ) + source: Optional[RecontextImageSource] = Field( + default=None, + description="""A set of source input(s) for image recontextualization.""", + ) + config: Optional[RecontextImageConfig] = Field( + default=None, + description="""Configuration for image recontextualization.""", + ) + + +class _RecontextImageParametersDict(TypedDict, total=False): + """The parameters for recontextualizing an image.""" + + model: Optional[str] + """ID of the model to use. For a list of models, see `Google models + `_.""" + + source: Optional[RecontextImageSourceDict] + """A set of source input(s) for image recontextualization.""" + + config: Optional[RecontextImageConfigDict] + """Configuration for image recontextualization.""" + + +_RecontextImageParametersOrDict = Union[ + _RecontextImageParameters, _RecontextImageParametersDict +] + + +class RecontextImageResponse(_common.BaseModel): + """The output images response.""" + + generated_images: Optional[list[GeneratedImage]] = Field( + default=None, description="""List of generated images.""" + ) + + +class RecontextImageResponseDict(TypedDict, total=False): + """The output images response.""" + + generated_images: Optional[list[GeneratedImageDict]] + """List of generated images.""" + + +RecontextImageResponseOrDict = Union[ + RecontextImageResponse, RecontextImageResponseDict +] + + +class ScribbleImage(_common.BaseModel): + """An image mask representing a brush scribble.""" + + image: Optional[Image] = Field( + default=None, + description="""The brush scribble to guide segmentation. Valid for the interactive mode.""", + ) + + +class ScribbleImageDict(TypedDict, total=False): + """An image mask representing a brush scribble.""" + + image: Optional[ImageDict] + """The brush scribble to guide segmentation. Valid for the interactive mode.""" + + +ScribbleImageOrDict = Union[ScribbleImage, ScribbleImageDict] + + +class SegmentImageSource(_common.BaseModel): + """A set of source input(s) for image segmentation.""" + + prompt: Optional[str] = Field( + default=None, + description="""A text prompt for guiding the model during image segmentation. + Required for prompt mode and semantic mode, disallowed for other modes.""", + ) + image: Optional[Image] = Field( + default=None, description="""The image to be segmented.""" + ) + scribble_image: Optional[ScribbleImage] = Field( + default=None, + description="""The brush scribble to guide segmentation. + Required for the interactive mode, disallowed for other modes.""", + ) + + +class SegmentImageSourceDict(TypedDict, total=False): + """A set of source input(s) for image segmentation.""" + + prompt: Optional[str] + """A text prompt for guiding the model during image segmentation. + Required for prompt mode and semantic mode, disallowed for other modes.""" + + image: Optional[ImageDict] + """The image to be segmented.""" + + scribble_image: Optional[ScribbleImageDict] + """The brush scribble to guide segmentation. + Required for the interactive mode, disallowed for other modes.""" + + +SegmentImageSourceOrDict = Union[SegmentImageSource, SegmentImageSourceDict] + + +class SegmentImageConfig(_common.BaseModel): + """Configuration for segmenting an image.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + mode: Optional[SegmentMode] = Field( + default=None, description="""The segmentation mode to use.""" + ) + max_predictions: Optional[int] = Field( + default=None, + description="""The maximum number of predictions to return up to, by top + confidence score.""", + ) + confidence_threshold: Optional[float] = Field( + default=None, + description="""The confidence score threshold for the detections as a decimal + value. Only predictions with a confidence score higher than this + threshold will be returned.""", + ) + mask_dilation: Optional[float] = Field( + default=None, + description="""A decimal value representing how much dilation to apply to the + masks. 0 for no dilation. 1.0 means the masked area covers the whole + image.""", + ) + binary_color_threshold: Optional[float] = Field( + default=None, + description="""The binary color threshold to apply to the masks. The threshold + can be set to a decimal value between 0 and 255 non-inclusive. + Set to -1 for no binary color thresholding.""", + ) + labels: Optional[dict[str, str]] = Field( + default=None, + description="""User specified labels to track billing usage.""", + ) + + +class SegmentImageConfigDict(TypedDict, total=False): + """Configuration for segmenting an image.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + mode: Optional[SegmentMode] + """The segmentation mode to use.""" + + max_predictions: Optional[int] + """The maximum number of predictions to return up to, by top + confidence score.""" + + confidence_threshold: Optional[float] + """The confidence score threshold for the detections as a decimal + value. Only predictions with a confidence score higher than this + threshold will be returned.""" + + mask_dilation: Optional[float] + """A decimal value representing how much dilation to apply to the + masks. 0 for no dilation. 1.0 means the masked area covers the whole + image.""" + + binary_color_threshold: Optional[float] + """The binary color threshold to apply to the masks. The threshold + can be set to a decimal value between 0 and 255 non-inclusive. + Set to -1 for no binary color thresholding.""" + + labels: Optional[dict[str, str]] + """User specified labels to track billing usage.""" + + +SegmentImageConfigOrDict = Union[SegmentImageConfig, SegmentImageConfigDict] + + +class _SegmentImageParameters(_common.BaseModel): + """The parameters for segmenting an image.""" + + model: Optional[str] = Field( + default=None, + description="""ID of the model to use. For a list of models, see `Google models + `_.""", + ) + source: Optional[SegmentImageSource] = Field( + default=None, + description="""A set of source input(s) for image segmentation.""", + ) + config: Optional[SegmentImageConfig] = Field( + default=None, description="""Configuration for image segmentation.""" + ) + + +class _SegmentImageParametersDict(TypedDict, total=False): + """The parameters for segmenting an image.""" + + model: Optional[str] + """ID of the model to use. For a list of models, see `Google models + `_.""" + + source: Optional[SegmentImageSourceDict] + """A set of source input(s) for image segmentation.""" + + config: Optional[SegmentImageConfigDict] + """Configuration for image segmentation.""" + + +_SegmentImageParametersOrDict = Union[ + _SegmentImageParameters, _SegmentImageParametersDict +] + + +class EntityLabel(_common.BaseModel): + """An entity representing the segmented area.""" + + label: Optional[str] = Field( + default=None, description="""The label of the segmented entity.""" + ) + score: Optional[float] = Field( + default=None, + description="""The confidence score of the detected label.""", + ) + + +class EntityLabelDict(TypedDict, total=False): + """An entity representing the segmented area.""" + + label: Optional[str] + """The label of the segmented entity.""" + + score: Optional[float] + """The confidence score of the detected label.""" + + +EntityLabelOrDict = Union[EntityLabel, EntityLabelDict] + + +class GeneratedImageMask(_common.BaseModel): + """A generated image mask.""" + + mask: Optional[Image] = Field( + default=None, description="""The generated image mask.""" + ) + labels: Optional[list[EntityLabel]] = Field( + default=None, + description="""The detected entities on the segmented area.""", + ) + + +class GeneratedImageMaskDict(TypedDict, total=False): + """A generated image mask.""" + + mask: Optional[ImageDict] + """The generated image mask.""" + + labels: Optional[list[EntityLabelDict]] + """The detected entities on the segmented area.""" + + +GeneratedImageMaskOrDict = Union[GeneratedImageMask, GeneratedImageMaskDict] + + +class SegmentImageResponse(_common.BaseModel): + """The output images response.""" + + generated_masks: Optional[list[GeneratedImageMask]] = Field( + default=None, + description="""List of generated image masks. + """, + ) + + +class SegmentImageResponseDict(TypedDict, total=False): + """The output images response.""" + + generated_masks: Optional[list[GeneratedImageMaskDict]] + """List of generated image masks. + """ + + +SegmentImageResponseOrDict = Union[ + SegmentImageResponse, SegmentImageResponseDict +] + + +class GetModelConfig(_common.BaseModel): + """Optional parameters for models.get method.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + + +class GetModelConfigDict(TypedDict, total=False): + """Optional parameters for models.get method.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + +GetModelConfigOrDict = Union[GetModelConfig, GetModelConfigDict] + + +class _GetModelParameters(_common.BaseModel): + + model: Optional[str] = Field(default=None, description="""""") + config: Optional[GetModelConfig] = Field( + default=None, description="""Optional parameters for the request.""" + ) + + +class _GetModelParametersDict(TypedDict, total=False): + + model: Optional[str] + """""" + + config: Optional[GetModelConfigDict] + """Optional parameters for the request.""" + + +_GetModelParametersOrDict = Union[_GetModelParameters, _GetModelParametersDict] + + +class Endpoint(_common.BaseModel): + """An endpoint where you deploy models.""" + + name: Optional[str] = Field( + default=None, description="""Resource name of the endpoint.""" + ) + deployed_model_id: Optional[str] = Field( + default=None, + description="""ID of the model that's deployed to the endpoint.""", + ) + + +class EndpointDict(TypedDict, total=False): + """An endpoint where you deploy models.""" + + name: Optional[str] + """Resource name of the endpoint.""" + + deployed_model_id: Optional[str] + """ID of the model that's deployed to the endpoint.""" + + +EndpointOrDict = Union[Endpoint, EndpointDict] + + +class TunedModelInfo(_common.BaseModel): + """A tuned machine learning model.""" + + base_model: Optional[str] = Field( + default=None, + description="""ID of the base model that you want to tune.""", + ) + create_time: Optional[datetime.datetime] = Field( + default=None, + description="""Date and time when the base model was created.""", + ) + update_time: Optional[datetime.datetime] = Field( + default=None, + description="""Date and time when the base model was last updated.""", + ) + + +class TunedModelInfoDict(TypedDict, total=False): + """A tuned machine learning model.""" + + base_model: Optional[str] + """ID of the base model that you want to tune.""" + + create_time: Optional[datetime.datetime] + """Date and time when the base model was created.""" + + update_time: Optional[datetime.datetime] + """Date and time when the base model was last updated.""" + + +TunedModelInfoOrDict = Union[TunedModelInfo, TunedModelInfoDict] + + +class Checkpoint(_common.BaseModel): + """Describes the machine learning model version checkpoint.""" + + checkpoint_id: Optional[str] = Field( + default=None, + description="""The ID of the checkpoint. + """, + ) + epoch: Optional[int] = Field( + default=None, + description="""The epoch of the checkpoint. + """, + ) + step: Optional[int] = Field( + default=None, + description="""The step of the checkpoint. + """, + ) + + +class CheckpointDict(TypedDict, total=False): + """Describes the machine learning model version checkpoint.""" + + checkpoint_id: Optional[str] + """The ID of the checkpoint. + """ + + epoch: Optional[int] + """The epoch of the checkpoint. + """ + + step: Optional[int] + """The step of the checkpoint. + """ + + +CheckpointOrDict = Union[Checkpoint, CheckpointDict] + + +class Model(_common.BaseModel): + """A trained machine learning model.""" + + name: Optional[str] = Field( + default=None, description="""Resource name of the model.""" + ) + display_name: Optional[str] = Field( + default=None, description="""Display name of the model.""" + ) + description: Optional[str] = Field( + default=None, description="""Description of the model.""" + ) + version: Optional[str] = Field( + default=None, + description="""Version ID of the model. A new version is committed when a new + model version is uploaded or trained under an existing model ID. The + version ID is an auto-incrementing decimal number in string + representation.""", + ) + endpoints: Optional[list[Endpoint]] = Field( + default=None, + description="""List of deployed models created from this base model. Note that a + model could have been deployed to endpoints in different locations.""", + ) + labels: Optional[dict[str, str]] = Field( + default=None, + description="""Labels with user-defined metadata to organize your models.""", + ) + tuned_model_info: Optional[TunedModelInfo] = Field( + default=None, + description="""Information about the tuned model from the base model.""", + ) + input_token_limit: Optional[int] = Field( + default=None, + description="""The maximum number of input tokens that the model can handle.""", + ) + output_token_limit: Optional[int] = Field( + default=None, + description="""The maximum number of output tokens that the model can generate.""", + ) + supported_actions: Optional[list[str]] = Field( + default=None, + description="""List of actions that are supported by the model.""", + ) + default_checkpoint_id: Optional[str] = Field( + default=None, + description="""The default checkpoint id of a model version. + """, + ) + checkpoints: Optional[list[Checkpoint]] = Field( + default=None, description="""The checkpoints of the model.""" + ) + temperature: Optional[float] = Field( + default=None, + description="""Temperature value used for sampling set when the dataset was saved. + This value is used to tune the degree of randomness.""", + ) + max_temperature: Optional[float] = Field( + default=None, + description="""The maximum temperature value used for sampling set when the + dataset was saved. This value is used to tune the degree of randomness.""", + ) + top_p: Optional[float] = Field( + default=None, + description="""Optional. Specifies the nucleus sampling threshold. The model + considers only the smallest set of tokens whose cumulative probability is + at least `top_p`. This helps generate more diverse and less repetitive + responses. For example, a `top_p` of 0.9 means the model considers tokens + until the cumulative probability of the tokens to select from reaches 0.9. + It's recommended to adjust either temperature or `top_p`, but not both.""", + ) + top_k: Optional[int] = Field( + default=None, + description="""Optional. Specifies the top-k sampling threshold. The model + considers only the top k most probable tokens for the next token. This can + be useful for generating more coherent and less random text. For example, + a `top_k` of 40 means the model will choose the next word from the 40 most + likely words.""", + ) + thinking: Optional[bool] = Field( + default=None, + description="""Whether the model supports thinking features. If true, thoughts are + returned only if the model supports thought and thoughts are available.""", + ) + + +class ModelDict(TypedDict, total=False): + """A trained machine learning model.""" + + name: Optional[str] + """Resource name of the model.""" + + display_name: Optional[str] + """Display name of the model.""" + + description: Optional[str] + """Description of the model.""" + + version: Optional[str] + """Version ID of the model. A new version is committed when a new + model version is uploaded or trained under an existing model ID. The + version ID is an auto-incrementing decimal number in string + representation.""" + + endpoints: Optional[list[EndpointDict]] + """List of deployed models created from this base model. Note that a + model could have been deployed to endpoints in different locations.""" + + labels: Optional[dict[str, str]] + """Labels with user-defined metadata to organize your models.""" + + tuned_model_info: Optional[TunedModelInfoDict] + """Information about the tuned model from the base model.""" + + input_token_limit: Optional[int] + """The maximum number of input tokens that the model can handle.""" + + output_token_limit: Optional[int] + """The maximum number of output tokens that the model can generate.""" + + supported_actions: Optional[list[str]] + """List of actions that are supported by the model.""" + + default_checkpoint_id: Optional[str] + """The default checkpoint id of a model version. + """ + + checkpoints: Optional[list[CheckpointDict]] + """The checkpoints of the model.""" + + temperature: Optional[float] + """Temperature value used for sampling set when the dataset was saved. + This value is used to tune the degree of randomness.""" + + max_temperature: Optional[float] + """The maximum temperature value used for sampling set when the + dataset was saved. This value is used to tune the degree of randomness.""" + + top_p: Optional[float] + """Optional. Specifies the nucleus sampling threshold. The model + considers only the smallest set of tokens whose cumulative probability is + at least `top_p`. This helps generate more diverse and less repetitive + responses. For example, a `top_p` of 0.9 means the model considers tokens + until the cumulative probability of the tokens to select from reaches 0.9. + It's recommended to adjust either temperature or `top_p`, but not both.""" + + top_k: Optional[int] + """Optional. Specifies the top-k sampling threshold. The model + considers only the top k most probable tokens for the next token. This can + be useful for generating more coherent and less random text. For example, + a `top_k` of 40 means the model will choose the next word from the 40 most + likely words.""" + + thinking: Optional[bool] + """Whether the model supports thinking features. If true, thoughts are + returned only if the model supports thought and thoughts are available.""" + + +ModelOrDict = Union[Model, ModelDict] + + +class ListModelsConfig(_common.BaseModel): + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + page_size: Optional[int] = Field(default=None, description="""""") + page_token: Optional[str] = Field(default=None, description="""""") + filter: Optional[str] = Field(default=None, description="""""") + query_base: Optional[bool] = Field( + default=None, + description="""Set true to list base models, false to list tuned models.""", + ) + + +class ListModelsConfigDict(TypedDict, total=False): + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + page_size: Optional[int] + """""" + + page_token: Optional[str] + """""" + + filter: Optional[str] + """""" + + query_base: Optional[bool] + """Set true to list base models, false to list tuned models.""" + + +ListModelsConfigOrDict = Union[ListModelsConfig, ListModelsConfigDict] + + +class _ListModelsParameters(_common.BaseModel): + + config: Optional[ListModelsConfig] = Field(default=None, description="""""") + + +class _ListModelsParametersDict(TypedDict, total=False): + + config: Optional[ListModelsConfigDict] + """""" + + +_ListModelsParametersOrDict = Union[ + _ListModelsParameters, _ListModelsParametersDict +] + + +class ListModelsResponse(_common.BaseModel): + + sdk_http_response: Optional[HttpResponse] = Field( + default=None, description="""Used to retain the full HTTP response.""" + ) + next_page_token: Optional[str] = Field(default=None, description="""""") + models: Optional[list[Model]] = Field(default=None, description="""""") + + +class ListModelsResponseDict(TypedDict, total=False): + + sdk_http_response: Optional[HttpResponseDict] + """Used to retain the full HTTP response.""" + + next_page_token: Optional[str] + """""" + + models: Optional[list[ModelDict]] + """""" + + +ListModelsResponseOrDict = Union[ListModelsResponse, ListModelsResponseDict] + + +class UpdateModelConfig(_common.BaseModel): + """Configuration for updating a tuned model.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + display_name: Optional[str] = Field(default=None, description="""""") + description: Optional[str] = Field(default=None, description="""""") + default_checkpoint_id: Optional[str] = Field(default=None, description="""""") + + +class UpdateModelConfigDict(TypedDict, total=False): + """Configuration for updating a tuned model.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + display_name: Optional[str] + """""" + + description: Optional[str] + """""" + + default_checkpoint_id: Optional[str] + """""" + + +UpdateModelConfigOrDict = Union[UpdateModelConfig, UpdateModelConfigDict] + + +class _UpdateModelParameters(_common.BaseModel): + """Configuration for updating a tuned model.""" + + model: Optional[str] = Field(default=None, description="""""") + config: Optional[UpdateModelConfig] = Field(default=None, description="""""") + + +class _UpdateModelParametersDict(TypedDict, total=False): + """Configuration for updating a tuned model.""" + + model: Optional[str] + """""" + + config: Optional[UpdateModelConfigDict] + """""" + + +_UpdateModelParametersOrDict = Union[ + _UpdateModelParameters, _UpdateModelParametersDict +] + + +class DeleteModelConfig(_common.BaseModel): + """Configuration for deleting a tuned model.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + + +class DeleteModelConfigDict(TypedDict, total=False): + """Configuration for deleting a tuned model.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + +DeleteModelConfigOrDict = Union[DeleteModelConfig, DeleteModelConfigDict] + + +class _DeleteModelParameters(_common.BaseModel): + """Parameters for deleting a tuned model.""" + + model: Optional[str] = Field(default=None, description="""""") + config: Optional[DeleteModelConfig] = Field( + default=None, description="""Optional parameters for the request.""" + ) + + +class _DeleteModelParametersDict(TypedDict, total=False): + """Parameters for deleting a tuned model.""" + + model: Optional[str] + """""" + + config: Optional[DeleteModelConfigDict] + """Optional parameters for the request.""" + + +_DeleteModelParametersOrDict = Union[ + _DeleteModelParameters, _DeleteModelParametersDict +] + + +class DeleteModelResponse(_common.BaseModel): + + sdk_http_response: Optional[HttpResponse] = Field( + default=None, description="""Used to retain the full HTTP response.""" + ) + + +class DeleteModelResponseDict(TypedDict, total=False): + + sdk_http_response: Optional[HttpResponseDict] + """Used to retain the full HTTP response.""" + + +DeleteModelResponseOrDict = Union[DeleteModelResponse, DeleteModelResponseDict] + + +class GenerationConfig(_common.BaseModel): + """Generation config.""" + + model_selection_config: Optional[ModelSelectionConfig] = Field( + default=None, description="""Optional. Config for model selection.""" + ) + response_json_schema: Optional[Any] = Field( + default=None, + description="""Output schema of the generated response. This is an alternative to + `response_schema` that accepts [JSON Schema](https://json-schema.org/). + """, + ) + audio_timestamp: Optional[bool] = Field( + default=None, + description="""Optional. If enabled, audio timestamps will be included in the request to the model. This can be useful for synchronizing audio with other modalities in the response. This field is not supported in Gemini API.""", + ) + candidate_count: Optional[int] = Field( + default=None, + description="""Optional. The number of candidate responses to generate. A higher `candidate_count` can provide more options to choose from, but it also consumes more resources. This can be useful for generating a variety of responses and selecting the best one.""", + ) + enable_affective_dialog: Optional[bool] = Field( + default=None, + description="""Optional. If enabled, the model will detect emotions and adapt its responses accordingly. For example, if the model detects that the user is frustrated, it may provide a more empathetic response. This field is not supported in Gemini API.""", + ) + frequency_penalty: Optional[float] = Field( + default=None, + description="""Optional. Penalizes tokens based on their frequency in the generated text. A positive value helps to reduce the repetition of words and phrases. Valid values can range from [-2.0, 2.0].""", + ) + logprobs: Optional[int] = Field( + default=None, + description="""Optional. The number of top log probabilities to return for each token. This can be used to see which other tokens were considered likely candidates for a given position. A higher value will return more options, but it will also increase the size of the response.""", + ) + max_output_tokens: Optional[int] = Field( + default=None, + description="""Optional. The maximum number of tokens to generate in the response. A token is approximately four characters. The default value varies by model. This parameter can be used to control the length of the generated text and prevent overly long responses.""", + ) + media_resolution: Optional[MediaResolution] = Field( + default=None, + description="""Optional. The token resolution at which input media content is sampled. This is used to control the trade-off between the quality of the response and the number of tokens used to represent the media. A higher resolution allows the model to perceive more detail, which can lead to a more nuanced response, but it will also use more tokens. This does not affect the image dimensions sent to the model.""", + ) + presence_penalty: Optional[float] = Field( + default=None, + description="""Optional. Penalizes tokens that have already appeared in the generated text. A positive value encourages the model to generate more diverse and less repetitive text. Valid values can range from [-2.0, 2.0].""", + ) + response_logprobs: Optional[bool] = Field( + default=None, + description="""Optional. If set to true, the log probabilities of the output tokens are returned. Log probabilities are the logarithm of the probability of a token appearing in the output. A higher log probability means the token is more likely to be generated. This can be useful for analyzing the model's confidence in its own output and for debugging.""", + ) + response_mime_type: Optional[str] = Field( + default=None, + description="""Optional. The IANA standard MIME type of the response. The model will generate output that conforms to this MIME type. Supported values include 'text/plain' (default) and 'application/json'. The model needs to be prompted to output the appropriate response type, otherwise the behavior is undefined. This is a preview feature.""", + ) + response_modalities: Optional[list[Modality]] = Field( + default=None, + description="""Optional. The modalities of the response. The model will generate a response that includes all the specified modalities. For example, if this is set to `[TEXT, IMAGE]`, the response will include both text and an image.""", + ) + response_schema: Optional[Schema] = Field( + default=None, + description="""Optional. Lets you to specify a schema for the model's response, ensuring that the output conforms to a particular structure. This is useful for generating structured data such as JSON. The schema is a subset of the [OpenAPI 3.0 schema object](https://spec.openapis.org/oas/v3.0.3#schema) object. When this field is set, you must also set the `response_mime_type` to `application/json`.""", + ) + routing_config: Optional[GenerationConfigRoutingConfig] = Field( + default=None, + description="""Optional. Routing configuration. This field is not supported in Gemini API.""", + ) + seed: Optional[int] = Field( + default=None, + description="""Optional. A seed for the random number generator. By setting a seed, you can make the model's output mostly deterministic. For a given prompt and parameters (like temperature, top_p, etc.), the model will produce the same response every time. However, it's not a guaranteed absolute deterministic behavior. This is different from parameters like `temperature`, which control the *level* of randomness. `seed` ensures that the "random" choices the model makes are the same on every run, making it essential for testing and ensuring reproducible results.""", + ) + speech_config: Optional[SpeechConfig] = Field( + default=None, description="""Optional. The speech generation config.""" + ) + stop_sequences: Optional[list[str]] = Field( + default=None, + description="""Optional. A list of character sequences that will stop the model from generating further tokens. If a stop sequence is generated, the output will end at that point. This is useful for controlling the length and structure of the output. For example, you can use ["\n", "###"] to stop generation at a new line or a specific marker.""", + ) + temperature: Optional[float] = Field( + default=None, + description="""Optional. Controls the randomness of the output. A higher temperature results in more creative and diverse responses, while a lower temperature makes the output more predictable and focused. The valid range is (0.0, 2.0].""", + ) + thinking_config: Optional[ThinkingConfig] = Field( + default=None, + description="""Optional. Configuration for thinking features. An error will be returned if this field is set for models that don't support thinking.""", + ) + top_k: Optional[float] = Field( + default=None, + description="""Optional. Specifies the top-k sampling threshold. The model considers only the top k most probable tokens for the next token. This can be useful for generating more coherent and less random text. For example, a `top_k` of 40 means the model will choose the next word from the 40 most likely words.""", + ) + top_p: Optional[float] = Field( + default=None, + description="""Optional. Specifies the nucleus sampling threshold. The model considers only the smallest set of tokens whose cumulative probability is at least `top_p`. This helps generate more diverse and less repetitive responses. For example, a `top_p` of 0.9 means the model considers tokens until the cumulative probability of the tokens to select from reaches 0.9. It's recommended to adjust either temperature or `top_p`, but not both.""", + ) + enable_enhanced_civic_answers: Optional[bool] = Field( + default=None, + description="""Optional. Enables enhanced civic answers. It may not be available for all models. This field is not supported in Vertex AI.""", + ) + + +class GenerationConfigDict(TypedDict, total=False): + """Generation config.""" + + model_selection_config: Optional[ModelSelectionConfigDict] + """Optional. Config for model selection.""" + + response_json_schema: Optional[Any] + """Output schema of the generated response. This is an alternative to + `response_schema` that accepts [JSON Schema](https://json-schema.org/). + """ + + audio_timestamp: Optional[bool] + """Optional. If enabled, audio timestamps will be included in the request to the model. This can be useful for synchronizing audio with other modalities in the response. This field is not supported in Gemini API.""" + + candidate_count: Optional[int] + """Optional. The number of candidate responses to generate. A higher `candidate_count` can provide more options to choose from, but it also consumes more resources. This can be useful for generating a variety of responses and selecting the best one.""" + + enable_affective_dialog: Optional[bool] + """Optional. If enabled, the model will detect emotions and adapt its responses accordingly. For example, if the model detects that the user is frustrated, it may provide a more empathetic response. This field is not supported in Gemini API.""" + + frequency_penalty: Optional[float] + """Optional. Penalizes tokens based on their frequency in the generated text. A positive value helps to reduce the repetition of words and phrases. Valid values can range from [-2.0, 2.0].""" + + logprobs: Optional[int] + """Optional. The number of top log probabilities to return for each token. This can be used to see which other tokens were considered likely candidates for a given position. A higher value will return more options, but it will also increase the size of the response.""" + + max_output_tokens: Optional[int] + """Optional. The maximum number of tokens to generate in the response. A token is approximately four characters. The default value varies by model. This parameter can be used to control the length of the generated text and prevent overly long responses.""" + + media_resolution: Optional[MediaResolution] + """Optional. The token resolution at which input media content is sampled. This is used to control the trade-off between the quality of the response and the number of tokens used to represent the media. A higher resolution allows the model to perceive more detail, which can lead to a more nuanced response, but it will also use more tokens. This does not affect the image dimensions sent to the model.""" + + presence_penalty: Optional[float] + """Optional. Penalizes tokens that have already appeared in the generated text. A positive value encourages the model to generate more diverse and less repetitive text. Valid values can range from [-2.0, 2.0].""" + + response_logprobs: Optional[bool] + """Optional. If set to true, the log probabilities of the output tokens are returned. Log probabilities are the logarithm of the probability of a token appearing in the output. A higher log probability means the token is more likely to be generated. This can be useful for analyzing the model's confidence in its own output and for debugging.""" + + response_mime_type: Optional[str] + """Optional. The IANA standard MIME type of the response. The model will generate output that conforms to this MIME type. Supported values include 'text/plain' (default) and 'application/json'. The model needs to be prompted to output the appropriate response type, otherwise the behavior is undefined. This is a preview feature.""" + + response_modalities: Optional[list[Modality]] + """Optional. The modalities of the response. The model will generate a response that includes all the specified modalities. For example, if this is set to `[TEXT, IMAGE]`, the response will include both text and an image.""" + + response_schema: Optional[SchemaDict] + """Optional. Lets you to specify a schema for the model's response, ensuring that the output conforms to a particular structure. This is useful for generating structured data such as JSON. The schema is a subset of the [OpenAPI 3.0 schema object](https://spec.openapis.org/oas/v3.0.3#schema) object. When this field is set, you must also set the `response_mime_type` to `application/json`.""" + + routing_config: Optional[GenerationConfigRoutingConfigDict] + """Optional. Routing configuration. This field is not supported in Gemini API.""" + + seed: Optional[int] + """Optional. A seed for the random number generator. By setting a seed, you can make the model's output mostly deterministic. For a given prompt and parameters (like temperature, top_p, etc.), the model will produce the same response every time. However, it's not a guaranteed absolute deterministic behavior. This is different from parameters like `temperature`, which control the *level* of randomness. `seed` ensures that the "random" choices the model makes are the same on every run, making it essential for testing and ensuring reproducible results.""" + + speech_config: Optional[SpeechConfigDict] + """Optional. The speech generation config.""" + + stop_sequences: Optional[list[str]] + """Optional. A list of character sequences that will stop the model from generating further tokens. If a stop sequence is generated, the output will end at that point. This is useful for controlling the length and structure of the output. For example, you can use ["\n", "###"] to stop generation at a new line or a specific marker.""" + + temperature: Optional[float] + """Optional. Controls the randomness of the output. A higher temperature results in more creative and diverse responses, while a lower temperature makes the output more predictable and focused. The valid range is (0.0, 2.0].""" + + thinking_config: Optional[ThinkingConfigDict] + """Optional. Configuration for thinking features. An error will be returned if this field is set for models that don't support thinking.""" + + top_k: Optional[float] + """Optional. Specifies the top-k sampling threshold. The model considers only the top k most probable tokens for the next token. This can be useful for generating more coherent and less random text. For example, a `top_k` of 40 means the model will choose the next word from the 40 most likely words.""" + + top_p: Optional[float] + """Optional. Specifies the nucleus sampling threshold. The model considers only the smallest set of tokens whose cumulative probability is at least `top_p`. This helps generate more diverse and less repetitive responses. For example, a `top_p` of 0.9 means the model considers tokens until the cumulative probability of the tokens to select from reaches 0.9. It's recommended to adjust either temperature or `top_p`, but not both.""" + + enable_enhanced_civic_answers: Optional[bool] + """Optional. Enables enhanced civic answers. It may not be available for all models. This field is not supported in Vertex AI.""" + + +GenerationConfigOrDict = Union[GenerationConfig, GenerationConfigDict] + + +class CountTokensConfig(_common.BaseModel): + """Config for the count_tokens method.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + system_instruction: Optional[ContentUnion] = Field( + default=None, + description="""Instructions for the model to steer it toward better performance. + """, + ) + tools: Optional[list[Tool]] = Field( + default=None, + description="""Code that enables the system to interact with external systems to + perform an action outside of the knowledge and scope of the model. + """, + ) + generation_config: Optional[GenerationConfig] = Field( + default=None, + description="""Configuration that the model uses to generate the response. Not + supported by the Gemini Developer API. + """, + ) + + +class CountTokensConfigDict(TypedDict, total=False): + """Config for the count_tokens method.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + system_instruction: Optional[ContentUnionDict] + """Instructions for the model to steer it toward better performance. + """ + + tools: Optional[list[ToolDict]] + """Code that enables the system to interact with external systems to + perform an action outside of the knowledge and scope of the model. + """ + + generation_config: Optional[GenerationConfigDict] + """Configuration that the model uses to generate the response. Not + supported by the Gemini Developer API. + """ + + +CountTokensConfigOrDict = Union[CountTokensConfig, CountTokensConfigDict] + + +class _CountTokensParameters(_common.BaseModel): + """Parameters for counting tokens.""" + + model: Optional[str] = Field( + default=None, + description="""ID of the model to use. For a list of models, see `Google models + `_.""", + ) + contents: Optional[ContentListUnion] = Field( + default=None, description="""Input content.""" + ) + config: Optional[CountTokensConfig] = Field( + default=None, description="""Configuration for counting tokens.""" + ) + + +class _CountTokensParametersDict(TypedDict, total=False): + """Parameters for counting tokens.""" + + model: Optional[str] + """ID of the model to use. For a list of models, see `Google models + `_.""" + + contents: Optional[ContentListUnionDict] + """Input content.""" + + config: Optional[CountTokensConfigDict] + """Configuration for counting tokens.""" + + +_CountTokensParametersOrDict = Union[ + _CountTokensParameters, _CountTokensParametersDict +] + + +class CountTokensResponse(_common.BaseModel): + """Response for counting tokens.""" + + sdk_http_response: Optional[HttpResponse] = Field( + default=None, description="""Used to retain the full HTTP response.""" + ) + total_tokens: Optional[int] = Field( + default=None, description="""Total number of tokens.""" + ) + cached_content_token_count: Optional[int] = Field( + default=None, + description="""Number of tokens in the cached part of the prompt (the cached content).""", + ) + + +class CountTokensResponseDict(TypedDict, total=False): + """Response for counting tokens.""" + + sdk_http_response: Optional[HttpResponseDict] + """Used to retain the full HTTP response.""" + + total_tokens: Optional[int] + """Total number of tokens.""" + + cached_content_token_count: Optional[int] + """Number of tokens in the cached part of the prompt (the cached content).""" + + +CountTokensResponseOrDict = Union[CountTokensResponse, CountTokensResponseDict] + + +class ComputeTokensConfig(_common.BaseModel): + """Optional parameters for computing tokens.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + + +class ComputeTokensConfigDict(TypedDict, total=False): + """Optional parameters for computing tokens.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + +ComputeTokensConfigOrDict = Union[ComputeTokensConfig, ComputeTokensConfigDict] + + +class _ComputeTokensParameters(_common.BaseModel): + """Parameters for computing tokens.""" + + model: Optional[str] = Field( + default=None, + description="""ID of the model to use. For a list of models, see `Google models + `_.""", + ) + contents: Optional[ContentListUnion] = Field( + default=None, description="""Input content.""" + ) + config: Optional[ComputeTokensConfig] = Field( + default=None, + description="""Optional parameters for the request. + """, + ) + + +class _ComputeTokensParametersDict(TypedDict, total=False): + """Parameters for computing tokens.""" + + model: Optional[str] + """ID of the model to use. For a list of models, see `Google models + `_.""" + + contents: Optional[ContentListUnionDict] + """Input content.""" + + config: Optional[ComputeTokensConfigDict] + """Optional parameters for the request. + """ + + +_ComputeTokensParametersOrDict = Union[ + _ComputeTokensParameters, _ComputeTokensParametersDict +] + + +class TokensInfo(_common.BaseModel): + """Tokens info with a list of tokens and the corresponding list of token ids.""" + + role: Optional[str] = Field( + default=None, + description="""Optional fields for the role from the corresponding Content.""", + ) + token_ids: Optional[list[int]] = Field( + default=None, description="""A list of token ids from the input.""" + ) + tokens: Optional[list[bytes]] = Field( + default=None, description="""A list of tokens from the input.""" + ) + + +class TokensInfoDict(TypedDict, total=False): + """Tokens info with a list of tokens and the corresponding list of token ids.""" + + role: Optional[str] + """Optional fields for the role from the corresponding Content.""" + + token_ids: Optional[list[int]] + """A list of token ids from the input.""" + + tokens: Optional[list[bytes]] + """A list of tokens from the input.""" + + +TokensInfoOrDict = Union[TokensInfo, TokensInfoDict] + + +class ComputeTokensResponse(_common.BaseModel): + """Response for computing tokens.""" + + sdk_http_response: Optional[HttpResponse] = Field( + default=None, description="""Used to retain the full HTTP response.""" + ) + tokens_info: Optional[list[TokensInfo]] = Field( + default=None, + description="""Lists of tokens info from the input. A ComputeTokensRequest could have multiple instances with a prompt in each instance. We also need to return lists of tokens info for the request with multiple instances.""", + ) + + +class ComputeTokensResponseDict(TypedDict, total=False): + """Response for computing tokens.""" + + sdk_http_response: Optional[HttpResponseDict] + """Used to retain the full HTTP response.""" + + tokens_info: Optional[list[TokensInfoDict]] + """Lists of tokens info from the input. A ComputeTokensRequest could have multiple instances with a prompt in each instance. We also need to return lists of tokens info for the request with multiple instances.""" + + +ComputeTokensResponseOrDict = Union[ + ComputeTokensResponse, ComputeTokensResponseDict +] + + +class Video(_common.BaseModel): + """A generated video.""" + + uri: Optional[str] = Field( + default=None, description="""Path to another storage.""" + ) + video_bytes: Optional[bytes] = Field( + default=None, description="""Video bytes.""" + ) + mime_type: Optional[str] = Field( + default=None, description="""Video encoding, for example ``video/mp4``.""" + ) + + @classmethod + def from_file( + cls, *, location: str, mime_type: Optional[str] = None + ) -> 'Video': + """Loads a video from a local file. + + Args: + location: The local path to load the video from. + mime_type: The MIME type of the video. If not provided, the MIME type + will be automatically determined. + + Returns: + A loaded video as an `Video` object. + """ + import mimetypes # pylint: disable=g-import-not-at-top + import pathlib # pylint: disable=g-import-not-at-top + + video_bytes = pathlib.Path(location).read_bytes() + + if not mime_type: + mime_type, _ = mimetypes.guess_type(location) + video = cls(video_bytes=video_bytes, mime_type=mime_type) + return video + + def save( + self, + path: str, + ) -> None: + """Saves the video to a file. + + Args: + path: Local path where to save the video. + """ + import pathlib # pylint: disable=g-import-not-at-top + + if not self.video_bytes: + raise NotImplementedError('Saving remote videos is not supported.') + + pathlib.Path(path).write_bytes(self.video_bytes) + + def show(self) -> None: + """Shows the video. + + If the video has no mime_type, it is assumed to be video/mp4. + + This method only works in a notebook environment. + """ + if self.uri and not self.video_bytes: + raise ValueError('Showing remote videos is not supported.') + if not self.video_bytes: + raise ValueError('Video has no bytes.') + + mime_type = self.mime_type or 'video/mp4' + + try: + from IPython import display as IPython_display + except ImportError: + IPython_display = None + + if IPython_display: + IPython_display.display( + IPython_display.Video( + data=self.video_bytes, mimetype=mime_type, embed=True + ) + ) + + def __repr__(self) -> str: + video_bytes = '' if self.video_bytes else 'None' + return ( + f'Video(uri={self.uri}, video_bytes={video_bytes},' + f' mime_type={self.mime_type})' + ) + + +class VideoDict(TypedDict, total=False): + """A generated video.""" + + uri: Optional[str] + """Path to another storage.""" + + video_bytes: Optional[bytes] + """Video bytes.""" + + mime_type: Optional[str] + """Video encoding, for example ``video/mp4``.""" + + +VideoOrDict = Union[Video, VideoDict] + + +class GenerateVideosSource(_common.BaseModel): + """A set of source input(s) for video generation.""" + + prompt: Optional[str] = Field( + default=None, + description="""The text prompt for generating the videos. + Optional if image or video is provided.""", + ) + image: Optional[Image] = Field( + default=None, + description="""The input image for generating the videos. + Optional if prompt is provided. Not allowed if video is provided.""", + ) + video: Optional[Video] = Field( + default=None, + description="""The input video for video extension use cases. + Optional if prompt is provided. Not allowed if image is provided.""", + ) + + +class GenerateVideosSourceDict(TypedDict, total=False): + """A set of source input(s) for video generation.""" + + prompt: Optional[str] + """The text prompt for generating the videos. + Optional if image or video is provided.""" + + image: Optional[ImageDict] + """The input image for generating the videos. + Optional if prompt is provided. Not allowed if video is provided.""" + + video: Optional[VideoDict] + """The input video for video extension use cases. + Optional if prompt is provided. Not allowed if image is provided.""" + + +GenerateVideosSourceOrDict = Union[ + GenerateVideosSource, GenerateVideosSourceDict +] + + +class VideoGenerationReferenceImage(_common.BaseModel): + """A reference image for video generation.""" + + image: Optional[Image] = Field( + default=None, description="""The reference image.""" + ) + reference_type: Optional[VideoGenerationReferenceType] = Field( + default=None, + description="""The type of the reference image, which defines how the reference + image will be used to generate the video.""", + ) + + +class VideoGenerationReferenceImageDict(TypedDict, total=False): + """A reference image for video generation.""" + + image: Optional[ImageDict] + """The reference image.""" + + reference_type: Optional[VideoGenerationReferenceType] + """The type of the reference image, which defines how the reference + image will be used to generate the video.""" + + +VideoGenerationReferenceImageOrDict = Union[ + VideoGenerationReferenceImage, VideoGenerationReferenceImageDict +] + + +class VideoGenerationMask(_common.BaseModel): + """A mask for video generation.""" + + image: Optional[Image] = Field( + default=None, + description="""The image mask to use for generating videos.""", + ) + mask_mode: Optional[VideoGenerationMaskMode] = Field( + default=None, + description="""Describes how the mask will be used. Inpainting masks must + match the aspect ratio of the input video. Outpainting masks can be + either 9:16 or 16:9.""", + ) + + +class VideoGenerationMaskDict(TypedDict, total=False): + """A mask for video generation.""" + + image: Optional[ImageDict] + """The image mask to use for generating videos.""" + + mask_mode: Optional[VideoGenerationMaskMode] + """Describes how the mask will be used. Inpainting masks must + match the aspect ratio of the input video. Outpainting masks can be + either 9:16 or 16:9.""" + + +VideoGenerationMaskOrDict = Union[VideoGenerationMask, VideoGenerationMaskDict] + + +class WebhookConfig(_common.BaseModel): + """Configuration for webhook notifications. + + Used to configure webhook endpoints that will receive notifications + when long-running operations (e.g., batch jobs, video generation) complete. + """ + + uris: Optional[list[str]] = Field( + default=None, + description="""The webhook URIs to receive notifications. If set, these + webhook URIs will be used instead of the registered webhooks.""", + ) + user_metadata: Optional[dict[str, Any]] = Field( + default=None, + description="""User metadata that will be included in each webhook event + notification. Use this to attach custom key-value data to correlate + webhook events with your internal systems.""", + ) + + +class WebhookConfigDict(TypedDict, total=False): + """Configuration for webhook notifications. + + Used to configure webhook endpoints that will receive notifications + when long-running operations (e.g., batch jobs, video generation) complete. + """ + + uris: Optional[list[str]] + """The webhook URIs to receive notifications. If set, these + webhook URIs will be used instead of the registered webhooks.""" + + user_metadata: Optional[dict[str, Any]] + """User metadata that will be included in each webhook event + notification. Use this to attach custom key-value data to correlate + webhook events with your internal systems.""" + + +WebhookConfigOrDict = Union[WebhookConfig, WebhookConfigDict] + + +class GenerateVideosConfig(_common.BaseModel): + """Configuration for generating videos.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + number_of_videos: Optional[int] = Field( + default=None, description="""Number of output videos.""" + ) + output_gcs_uri: Optional[str] = Field( + default=None, + description="""The gcs bucket where to save the generated videos.""", + ) + fps: Optional[int] = Field( + default=None, description="""Frames per second for video generation.""" + ) + duration_seconds: Optional[int] = Field( + default=None, + description="""Duration of the clip for video generation in seconds.""", + ) + seed: Optional[int] = Field( + default=None, + description="""The RNG seed. If RNG seed is exactly same for each request with + unchanged inputs, the prediction results will be consistent. Otherwise, + a random RNG seed will be used each time to produce a different + result.""", + ) + aspect_ratio: Optional[str] = Field( + default=None, + description="""The aspect ratio for the generated video. 16:9 (landscape) and + 9:16 (portrait) are supported.""", + ) + resolution: Optional[str] = Field( + default=None, + description="""The resolution for the generated video. 720p and 1080p are + supported.""", + ) + person_generation: Optional[str] = Field( + default=None, + description="""Whether allow to generate person videos, and restrict to specific + ages. Supported values are: dont_allow, allow_adult.""", + ) + pubsub_topic: Optional[str] = Field( + default=None, + description="""The pubsub topic where to publish the video generation + progress.""", + ) + negative_prompt: Optional[str] = Field( + default=None, + description="""Explicitly state what should not be included in the generated + videos.""", + ) + enhance_prompt: Optional[bool] = Field( + default=None, description="""Whether to use the prompt rewriting logic.""" + ) + generate_audio: Optional[bool] = Field( + default=None, + description="""Whether to generate audio along with the video.""", + ) + last_frame: Optional[Image] = Field( + default=None, + description="""Image to use as the last frame of generated videos. + Only supported for image to video use cases.""", + ) + reference_images: Optional[list[VideoGenerationReferenceImage]] = Field( + default=None, + description="""The images to use as the references to generate the videos. + If this field is provided, the text prompt field must also be provided. + The image, video, or last_frame field are not supported. Each image must + be associated with a type. Veo 2 supports up to 3 asset images *or* 1 + style image.""", + ) + mask: Optional[VideoGenerationMask] = Field( + default=None, description="""The mask to use for generating videos.""" + ) + compression_quality: Optional[VideoCompressionQuality] = Field( + default=None, + description="""Compression quality of the generated videos.""", + ) + labels: Optional[dict[str, str]] = Field( + default=None, + description="""User specified labels to track billing usage.""", + ) + webhook_config: Optional[WebhookConfig] = Field( + default=None, + description="""Webhook configuration for receiving notifications when the + video generation operation completes.""", + ) + + +class GenerateVideosConfigDict(TypedDict, total=False): + """Configuration for generating videos.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + number_of_videos: Optional[int] + """Number of output videos.""" + + output_gcs_uri: Optional[str] + """The gcs bucket where to save the generated videos.""" + + fps: Optional[int] + """Frames per second for video generation.""" + + duration_seconds: Optional[int] + """Duration of the clip for video generation in seconds.""" + + seed: Optional[int] + """The RNG seed. If RNG seed is exactly same for each request with + unchanged inputs, the prediction results will be consistent. Otherwise, + a random RNG seed will be used each time to produce a different + result.""" + + aspect_ratio: Optional[str] + """The aspect ratio for the generated video. 16:9 (landscape) and + 9:16 (portrait) are supported.""" + + resolution: Optional[str] + """The resolution for the generated video. 720p and 1080p are + supported.""" + + person_generation: Optional[str] + """Whether allow to generate person videos, and restrict to specific + ages. Supported values are: dont_allow, allow_adult.""" + + pubsub_topic: Optional[str] + """The pubsub topic where to publish the video generation + progress.""" + + negative_prompt: Optional[str] + """Explicitly state what should not be included in the generated + videos.""" + + enhance_prompt: Optional[bool] + """Whether to use the prompt rewriting logic.""" + + generate_audio: Optional[bool] + """Whether to generate audio along with the video.""" + + last_frame: Optional[ImageDict] + """Image to use as the last frame of generated videos. + Only supported for image to video use cases.""" + + reference_images: Optional[list[VideoGenerationReferenceImageDict]] + """The images to use as the references to generate the videos. + If this field is provided, the text prompt field must also be provided. + The image, video, or last_frame field are not supported. Each image must + be associated with a type. Veo 2 supports up to 3 asset images *or* 1 + style image.""" + + mask: Optional[VideoGenerationMaskDict] + """The mask to use for generating videos.""" + + compression_quality: Optional[VideoCompressionQuality] + """Compression quality of the generated videos.""" + + labels: Optional[dict[str, str]] + """User specified labels to track billing usage.""" + + webhook_config: Optional[WebhookConfigDict] + """Webhook configuration for receiving notifications when the + video generation operation completes.""" + + +GenerateVideosConfigOrDict = Union[ + GenerateVideosConfig, GenerateVideosConfigDict +] + + +class _GenerateVideosParameters(_common.BaseModel): + """Class that represents the parameters for generating videos.""" + + model: Optional[str] = Field( + default=None, + description="""ID of the model to use. For a list of models, see `Google models + `_.""", + ) + prompt: Optional[str] = Field( + default=None, + description="""The text prompt for generating the videos. + Optional if image or video is provided.""", + ) + image: Optional[Image] = Field( + default=None, + description="""The input image for generating the videos. + Optional if prompt is provided. Not allowed if video is provided.""", + ) + video: Optional[Video] = Field( + default=None, + description="""The input video for video extension use cases. + Optional if prompt is provided. Not allowed if image is provided.""", + ) + source: Optional[GenerateVideosSource] = Field( + default=None, + description="""A set of source input(s) for video generation.""", + ) + config: Optional[GenerateVideosConfig] = Field( + default=None, description="""Configuration for generating videos.""" + ) + + +class _GenerateVideosParametersDict(TypedDict, total=False): + """Class that represents the parameters for generating videos.""" + + model: Optional[str] + """ID of the model to use. For a list of models, see `Google models + `_.""" + + prompt: Optional[str] + """The text prompt for generating the videos. + Optional if image or video is provided.""" + + image: Optional[ImageDict] + """The input image for generating the videos. + Optional if prompt is provided. Not allowed if video is provided.""" + + video: Optional[VideoDict] + """The input video for video extension use cases. + Optional if prompt is provided. Not allowed if image is provided.""" + + source: Optional[GenerateVideosSourceDict] + """A set of source input(s) for video generation.""" + + config: Optional[GenerateVideosConfigDict] + """Configuration for generating videos.""" + + +_GenerateVideosParametersOrDict = Union[ + _GenerateVideosParameters, _GenerateVideosParametersDict +] + + +class GeneratedVideo(_common.BaseModel): + """A generated video.""" + + video: Optional[Video] = Field( + default=None, description="""The output video""" + ) + + +class GeneratedVideoDict(TypedDict, total=False): + """A generated video.""" + + video: Optional[VideoDict] + """The output video""" + + +GeneratedVideoOrDict = Union[GeneratedVideo, GeneratedVideoDict] + + +class GenerateVideosResponse(_common.BaseModel): + """Response with generated videos.""" + + generated_videos: Optional[list[GeneratedVideo]] = Field( + default=None, description="""List of the generated videos""" + ) + rai_media_filtered_count: Optional[int] = Field( + default=None, + description="""Returns if any videos were filtered due to RAI policies.""", + ) + rai_media_filtered_reasons: Optional[list[str]] = Field( + default=None, description="""Returns rai failure reasons if any.""" + ) + + +class GenerateVideosResponseDict(TypedDict, total=False): + """Response with generated videos.""" + + generated_videos: Optional[list[GeneratedVideoDict]] + """List of the generated videos""" + + rai_media_filtered_count: Optional[int] + """Returns if any videos were filtered due to RAI policies.""" + + rai_media_filtered_reasons: Optional[list[str]] + """Returns rai failure reasons if any.""" + + +GenerateVideosResponseOrDict = Union[ + GenerateVideosResponse, GenerateVideosResponseDict +] + + +class Operation(ABC): + """A long-running operation.""" + + name: Optional[str] = Field( + default=None, + description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""", + ) + metadata: Optional[dict[str, Any]] = Field( + default=None, + description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.""", + ) + done: Optional[bool] = Field( + default=None, + description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""", + ) + error: Optional[dict[str, Any]] = Field( + default=None, + description="""The error result of the operation in case of failure or cancellation.""", + ) + + @classmethod + @abstractmethod + def from_api_response( + cls, api_response: Any, is_vertex_ai: bool = False + ) -> Self: + """Creates an Operation from an API response.""" + pass + + +class GenerateVideosOperation(_common.BaseModel, Operation): + """A video generation operation.""" + + response: Optional[GenerateVideosResponse] = Field( + default=None, description="""The generated videos.""" + ) + result: Optional[GenerateVideosResponse] = Field( + default=None, description="""The generated videos.""" + ) + + @classmethod + def from_api_response( + cls, api_response: Any, is_vertex_ai: bool = False + ) -> Self: + """Instantiates a GenerateVideosOperation from an API response.""" + + if is_vertex_ai: + response_dict = _GenerateVideosOperation_from_vertex(api_response) + else: + response_dict = _GenerateVideosOperation_from_mldev(api_response) + + return cls._from_response(response=response_dict, kwargs={}) + + +class GetTuningJobConfig(_common.BaseModel): + """Optional parameters for tunings.get method.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + + +class GetTuningJobConfigDict(TypedDict, total=False): + """Optional parameters for tunings.get method.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + +GetTuningJobConfigOrDict = Union[GetTuningJobConfig, GetTuningJobConfigDict] + + +class _GetTuningJobParameters(_common.BaseModel): + """Parameters for the get method.""" + + name: Optional[str] = Field(default=None, description="""""") + config: Optional[GetTuningJobConfig] = Field( + default=None, description="""Optional parameters for the request.""" + ) + + +class _GetTuningJobParametersDict(TypedDict, total=False): + """Parameters for the get method.""" + + name: Optional[str] + """""" + + config: Optional[GetTuningJobConfigDict] + """Optional parameters for the request.""" + + +_GetTuningJobParametersOrDict = Union[ + _GetTuningJobParameters, _GetTuningJobParametersDict +] + + +class TunedModelCheckpoint(_common.BaseModel): + """TunedModelCheckpoint for the Tuned Model of a Tuning Job.""" + + checkpoint_id: Optional[str] = Field( + default=None, + description="""The ID of the checkpoint. + """, + ) + epoch: Optional[int] = Field( + default=None, + description="""The epoch of the checkpoint. + """, + ) + step: Optional[int] = Field( + default=None, + description="""The step of the checkpoint. + """, + ) + endpoint: Optional[str] = Field( + default=None, + description="""The Endpoint resource name that the checkpoint is deployed to. + Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`. + """, + ) + + +class TunedModelCheckpointDict(TypedDict, total=False): + """TunedModelCheckpoint for the Tuned Model of a Tuning Job.""" + + checkpoint_id: Optional[str] + """The ID of the checkpoint. + """ + + epoch: Optional[int] + """The epoch of the checkpoint. + """ + + step: Optional[int] + """The step of the checkpoint. + """ + + endpoint: Optional[str] + """The Endpoint resource name that the checkpoint is deployed to. + Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`. + """ + + +TunedModelCheckpointOrDict = Union[ + TunedModelCheckpoint, TunedModelCheckpointDict +] + + +class TunedModel(_common.BaseModel): + """TunedModel for the Tuned Model of a Tuning Job.""" + + model: Optional[str] = Field( + default=None, + description="""Output only. The resource name of the TunedModel. + Format: `projects/{project}/locations/{location}/models/{model}@{version_id}` + When tuning from a base model, the version_id will be 1. + For continuous tuning, the version id will be incremented by 1 from the + last version id in the parent model. E.g., `projects/{project}/locations/{location}/models/{model}@{last_version_id + 1}` + """, + ) + endpoint: Optional[str] = Field( + default=None, + description="""Output only. A resource name of an Endpoint. + Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`. + """, + ) + checkpoints: Optional[list[TunedModelCheckpoint]] = Field( + default=None, + description="""The checkpoints associated with this TunedModel. + This field is only populated for tuning jobs that enable intermediate + checkpoints.""", + ) + + +class TunedModelDict(TypedDict, total=False): + """TunedModel for the Tuned Model of a Tuning Job.""" + + model: Optional[str] + """Output only. The resource name of the TunedModel. + Format: `projects/{project}/locations/{location}/models/{model}@{version_id}` + When tuning from a base model, the version_id will be 1. + For continuous tuning, the version id will be incremented by 1 from the + last version id in the parent model. E.g., `projects/{project}/locations/{location}/models/{model}@{last_version_id + 1}` + """ + + endpoint: Optional[str] + """Output only. A resource name of an Endpoint. + Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`. + """ + + checkpoints: Optional[list[TunedModelCheckpointDict]] + """The checkpoints associated with this TunedModel. + This field is only populated for tuning jobs that enable intermediate + checkpoints.""" + + +TunedModelOrDict = Union[TunedModel, TunedModelDict] + + +class SupervisedHyperParameters(_common.BaseModel): + """Hyperparameters for SFT. This data type is not supported in Gemini API.""" + + adapter_size: Optional[AdapterSize] = Field( + default=None, description="""Optional. Adapter size for tuning.""" + ) + batch_size: Optional[int] = Field( + default=None, + description="""Optional. Batch size for tuning. This feature is only available for open source models.""", + ) + epoch_count: Optional[int] = Field( + default=None, + description="""Optional. Number of complete passes the model makes over the entire training dataset during training.""", + ) + learning_rate: Optional[float] = Field( + default=None, + description="""Optional. Learning rate for tuning. Mutually exclusive with `learning_rate_multiplier`. This feature is only available for open source models.""", + ) + learning_rate_multiplier: Optional[float] = Field( + default=None, + description="""Optional. Multiplier for adjusting the default learning rate. Mutually exclusive with `learning_rate`. This feature is only available for 1P models.""", + ) + + +class SupervisedHyperParametersDict(TypedDict, total=False): + """Hyperparameters for SFT. This data type is not supported in Gemini API.""" + + adapter_size: Optional[AdapterSize] + """Optional. Adapter size for tuning.""" + + batch_size: Optional[int] + """Optional. Batch size for tuning. This feature is only available for open source models.""" + + epoch_count: Optional[int] + """Optional. Number of complete passes the model makes over the entire training dataset during training.""" + + learning_rate: Optional[float] + """Optional. Learning rate for tuning. Mutually exclusive with `learning_rate_multiplier`. This feature is only available for open source models.""" + + learning_rate_multiplier: Optional[float] + """Optional. Multiplier for adjusting the default learning rate. Mutually exclusive with `learning_rate`. This feature is only available for 1P models.""" + + +SupervisedHyperParametersOrDict = Union[ + SupervisedHyperParameters, SupervisedHyperParametersDict +] + + +class SupervisedTuningSpec(_common.BaseModel): + """Supervised tuning spec for tuning.""" + + export_last_checkpoint_only: Optional[bool] = Field( + default=None, + description="""Optional. If set to true, disable intermediate checkpoints for SFT and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for SFT. Default is false.""", + ) + hyper_parameters: Optional[SupervisedHyperParameters] = Field( + default=None, description="""Optional. Hyperparameters for SFT.""" + ) + training_dataset_uri: Optional[str] = Field( + default=None, + description="""Required. Training dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset.""", + ) + tuning_mode: Optional[TuningMode] = Field( + default=None, description="""Tuning mode.""" + ) + validation_dataset_uri: Optional[str] = Field( + default=None, + description="""Optional. Validation dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset.""", + ) + + +class SupervisedTuningSpecDict(TypedDict, total=False): + """Supervised tuning spec for tuning.""" + + export_last_checkpoint_only: Optional[bool] + """Optional. If set to true, disable intermediate checkpoints for SFT and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for SFT. Default is false.""" + + hyper_parameters: Optional[SupervisedHyperParametersDict] + """Optional. Hyperparameters for SFT.""" + + training_dataset_uri: Optional[str] + """Required. Training dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset.""" + + tuning_mode: Optional[TuningMode] + """Tuning mode.""" + + validation_dataset_uri: Optional[str] + """Optional. Validation dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset.""" + + +SupervisedTuningSpecOrDict = Union[ + SupervisedTuningSpec, SupervisedTuningSpecDict +] + + +class PreferenceOptimizationHyperParameters(_common.BaseModel): + """Hyperparameters for Preference Optimization. + + This data type is not supported in Gemini API. + """ + + adapter_size: Optional[AdapterSize] = Field( + default=None, + description="""Optional. Adapter size for preference optimization.""", + ) + beta: Optional[float] = Field( + default=None, + description="""Optional. Weight for KL Divergence regularization.""", + ) + epoch_count: Optional[int] = Field( + default=None, + description="""Optional. Number of complete passes the model makes over the entire training dataset during training.""", + ) + learning_rate_multiplier: Optional[float] = Field( + default=None, + description="""Optional. Multiplier for adjusting the default learning rate.""", + ) + + +class PreferenceOptimizationHyperParametersDict(TypedDict, total=False): + """Hyperparameters for Preference Optimization. + + This data type is not supported in Gemini API. + """ + + adapter_size: Optional[AdapterSize] + """Optional. Adapter size for preference optimization.""" + + beta: Optional[float] + """Optional. Weight for KL Divergence regularization.""" + + epoch_count: Optional[int] + """Optional. Number of complete passes the model makes over the entire training dataset during training.""" + + learning_rate_multiplier: Optional[float] + """Optional. Multiplier for adjusting the default learning rate.""" + + +PreferenceOptimizationHyperParametersOrDict = Union[ + PreferenceOptimizationHyperParameters, + PreferenceOptimizationHyperParametersDict, +] + + +class PreferenceOptimizationSpec(_common.BaseModel): + """Preference optimization tuning spec for tuning.""" + + export_last_checkpoint_only: Optional[bool] = Field( + default=None, + description="""Optional. If set to true, disable intermediate checkpoints for Preference Optimization and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for Preference Optimization. Default is false.""", + ) + hyper_parameters: Optional[PreferenceOptimizationHyperParameters] = Field( + default=None, + description="""Optional. Hyperparameters for Preference Optimization.""", + ) + training_dataset_uri: Optional[str] = Field( + default=None, + description="""Required. Cloud Storage path to file containing training dataset for preference optimization tuning. The dataset must be formatted as a JSONL file.""", + ) + validation_dataset_uri: Optional[str] = Field( + default=None, + description="""Optional. Cloud Storage path to file containing validation dataset for preference optimization tuning. The dataset must be formatted as a JSONL file.""", + ) + + +class PreferenceOptimizationSpecDict(TypedDict, total=False): + """Preference optimization tuning spec for tuning.""" + + export_last_checkpoint_only: Optional[bool] + """Optional. If set to true, disable intermediate checkpoints for Preference Optimization and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for Preference Optimization. Default is false.""" + + hyper_parameters: Optional[PreferenceOptimizationHyperParametersDict] + """Optional. Hyperparameters for Preference Optimization.""" + + training_dataset_uri: Optional[str] + """Required. Cloud Storage path to file containing training dataset for preference optimization tuning. The dataset must be formatted as a JSONL file.""" + + validation_dataset_uri: Optional[str] + """Optional. Cloud Storage path to file containing validation dataset for preference optimization tuning. The dataset must be formatted as a JSONL file.""" + + +PreferenceOptimizationSpecOrDict = Union[ + PreferenceOptimizationSpec, PreferenceOptimizationSpecDict +] + + +class DistillationHyperParameters(_common.BaseModel): + """Hyperparameters for distillation.""" + + adapter_size: Optional[AdapterSize] = Field( + default=None, description="""Optional. Adapter size for distillation.""" + ) + epoch_count: Optional[int] = Field( + default=None, + description="""Optional. Number of complete passes the model makes over the entire training dataset during training.""", + ) + learning_rate_multiplier: Optional[float] = Field( + default=None, + description="""Optional. Multiplier for adjusting the default learning rate.""", + ) + batch_size: Optional[int] = Field( + default=None, + description="""The batch size hyperparameter for tuning. + This is only supported for OSS models in Vertex.""", + ) + learning_rate: Optional[float] = Field( + default=None, + description="""The learning rate for tuning. OSS models only.""", + ) + + +class DistillationHyperParametersDict(TypedDict, total=False): + """Hyperparameters for distillation.""" + + adapter_size: Optional[AdapterSize] + """Optional. Adapter size for distillation.""" + + epoch_count: Optional[int] + """Optional. Number of complete passes the model makes over the entire training dataset during training.""" + + learning_rate_multiplier: Optional[float] + """Optional. Multiplier for adjusting the default learning rate.""" + + batch_size: Optional[int] + """The batch size hyperparameter for tuning. + This is only supported for OSS models in Vertex.""" + + learning_rate: Optional[float] + """The learning rate for tuning. OSS models only.""" + + +DistillationHyperParametersOrDict = Union[ + DistillationHyperParameters, DistillationHyperParametersDict +] + + +class DistillationSpec(_common.BaseModel): + """Distillation tuning spec for tuning.""" + + prompt_dataset_uri: Optional[str] = Field( + default=None, + description="""The GCS URI of the prompt dataset to use during distillation.""", + ) + base_teacher_model: Optional[str] = Field( + default=None, + description="""The base teacher model that is being distilled. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/tuning#supported_models).""", + ) + hyper_parameters: Optional[DistillationHyperParameters] = Field( + default=None, + description="""Optional. Hyperparameters for Distillation.""", + ) + pipeline_root_directory: Optional[str] = Field( + default=None, + description="""Deprecated. A path in a Cloud Storage bucket, which will be treated as the root output directory of the distillation pipeline. It is used by the system to generate the paths of output artifacts.""", + ) + student_model: Optional[str] = Field( + default=None, + description="""The student model that is being tuned, e.g., "google/gemma-2b-1.1-it". Deprecated. Use base_model instead.""", + ) + training_dataset_uri: Optional[str] = Field( + default=None, + description="""Deprecated. Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file.""", + ) + tuned_teacher_model_source: Optional[str] = Field( + default=None, + description="""The resource name of the Tuned teacher model. Format: `projects/{project}/locations/{location}/models/{model}`.""", + ) + validation_dataset_uri: Optional[str] = Field( + default=None, + description="""Optional. Cloud Storage path to file containing validation dataset for tuning. The dataset must be formatted as a JSONL file.""", + ) + tuning_mode: Optional[TuningMode] = Field( + default=None, description="""Tuning mode for tuning.""" + ) + + +class DistillationSpecDict(TypedDict, total=False): + """Distillation tuning spec for tuning.""" + + prompt_dataset_uri: Optional[str] + """The GCS URI of the prompt dataset to use during distillation.""" + + base_teacher_model: Optional[str] + """The base teacher model that is being distilled. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/tuning#supported_models).""" + + hyper_parameters: Optional[DistillationHyperParametersDict] + """Optional. Hyperparameters for Distillation.""" + + pipeline_root_directory: Optional[str] + """Deprecated. A path in a Cloud Storage bucket, which will be treated as the root output directory of the distillation pipeline. It is used by the system to generate the paths of output artifacts.""" + + student_model: Optional[str] + """The student model that is being tuned, e.g., "google/gemma-2b-1.1-it". Deprecated. Use base_model instead.""" + + training_dataset_uri: Optional[str] + """Deprecated. Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file.""" + + tuned_teacher_model_source: Optional[str] + """The resource name of the Tuned teacher model. Format: `projects/{project}/locations/{location}/models/{model}`.""" + + validation_dataset_uri: Optional[str] + """Optional. Cloud Storage path to file containing validation dataset for tuning. The dataset must be formatted as a JSONL file.""" + + tuning_mode: Optional[TuningMode] + """Tuning mode for tuning.""" + + +DistillationSpecOrDict = Union[DistillationSpec, DistillationSpecDict] + + +class GcsDestination(_common.BaseModel): + """The Google Cloud Storage location where the output is to be written to.""" + + output_uri_prefix: Optional[str] = Field( + default=None, + description="""Required. Google Cloud Storage URI to output directory. If the uri doesn't end with '/', a '/' will be automatically appended. The directory is created if it doesn't exist.""", + ) + + @pydantic.model_validator(mode='after') + def _validate_gcs_path(self) -> 'GcsDestination': + if self.output_uri_prefix and not self.output_uri_prefix.startswith( + 'gs://' + ): + raise ValueError( + 'output_uri_prefix must be a valid GCS path starting with "gs://".' + ) + return self + + +class GcsDestinationDict(TypedDict, total=False): + """The Google Cloud Storage location where the output is to be written to.""" + + output_uri_prefix: Optional[str] + """Required. Google Cloud Storage URI to output directory. If the uri doesn't end with '/', a '/' will be automatically appended. The directory is created if it doesn't exist.""" + + +GcsDestinationOrDict = Union[GcsDestination, GcsDestinationDict] + + +class OutputConfig(_common.BaseModel): + """Config for evaluation output.""" + + gcs_destination: Optional[GcsDestination] = Field( + default=None, + description="""Cloud storage destination for evaluation output.""", + ) + + +class OutputConfigDict(TypedDict, total=False): + """Config for evaluation output.""" + + gcs_destination: Optional[GcsDestinationDict] + """Cloud storage destination for evaluation output.""" + + +OutputConfigOrDict = Union[OutputConfig, OutputConfigDict] + + +class AutoraterConfig(_common.BaseModel): + """Autorater config used for evaluation.""" + + sampling_count: Optional[int] = Field( + default=None, + description="""Number of samples for each instance in the dataset. + If not specified, the default is 4. Minimum value is 1, maximum value + is 32.""", + ) + flip_enabled: Optional[bool] = Field( + default=None, + description="""Optional. Default is true. Whether to flip the candidate and baseline + responses. This is only applicable to the pairwise metric. If enabled, also + provide PairwiseMetricSpec.candidate_response_field_name and + PairwiseMetricSpec.baseline_response_field_name. When rendering + PairwiseMetricSpec.metric_prompt_template, the candidate and baseline + fields will be flipped for half of the samples to reduce bias.""", + ) + autorater_model: Optional[str] = Field( + default=None, + description="""The fully qualified name of the publisher model or tuned autorater + endpoint to use. + + Publisher model format: + `projects/{project}/locations/{location}/publishers/{publisher}/models/{model}` + + Tuned model endpoint format: + `projects/{project}/locations/{location}/endpoints/{endpoint}`""", + ) + generation_config: Optional[GenerationConfig] = Field( + default=None, + description="""Configuration options for model generation and outputs.""", + ) + + +class AutoraterConfigDict(TypedDict, total=False): + """Autorater config used for evaluation.""" + + sampling_count: Optional[int] + """Number of samples for each instance in the dataset. + If not specified, the default is 4. Minimum value is 1, maximum value + is 32.""" + + flip_enabled: Optional[bool] + """Optional. Default is true. Whether to flip the candidate and baseline + responses. This is only applicable to the pairwise metric. If enabled, also + provide PairwiseMetricSpec.candidate_response_field_name and + PairwiseMetricSpec.baseline_response_field_name. When rendering + PairwiseMetricSpec.metric_prompt_template, the candidate and baseline + fields will be flipped for half of the samples to reduce bias.""" + + autorater_model: Optional[str] + """The fully qualified name of the publisher model or tuned autorater + endpoint to use. + + Publisher model format: + `projects/{project}/locations/{location}/publishers/{publisher}/models/{model}` + + Tuned model endpoint format: + `projects/{project}/locations/{location}/endpoints/{endpoint}`""" + + generation_config: Optional[GenerationConfigDict] + """Configuration options for model generation and outputs.""" + + +AutoraterConfigOrDict = Union[AutoraterConfig, AutoraterConfigDict] + + +class EvaluationConfig(_common.BaseModel): + """Evaluation config for tuning.""" + + metrics: Optional[list[MetricUnion]] = Field( + default=None, description="""The metrics used for evaluation.""" + ) + output_config: Optional[OutputConfig] = Field( + default=None, description="""Config for evaluation output.""" + ) + autorater_config: Optional[AutoraterConfig] = Field( + default=None, description="""Autorater config for evaluation.""" + ) + inference_generation_config: Optional[GenerationConfig] = Field( + default=None, description="""Generation config for inference.""" + ) + + +class EvaluationConfigDict(TypedDict, total=False): + """Evaluation config for tuning.""" + + metrics: Optional[list[MetricUnionDict]] + """The metrics used for evaluation.""" + + output_config: Optional[OutputConfigDict] + """Config for evaluation output.""" + + autorater_config: Optional[AutoraterConfigDict] + """Autorater config for evaluation.""" + + inference_generation_config: Optional[GenerationConfigDict] + """Generation config for inference.""" + + +EvaluationConfigOrDict = Union[EvaluationConfig, EvaluationConfigDict] + + +class GoogleRpcStatus(_common.BaseModel): + """The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. + + It is used by [gRPC](https://github.com/grpc). Each `Status` message contains + three pieces of data: error code, error message, and error details. You can + find out more about this error model and how to work with it in the [API + Design Guide](https://cloud.google.com/apis/design/errors). This data type is + not supported in Gemini API. + """ + + code: Optional[int] = Field( + default=None, + description="""The status code, which should be an enum value of google.rpc.Code.""", + ) + details: Optional[list[dict[str, Any]]] = Field( + default=None, + description="""A list of messages that carry the error details. There is a common set of message types for APIs to use.""", + ) + message: Optional[str] = Field( + default=None, + description="""A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client.""", + ) + + +class GoogleRpcStatusDict(TypedDict, total=False): + """The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. + + It is used by [gRPC](https://github.com/grpc). Each `Status` message contains + three pieces of data: error code, error message, and error details. You can + find out more about this error model and how to work with it in the [API + Design Guide](https://cloud.google.com/apis/design/errors). This data type is + not supported in Gemini API. + """ + + code: Optional[int] + """The status code, which should be an enum value of google.rpc.Code.""" + + details: Optional[list[dict[str, Any]]] + """A list of messages that carry the error details. There is a common set of message types for APIs to use.""" + + message: Optional[str] + """A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client.""" + + +GoogleRpcStatusOrDict = Union[GoogleRpcStatus, GoogleRpcStatusDict] + + +class PreTunedModel(_common.BaseModel): + """A pre-tuned model for continuous tuning. + + This data type is not supported in Gemini API. + """ + + base_model: Optional[str] = Field( + default=None, + description="""Output only. The name of the base model this PreTunedModel was tuned from.""", + ) + checkpoint_id: Optional[str] = Field( + default=None, + description="""Optional. The source checkpoint id. If not specified, the default checkpoint will be used.""", + ) + tuned_model_name: Optional[str] = Field( + default=None, + description="""The resource name of the Model. E.g., a model resource name with a specified version id or alias: `projects/{project}/locations/{location}/models/{model}@{version_id}` `projects/{project}/locations/{location}/models/{model}@{alias}` Or, omit the version id to use the default version: `projects/{project}/locations/{location}/models/{model}`""", + ) + + +class PreTunedModelDict(TypedDict, total=False): + """A pre-tuned model for continuous tuning. + + This data type is not supported in Gemini API. + """ + + base_model: Optional[str] + """Output only. The name of the base model this PreTunedModel was tuned from.""" + + checkpoint_id: Optional[str] + """Optional. The source checkpoint id. If not specified, the default checkpoint will be used.""" + + tuned_model_name: Optional[str] + """The resource name of the Model. E.g., a model resource name with a specified version id or alias: `projects/{project}/locations/{location}/models/{model}@{version_id}` `projects/{project}/locations/{location}/models/{model}@{alias}` Or, omit the version id to use the default version: `projects/{project}/locations/{location}/models/{model}`""" + + +PreTunedModelOrDict = Union[PreTunedModel, PreTunedModelDict] + + +class DatasetDistributionDistributionBucket(_common.BaseModel): + """Dataset bucket used to create a histogram for the distribution given a population of values. + + This data type is not supported in Gemini API. + """ + + count: Optional[int] = Field( + default=None, + description="""Output only. Number of values in the bucket.""", + ) + left: Optional[float] = Field( + default=None, description="""Output only. Left bound of the bucket.""" + ) + right: Optional[float] = Field( + default=None, description="""Output only. Right bound of the bucket.""" + ) + + +class DatasetDistributionDistributionBucketDict(TypedDict, total=False): + """Dataset bucket used to create a histogram for the distribution given a population of values. + + This data type is not supported in Gemini API. + """ + + count: Optional[int] + """Output only. Number of values in the bucket.""" + + left: Optional[float] + """Output only. Left bound of the bucket.""" + + right: Optional[float] + """Output only. Right bound of the bucket.""" + + +DatasetDistributionDistributionBucketOrDict = Union[ + DatasetDistributionDistributionBucket, + DatasetDistributionDistributionBucketDict, +] + + +class DatasetDistribution(_common.BaseModel): + """Distribution computed over a tuning dataset. + + This data type is not supported in Gemini API. + """ + + buckets: Optional[list[DatasetDistributionDistributionBucket]] = Field( + default=None, description="""Output only. Defines the histogram bucket.""" + ) + max: Optional[float] = Field( + default=None, + description="""Output only. The maximum of the population values.""", + ) + mean: Optional[float] = Field( + default=None, + description="""Output only. The arithmetic mean of the values in the population.""", + ) + median: Optional[float] = Field( + default=None, + description="""Output only. The median of the values in the population.""", + ) + min: Optional[float] = Field( + default=None, + description="""Output only. The minimum of the population values.""", + ) + p5: Optional[float] = Field( + default=None, + description="""Output only. The 5th percentile of the values in the population.""", + ) + p95: Optional[float] = Field( + default=None, + description="""Output only. The 95th percentile of the values in the population.""", + ) + sum: Optional[float] = Field( + default=None, + description="""Output only. Sum of a given population of values.""", + ) + + +class DatasetDistributionDict(TypedDict, total=False): + """Distribution computed over a tuning dataset. + + This data type is not supported in Gemini API. + """ + + buckets: Optional[list[DatasetDistributionDistributionBucketDict]] + """Output only. Defines the histogram bucket.""" + + max: Optional[float] + """Output only. The maximum of the population values.""" + + mean: Optional[float] + """Output only. The arithmetic mean of the values in the population.""" + + median: Optional[float] + """Output only. The median of the values in the population.""" + + min: Optional[float] + """Output only. The minimum of the population values.""" + + p5: Optional[float] + """Output only. The 5th percentile of the values in the population.""" + + p95: Optional[float] + """Output only. The 95th percentile of the values in the population.""" + + sum: Optional[float] + """Output only. Sum of a given population of values.""" + + +DatasetDistributionOrDict = Union[DatasetDistribution, DatasetDistributionDict] + + +class DatasetStats(_common.BaseModel): + """Statistics computed over a tuning dataset. + + This data type is not supported in Gemini API. + """ + + dropped_example_indices: Optional[list[int]] = Field( + default=None, + description="""Output only. A partial sample of the indices (starting from 1) of the dropped examples.""", + ) + dropped_example_reasons: Optional[list[str]] = Field( + default=None, + description="""Output only. For each index in `dropped_example_indices`, the user-facing reason why the example was dropped.""", + ) + total_billable_character_count: Optional[int] = Field( + default=None, + description="""Output only. Number of billable characters in the tuning dataset.""", + ) + total_tuning_character_count: Optional[int] = Field( + default=None, + description="""Output only. Number of tuning characters in the tuning dataset.""", + ) + tuning_dataset_example_count: Optional[int] = Field( + default=None, + description="""Output only. Number of examples in the tuning dataset.""", + ) + tuning_step_count: Optional[int] = Field( + default=None, + description="""Output only. Number of tuning steps for this Tuning Job.""", + ) + user_dataset_examples: Optional[list[Content]] = Field( + default=None, + description="""Output only. Sample user messages in the training dataset uri.""", + ) + user_input_token_distribution: Optional[DatasetDistribution] = Field( + default=None, + description="""Output only. Dataset distributions for the user input tokens.""", + ) + user_message_per_example_distribution: Optional[DatasetDistribution] = Field( + default=None, + description="""Output only. Dataset distributions for the messages per example.""", + ) + user_output_token_distribution: Optional[DatasetDistribution] = Field( + default=None, + description="""Output only. Dataset distributions for the user output tokens.""", + ) + + +class DatasetStatsDict(TypedDict, total=False): + """Statistics computed over a tuning dataset. + + This data type is not supported in Gemini API. + """ + + dropped_example_indices: Optional[list[int]] + """Output only. A partial sample of the indices (starting from 1) of the dropped examples.""" + + dropped_example_reasons: Optional[list[str]] + """Output only. For each index in `dropped_example_indices`, the user-facing reason why the example was dropped.""" + + total_billable_character_count: Optional[int] + """Output only. Number of billable characters in the tuning dataset.""" + + total_tuning_character_count: Optional[int] + """Output only. Number of tuning characters in the tuning dataset.""" + + tuning_dataset_example_count: Optional[int] + """Output only. Number of examples in the tuning dataset.""" + + tuning_step_count: Optional[int] + """Output only. Number of tuning steps for this Tuning Job.""" + + user_dataset_examples: Optional[list[ContentDict]] + """Output only. Sample user messages in the training dataset uri.""" + + user_input_token_distribution: Optional[DatasetDistributionDict] + """Output only. Dataset distributions for the user input tokens.""" + + user_message_per_example_distribution: Optional[DatasetDistributionDict] + """Output only. Dataset distributions for the messages per example.""" + + user_output_token_distribution: Optional[DatasetDistributionDict] + """Output only. Dataset distributions for the user output tokens.""" + + +DatasetStatsOrDict = Union[DatasetStats, DatasetStatsDict] + + +class DistillationDataStats(_common.BaseModel): + """Statistics for distillation prompt dataset. + + These statistics do not include the responses sampled from the teacher model. + This data type is not supported in Gemini API. + """ + + training_dataset_stats: Optional[DatasetStats] = Field( + default=None, + description="""Output only. Statistics computed for the training dataset.""", + ) + + +class DistillationDataStatsDict(TypedDict, total=False): + """Statistics for distillation prompt dataset. + + These statistics do not include the responses sampled from the teacher model. + This data type is not supported in Gemini API. + """ + + training_dataset_stats: Optional[DatasetStatsDict] + """Output only. Statistics computed for the training dataset.""" + + +DistillationDataStatsOrDict = Union[ + DistillationDataStats, DistillationDataStatsDict +] + + +class GeminiPreferenceExampleCompletion(_common.BaseModel): + """Completion and its preference score. + + This data type is not supported in Gemini API. + """ + + completion: Optional[Content] = Field( + default=None, + description="""Single turn completion for the given prompt.""", + ) + score: Optional[float] = Field( + default=None, description="""The score for the given completion.""" + ) + + +class GeminiPreferenceExampleCompletionDict(TypedDict, total=False): + """Completion and its preference score. + + This data type is not supported in Gemini API. + """ + + completion: Optional[ContentDict] + """Single turn completion for the given prompt.""" + + score: Optional[float] + """The score for the given completion.""" + + +GeminiPreferenceExampleCompletionOrDict = Union[ + GeminiPreferenceExampleCompletion, GeminiPreferenceExampleCompletionDict +] + + +class GeminiPreferenceExample(_common.BaseModel): + """Input example for preference optimization. + + This data type is not supported in Gemini API. + """ + + completions: Optional[list[GeminiPreferenceExampleCompletion]] = Field( + default=None, description="""List of completions for a given prompt.""" + ) + contents: Optional[list[Content]] = Field( + default=None, + description="""Multi-turn contents that represents the Prompt.""", + ) + + +class GeminiPreferenceExampleDict(TypedDict, total=False): + """Input example for preference optimization. + + This data type is not supported in Gemini API. + """ + + completions: Optional[list[GeminiPreferenceExampleCompletionDict]] + """List of completions for a given prompt.""" + + contents: Optional[list[ContentDict]] + """Multi-turn contents that represents the Prompt.""" + + +GeminiPreferenceExampleOrDict = Union[ + GeminiPreferenceExample, GeminiPreferenceExampleDict +] + + +class PreferenceOptimizationDataStats(_common.BaseModel): + """Statistics computed for datasets used for preference optimization. + + This data type is not supported in Gemini API. + """ + + dropped_example_indices: Optional[list[int]] = Field( + default=None, + description="""Output only. A partial sample of the indices (starting from 1) of the dropped examples.""", + ) + dropped_example_reasons: Optional[list[str]] = Field( + default=None, + description="""Output only. For each index in `dropped_example_indices`, the user-facing reason why the example was dropped.""", + ) + score_variance_per_example_distribution: Optional[DatasetDistribution] = ( + Field( + default=None, + description="""Output only. Dataset distributions for scores variance per example.""", + ) + ) + scores_distribution: Optional[DatasetDistribution] = Field( + default=None, + description="""Output only. Dataset distributions for scores.""", + ) + total_billable_token_count: Optional[int] = Field( + default=None, + description="""Output only. Number of billable tokens in the tuning dataset.""", + ) + tuning_dataset_example_count: Optional[int] = Field( + default=None, + description="""Output only. Number of examples in the tuning dataset.""", + ) + tuning_step_count: Optional[int] = Field( + default=None, + description="""Output only. Number of tuning steps for this Tuning Job.""", + ) + user_dataset_examples: Optional[list[GeminiPreferenceExample]] = Field( + default=None, + description="""Output only. Sample user examples in the training dataset.""", + ) + user_input_token_distribution: Optional[DatasetDistribution] = Field( + default=None, + description="""Output only. Dataset distributions for the user input tokens.""", + ) + user_output_token_distribution: Optional[DatasetDistribution] = Field( + default=None, + description="""Output only. Dataset distributions for the user output tokens.""", + ) + + +class PreferenceOptimizationDataStatsDict(TypedDict, total=False): + """Statistics computed for datasets used for preference optimization. + + This data type is not supported in Gemini API. + """ + + dropped_example_indices: Optional[list[int]] + """Output only. A partial sample of the indices (starting from 1) of the dropped examples.""" + + dropped_example_reasons: Optional[list[str]] + """Output only. For each index in `dropped_example_indices`, the user-facing reason why the example was dropped.""" + + score_variance_per_example_distribution: Optional[DatasetDistributionDict] + """Output only. Dataset distributions for scores variance per example.""" + + scores_distribution: Optional[DatasetDistributionDict] + """Output only. Dataset distributions for scores.""" + + total_billable_token_count: Optional[int] + """Output only. Number of billable tokens in the tuning dataset.""" + + tuning_dataset_example_count: Optional[int] + """Output only. Number of examples in the tuning dataset.""" + + tuning_step_count: Optional[int] + """Output only. Number of tuning steps for this Tuning Job.""" + + user_dataset_examples: Optional[list[GeminiPreferenceExampleDict]] + """Output only. Sample user examples in the training dataset.""" + + user_input_token_distribution: Optional[DatasetDistributionDict] + """Output only. Dataset distributions for the user input tokens.""" + + user_output_token_distribution: Optional[DatasetDistributionDict] + """Output only. Dataset distributions for the user output tokens.""" + + +PreferenceOptimizationDataStatsOrDict = Union[ + PreferenceOptimizationDataStats, PreferenceOptimizationDataStatsDict +] + + +class SupervisedTuningDatasetDistributionDatasetBucket(_common.BaseModel): + """Dataset bucket used to create a histogram for the distribution given a population of values. + + This data type is not supported in Gemini API. + """ + + count: Optional[float] = Field( + default=None, + description="""Output only. Number of values in the bucket.""", + ) + left: Optional[float] = Field( + default=None, description="""Output only. Left bound of the bucket.""" + ) + right: Optional[float] = Field( + default=None, description="""Output only. Right bound of the bucket.""" + ) + + +class SupervisedTuningDatasetDistributionDatasetBucketDict( + TypedDict, total=False +): + """Dataset bucket used to create a histogram for the distribution given a population of values. + + This data type is not supported in Gemini API. + """ + + count: Optional[float] + """Output only. Number of values in the bucket.""" + + left: Optional[float] + """Output only. Left bound of the bucket.""" + + right: Optional[float] + """Output only. Right bound of the bucket.""" + + +SupervisedTuningDatasetDistributionDatasetBucketOrDict = Union[ + SupervisedTuningDatasetDistributionDatasetBucket, + SupervisedTuningDatasetDistributionDatasetBucketDict, +] + + +class SupervisedTuningDatasetDistribution(_common.BaseModel): + """Dataset distribution for Supervised Tuning. + + This data type is not supported in Gemini API. + """ + + billable_sum: Optional[int] = Field( + default=None, + description="""Output only. Sum of a given population of values that are billable.""", + ) + buckets: Optional[list[SupervisedTuningDatasetDistributionDatasetBucket]] = ( + Field( + default=None, + description="""Output only. Defines the histogram bucket.""", + ) + ) + max: Optional[float] = Field( + default=None, + description="""Output only. The maximum of the population values.""", + ) + mean: Optional[float] = Field( + default=None, + description="""Output only. The arithmetic mean of the values in the population.""", + ) + median: Optional[float] = Field( + default=None, + description="""Output only. The median of the values in the population.""", + ) + min: Optional[float] = Field( + default=None, + description="""Output only. The minimum of the population values.""", + ) + p5: Optional[float] = Field( + default=None, + description="""Output only. The 5th percentile of the values in the population.""", + ) + p95: Optional[float] = Field( + default=None, + description="""Output only. The 95th percentile of the values in the population.""", + ) + sum: Optional[int] = Field( + default=None, + description="""Output only. Sum of a given population of values.""", + ) + + +class SupervisedTuningDatasetDistributionDict(TypedDict, total=False): + """Dataset distribution for Supervised Tuning. + + This data type is not supported in Gemini API. + """ + + billable_sum: Optional[int] + """Output only. Sum of a given population of values that are billable.""" + + buckets: Optional[list[SupervisedTuningDatasetDistributionDatasetBucketDict]] + """Output only. Defines the histogram bucket.""" + + max: Optional[float] + """Output only. The maximum of the population values.""" + + mean: Optional[float] + """Output only. The arithmetic mean of the values in the population.""" + + median: Optional[float] + """Output only. The median of the values in the population.""" + + min: Optional[float] + """Output only. The minimum of the population values.""" + + p5: Optional[float] + """Output only. The 5th percentile of the values in the population.""" + + p95: Optional[float] + """Output only. The 95th percentile of the values in the population.""" + + sum: Optional[int] + """Output only. Sum of a given population of values.""" + + +SupervisedTuningDatasetDistributionOrDict = Union[ + SupervisedTuningDatasetDistribution, SupervisedTuningDatasetDistributionDict +] + + +class SupervisedTuningDataStats(_common.BaseModel): + """Tuning data statistics for Supervised Tuning. + + This data type is not supported in Gemini API. + """ + + dropped_example_reasons: Optional[list[str]] = Field( + default=None, + description="""Output only. For each index in `truncated_example_indices`, the user-facing reason why the example was dropped.""", + ) + total_billable_character_count: Optional[int] = Field( + default=None, + description="""Output only. Number of billable characters in the tuning dataset.""", + ) + total_billable_token_count: Optional[int] = Field( + default=None, + description="""Output only. Number of billable tokens in the tuning dataset.""", + ) + total_truncated_example_count: Optional[int] = Field( + default=None, + description="""Output only. The number of examples in the dataset that have been dropped. An example can be dropped for reasons including: too many tokens, contains an invalid image, contains too many images, etc.""", + ) + total_tuning_character_count: Optional[int] = Field( + default=None, + description="""Output only. Number of tuning characters in the tuning dataset.""", + ) + truncated_example_indices: Optional[list[int]] = Field( + default=None, + description="""Output only. A partial sample of the indices (starting from 1) of the dropped examples.""", + ) + tuning_dataset_example_count: Optional[int] = Field( + default=None, + description="""Output only. Number of examples in the tuning dataset.""", + ) + tuning_step_count: Optional[int] = Field( + default=None, + description="""Output only. Number of tuning steps for this Tuning Job.""", + ) + user_dataset_examples: Optional[list[Content]] = Field( + default=None, + description="""Output only. Sample user messages in the training dataset uri.""", + ) + user_input_token_distribution: Optional[ + SupervisedTuningDatasetDistribution + ] = Field( + default=None, + description="""Output only. Dataset distributions for the user input tokens.""", + ) + user_message_per_example_distribution: Optional[ + SupervisedTuningDatasetDistribution + ] = Field( + default=None, + description="""Output only. Dataset distributions for the messages per example.""", + ) + user_output_token_distribution: Optional[ + SupervisedTuningDatasetDistribution + ] = Field( + default=None, + description="""Output only. Dataset distributions for the user output tokens.""", + ) + + +class SupervisedTuningDataStatsDict(TypedDict, total=False): + """Tuning data statistics for Supervised Tuning. + + This data type is not supported in Gemini API. + """ + + dropped_example_reasons: Optional[list[str]] + """Output only. For each index in `truncated_example_indices`, the user-facing reason why the example was dropped.""" + + total_billable_character_count: Optional[int] + """Output only. Number of billable characters in the tuning dataset.""" + + total_billable_token_count: Optional[int] + """Output only. Number of billable tokens in the tuning dataset.""" + + total_truncated_example_count: Optional[int] + """Output only. The number of examples in the dataset that have been dropped. An example can be dropped for reasons including: too many tokens, contains an invalid image, contains too many images, etc.""" + + total_tuning_character_count: Optional[int] + """Output only. Number of tuning characters in the tuning dataset.""" + + truncated_example_indices: Optional[list[int]] + """Output only. A partial sample of the indices (starting from 1) of the dropped examples.""" + + tuning_dataset_example_count: Optional[int] + """Output only. Number of examples in the tuning dataset.""" + + tuning_step_count: Optional[int] + """Output only. Number of tuning steps for this Tuning Job.""" + + user_dataset_examples: Optional[list[ContentDict]] + """Output only. Sample user messages in the training dataset uri.""" + + user_input_token_distribution: Optional[ + SupervisedTuningDatasetDistributionDict + ] + """Output only. Dataset distributions for the user input tokens.""" + + user_message_per_example_distribution: Optional[ + SupervisedTuningDatasetDistributionDict + ] + """Output only. Dataset distributions for the messages per example.""" + + user_output_token_distribution: Optional[ + SupervisedTuningDatasetDistributionDict + ] + """Output only. Dataset distributions for the user output tokens.""" + + +SupervisedTuningDataStatsOrDict = Union[ + SupervisedTuningDataStats, SupervisedTuningDataStatsDict +] + + +class TuningDataStats(_common.BaseModel): + """The tuning data statistic values for TuningJob. + + This data type is not supported in Gemini API. + """ + + distillation_data_stats: Optional[DistillationDataStats] = Field( + default=None, + description="""Output only. Statistics for distillation prompt dataset. These statistics do not include the responses sampled from the teacher model.""", + ) + preference_optimization_data_stats: Optional[ + PreferenceOptimizationDataStats + ] = Field( + default=None, + description="""Output only. Statistics for preference optimization.""", + ) + supervised_tuning_data_stats: Optional[SupervisedTuningDataStats] = Field( + default=None, description="""The SFT Tuning data stats.""" + ) + + +class TuningDataStatsDict(TypedDict, total=False): + """The tuning data statistic values for TuningJob. + + This data type is not supported in Gemini API. + """ + + distillation_data_stats: Optional[DistillationDataStatsDict] + """Output only. Statistics for distillation prompt dataset. These statistics do not include the responses sampled from the teacher model.""" + + preference_optimization_data_stats: Optional[ + PreferenceOptimizationDataStatsDict + ] + """Output only. Statistics for preference optimization.""" + + supervised_tuning_data_stats: Optional[SupervisedTuningDataStatsDict] + """The SFT Tuning data stats.""" + + +TuningDataStatsOrDict = Union[TuningDataStats, TuningDataStatsDict] + + +class EncryptionSpec(_common.BaseModel): + """Represents a customer-managed encryption key specification that can be applied to a Vertex AI resource. + + This data type is not supported in Gemini API. + """ + + kms_key_name: Optional[str] = Field( + default=None, + description="""Required. Resource name of the Cloud KMS key used to protect the resource. The Cloud KMS key must be in the same region as the resource. It must have the format `projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}`.""", + ) + + +class EncryptionSpecDict(TypedDict, total=False): + """Represents a customer-managed encryption key specification that can be applied to a Vertex AI resource. + + This data type is not supported in Gemini API. + """ + + kms_key_name: Optional[str] + """Required. Resource name of the Cloud KMS key used to protect the resource. The Cloud KMS key must be in the same region as the resource. It must have the format `projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}`.""" + + +EncryptionSpecOrDict = Union[EncryptionSpec, EncryptionSpecDict] + + +class PartnerModelTuningSpec(_common.BaseModel): + """Tuning spec for Partner models. + + This data type is not supported in Gemini API. + """ + + hyper_parameters: Optional[dict[str, Any]] = Field( + default=None, + description="""Hyperparameters for tuning. The accepted hyper_parameters and their valid range of values will differ depending on the base model.""", + ) + training_dataset_uri: Optional[str] = Field( + default=None, + description="""Required. Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file.""", + ) + validation_dataset_uri: Optional[str] = Field( + default=None, + description="""Optional. Cloud Storage path to file containing validation dataset for tuning. The dataset must be formatted as a JSONL file.""", + ) + + +class PartnerModelTuningSpecDict(TypedDict, total=False): + """Tuning spec for Partner models. + + This data type is not supported in Gemini API. + """ + + hyper_parameters: Optional[dict[str, Any]] + """Hyperparameters for tuning. The accepted hyper_parameters and their valid range of values will differ depending on the base model.""" + + training_dataset_uri: Optional[str] + """Required. Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file.""" + + validation_dataset_uri: Optional[str] + """Optional. Cloud Storage path to file containing validation dataset for tuning. The dataset must be formatted as a JSONL file.""" + + +PartnerModelTuningSpecOrDict = Union[ + PartnerModelTuningSpec, PartnerModelTuningSpecDict +] + + +class BleuMetricValue(_common.BaseModel): + """Bleu metric value for an instance. + + This data type is not supported in Gemini API. + """ + + score: Optional[float] = Field( + default=None, description="""Output only. Bleu score.""" + ) + + +class BleuMetricValueDict(TypedDict, total=False): + """Bleu metric value for an instance. + + This data type is not supported in Gemini API. + """ + + score: Optional[float] + """Output only. Bleu score.""" + + +BleuMetricValueOrDict = Union[BleuMetricValue, BleuMetricValueDict] + + +class CustomCodeExecutionResult(_common.BaseModel): + """Result for custom code execution metric. + + This data type is not supported in Gemini API. + """ + + score: Optional[float] = Field( + default=None, description="""Output only. Custom code execution score.""" + ) + + +class CustomCodeExecutionResultDict(TypedDict, total=False): + """Result for custom code execution metric. + + This data type is not supported in Gemini API. + """ + + score: Optional[float] + """Output only. Custom code execution score.""" + + +CustomCodeExecutionResultOrDict = Union[ + CustomCodeExecutionResult, CustomCodeExecutionResultDict +] + + +class ExactMatchMetricValue(_common.BaseModel): + """Exact match metric value for an instance. + + This data type is not supported in Gemini API. + """ + + score: Optional[float] = Field( + default=None, description="""Output only. Exact match score.""" + ) + + +class ExactMatchMetricValueDict(TypedDict, total=False): + """Exact match metric value for an instance. + + This data type is not supported in Gemini API. + """ + + score: Optional[float] + """Output only. Exact match score.""" + + +ExactMatchMetricValueOrDict = Union[ + ExactMatchMetricValue, ExactMatchMetricValueDict +] + + +class RawOutput(_common.BaseModel): + """Raw output. This data type is not supported in Gemini API.""" + + raw_output: Optional[list[str]] = Field( + default=None, description="""Output only. Raw output string.""" + ) + + +class RawOutputDict(TypedDict, total=False): + """Raw output. This data type is not supported in Gemini API.""" + + raw_output: Optional[list[str]] + """Output only. Raw output string.""" + + +RawOutputOrDict = Union[RawOutput, RawOutputDict] + + +class CustomOutput(_common.BaseModel): + """Spec for custom output. This data type is not supported in Gemini API.""" + + raw_outputs: Optional[RawOutput] = Field( + default=None, description="""Output only. List of raw output strings.""" + ) + + +class CustomOutputDict(TypedDict, total=False): + """Spec for custom output. This data type is not supported in Gemini API.""" + + raw_outputs: Optional[RawOutputDict] + """Output only. List of raw output strings.""" + + +CustomOutputOrDict = Union[CustomOutput, CustomOutputDict] + + +class PairwiseMetricResult(_common.BaseModel): + """Spec for pairwise metric result. + + This data type is not supported in Gemini API. + """ + + custom_output: Optional[CustomOutput] = Field( + default=None, description="""Output only. Spec for custom output.""" + ) + explanation: Optional[str] = Field( + default=None, + description="""Output only. Explanation for pairwise metric score.""", + ) + pairwise_choice: Optional[PairwiseChoice] = Field( + default=None, description="""Output only. Pairwise metric choice.""" + ) + + +class PairwiseMetricResultDict(TypedDict, total=False): + """Spec for pairwise metric result. + + This data type is not supported in Gemini API. + """ + + custom_output: Optional[CustomOutputDict] + """Output only. Spec for custom output.""" + + explanation: Optional[str] + """Output only. Explanation for pairwise metric score.""" + + pairwise_choice: Optional[PairwiseChoice] + """Output only. Pairwise metric choice.""" + + +PairwiseMetricResultOrDict = Union[ + PairwiseMetricResult, PairwiseMetricResultDict +] + + +class PointwiseMetricResult(_common.BaseModel): + """Spec for pointwise metric result. + + This data type is not supported in Gemini API. + """ + + custom_output: Optional[CustomOutput] = Field( + default=None, description="""Output only. Spec for custom output.""" + ) + explanation: Optional[str] = Field( + default=None, + description="""Output only. Explanation for pointwise metric score.""", + ) + score: Optional[float] = Field( + default=None, description="""Output only. Pointwise metric score.""" + ) + + +class PointwiseMetricResultDict(TypedDict, total=False): + """Spec for pointwise metric result. + + This data type is not supported in Gemini API. + """ + + custom_output: Optional[CustomOutputDict] + """Output only. Spec for custom output.""" + + explanation: Optional[str] + """Output only. Explanation for pointwise metric score.""" + + score: Optional[float] + """Output only. Pointwise metric score.""" + + +PointwiseMetricResultOrDict = Union[ + PointwiseMetricResult, PointwiseMetricResultDict +] + + +class RougeMetricValue(_common.BaseModel): + """Rouge metric value for an instance. + + This data type is not supported in Gemini API. + """ + + score: Optional[float] = Field( + default=None, description="""Output only. Rouge score.""" + ) + + +class RougeMetricValueDict(TypedDict, total=False): + """Rouge metric value for an instance. + + This data type is not supported in Gemini API. + """ + + score: Optional[float] + """Output only. Rouge score.""" + + +RougeMetricValueOrDict = Union[RougeMetricValue, RougeMetricValueDict] + + +class AggregationResult(_common.BaseModel): + """The aggregation result for a single metric. + + This data type is not supported in Gemini API. + """ + + aggregation_metric: Optional[AggregationMetric] = Field( + default=None, description="""Aggregation metric.""" + ) + bleu_metric_value: Optional[BleuMetricValue] = Field( + default=None, description="""Results for bleu metric.""" + ) + custom_code_execution_result: Optional[CustomCodeExecutionResult] = Field( + default=None, description="""Result for code execution metric.""" + ) + exact_match_metric_value: Optional[ExactMatchMetricValue] = Field( + default=None, description="""Results for exact match metric.""" + ) + pairwise_metric_result: Optional[PairwiseMetricResult] = Field( + default=None, description="""Result for pairwise metric.""" + ) + pointwise_metric_result: Optional[PointwiseMetricResult] = Field( + default=None, description="""Result for pointwise metric.""" + ) + rouge_metric_value: Optional[RougeMetricValue] = Field( + default=None, description="""Results for rouge metric.""" + ) + + +class AggregationResultDict(TypedDict, total=False): + """The aggregation result for a single metric. + + This data type is not supported in Gemini API. + """ + + aggregation_metric: Optional[AggregationMetric] + """Aggregation metric.""" + + bleu_metric_value: Optional[BleuMetricValueDict] + """Results for bleu metric.""" + + custom_code_execution_result: Optional[CustomCodeExecutionResultDict] + """Result for code execution metric.""" + + exact_match_metric_value: Optional[ExactMatchMetricValueDict] + """Results for exact match metric.""" + + pairwise_metric_result: Optional[PairwiseMetricResultDict] + """Result for pairwise metric.""" + + pointwise_metric_result: Optional[PointwiseMetricResultDict] + """Result for pointwise metric.""" + + rouge_metric_value: Optional[RougeMetricValueDict] + """Results for rouge metric.""" + + +AggregationResultOrDict = Union[AggregationResult, AggregationResultDict] + + +class BigQuerySource(_common.BaseModel): + """The BigQuery location for the input content. + + This data type is not supported in Gemini API. + """ + + input_uri: Optional[str] = Field( + default=None, + description="""Required. BigQuery URI to a table, up to 2000 characters long. Accepted forms: * BigQuery path. For example: `bq://projectId.bqDatasetId.bqTableId`.""", + ) + + +class BigQuerySourceDict(TypedDict, total=False): + """The BigQuery location for the input content. + + This data type is not supported in Gemini API. + """ + + input_uri: Optional[str] + """Required. BigQuery URI to a table, up to 2000 characters long. Accepted forms: * BigQuery path. For example: `bq://projectId.bqDatasetId.bqTableId`.""" + + +BigQuerySourceOrDict = Union[BigQuerySource, BigQuerySourceDict] + + +class GcsSource(_common.BaseModel): + """The Google Cloud Storage location for the input content. + + This data type is not supported in Gemini API. + """ + + uris: Optional[list[str]] = Field( + default=None, + description="""Required. Google Cloud Storage URI(-s) to the input file(s). May contain wildcards. For more information on wildcards, see https://cloud.google.com/storage/docs/wildcards.""", + ) + + +class GcsSourceDict(TypedDict, total=False): + """The Google Cloud Storage location for the input content. + + This data type is not supported in Gemini API. + """ + + uris: Optional[list[str]] + """Required. Google Cloud Storage URI(-s) to the input file(s). May contain wildcards. For more information on wildcards, see https://cloud.google.com/storage/docs/wildcards.""" + + +GcsSourceOrDict = Union[GcsSource, GcsSourceDict] + + +class EvaluationDataset(_common.BaseModel): + """The dataset used for evaluation. + + This data type is not supported in Gemini API. + """ + + bigquery_source: Optional[BigQuerySource] = Field( + default=None, description="""BigQuery source holds the dataset.""" + ) + gcs_source: Optional[GcsSource] = Field( + default=None, + description="""Cloud storage source holds the dataset. Currently only one Cloud Storage file path is supported.""", + ) + + +class EvaluationDatasetDict(TypedDict, total=False): + """The dataset used for evaluation. + + This data type is not supported in Gemini API. + """ + + bigquery_source: Optional[BigQuerySourceDict] + """BigQuery source holds the dataset.""" + + gcs_source: Optional[GcsSourceDict] + """Cloud storage source holds the dataset. Currently only one Cloud Storage file path is supported.""" + + +EvaluationDatasetOrDict = Union[EvaluationDataset, EvaluationDatasetDict] + + +class AggregationOutput(_common.BaseModel): + """The aggregation result for the entire dataset and all metrics. + + This data type is not supported in Gemini API. + """ + + aggregation_results: Optional[list[AggregationResult]] = Field( + default=None, description="""One AggregationResult per metric.""" + ) + dataset: Optional[EvaluationDataset] = Field( + default=None, + description="""The dataset used for evaluation & aggregation.""", + ) + + +class AggregationOutputDict(TypedDict, total=False): + """The aggregation result for the entire dataset and all metrics. + + This data type is not supported in Gemini API. + """ + + aggregation_results: Optional[list[AggregationResultDict]] + """One AggregationResult per metric.""" + + dataset: Optional[EvaluationDatasetDict] + """The dataset used for evaluation & aggregation.""" + + +AggregationOutputOrDict = Union[AggregationOutput, AggregationOutputDict] + + +class OutputInfo(_common.BaseModel): + """Describes the info for output of EvaluationService. + + This data type is not supported in Gemini API. + """ + + gcs_output_directory: Optional[str] = Field( + default=None, + description="""Output only. The full path of the Cloud Storage directory created, into which the evaluation results and aggregation results are written.""", + ) + + +class OutputInfoDict(TypedDict, total=False): + """Describes the info for output of EvaluationService. + + This data type is not supported in Gemini API. + """ + + gcs_output_directory: Optional[str] + """Output only. The full path of the Cloud Storage directory created, into which the evaluation results and aggregation results are written.""" + + +OutputInfoOrDict = Union[OutputInfo, OutputInfoDict] + + +class EvaluateDatasetResponse(_common.BaseModel): + """The results from an evaluation run performed by the EvaluationService. + + This data type is not supported in Gemini API. + """ + + aggregation_output: Optional[AggregationOutput] = Field( + default=None, + description="""Output only. Aggregation statistics derived from results of EvaluationService.""", + ) + output_info: Optional[OutputInfo] = Field( + default=None, + description="""Output only. Output info for EvaluationService.""", + ) + + +class EvaluateDatasetResponseDict(TypedDict, total=False): + """The results from an evaluation run performed by the EvaluationService. + + This data type is not supported in Gemini API. + """ + + aggregation_output: Optional[AggregationOutputDict] + """Output only. Aggregation statistics derived from results of EvaluationService.""" + + output_info: Optional[OutputInfoDict] + """Output only. Output info for EvaluationService.""" + + +EvaluateDatasetResponseOrDict = Union[ + EvaluateDatasetResponse, EvaluateDatasetResponseDict +] + + +class EvaluateDatasetRun(_common.BaseModel): + """Evaluate Dataset Run Result for Tuning Job. + + This data type is not supported in Gemini API. + """ + + checkpoint_id: Optional[str] = Field( + default=None, + description="""Output only. The checkpoint id used in the evaluation run. Only populated when evaluating checkpoints.""", + ) + error: Optional[GoogleRpcStatus] = Field( + default=None, + description="""Output only. The error of the evaluation run if any.""", + ) + evaluate_dataset_response: Optional[EvaluateDatasetResponse] = Field( + default=None, + description="""Output only. Results for EvaluationService.""", + ) + evaluation_run: Optional[str] = Field( + default=None, + description="""Output only. The resource name of the evaluation run. Format: `projects/{project}/locations/{location}/evaluationRuns/{evaluation_run_id}`.""", + ) + operation_name: Optional[str] = Field( + default=None, + description="""Output only. Deprecated: The updated architecture uses evaluation_run instead.""", + ) + + +class EvaluateDatasetRunDict(TypedDict, total=False): + """Evaluate Dataset Run Result for Tuning Job. + + This data type is not supported in Gemini API. + """ + + checkpoint_id: Optional[str] + """Output only. The checkpoint id used in the evaluation run. Only populated when evaluating checkpoints.""" + + error: Optional[GoogleRpcStatusDict] + """Output only. The error of the evaluation run if any.""" + + evaluate_dataset_response: Optional[EvaluateDatasetResponseDict] + """Output only. Results for EvaluationService.""" + + evaluation_run: Optional[str] + """Output only. The resource name of the evaluation run. Format: `projects/{project}/locations/{location}/evaluationRuns/{evaluation_run_id}`.""" + + operation_name: Optional[str] + """Output only. Deprecated: The updated architecture uses evaluation_run instead.""" + + +EvaluateDatasetRunOrDict = Union[EvaluateDatasetRun, EvaluateDatasetRunDict] + + +class FullFineTuningSpec(_common.BaseModel): + """Tuning Spec for Full Fine Tuning. + + This data type is not supported in Gemini API. + """ + + hyper_parameters: Optional[SupervisedHyperParameters] = Field( + default=None, + description="""Optional. Hyperparameters for Full Fine Tuning.""", + ) + training_dataset_uri: Optional[str] = Field( + default=None, + description="""Required. Training dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset.""", + ) + validation_dataset_uri: Optional[str] = Field( + default=None, + description="""Optional. Validation dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset.""", + ) + + +class FullFineTuningSpecDict(TypedDict, total=False): + """Tuning Spec for Full Fine Tuning. + + This data type is not supported in Gemini API. + """ + + hyper_parameters: Optional[SupervisedHyperParametersDict] + """Optional. Hyperparameters for Full Fine Tuning.""" + + training_dataset_uri: Optional[str] + """Required. Training dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset.""" + + validation_dataset_uri: Optional[str] + """Optional. Validation dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset.""" + + +FullFineTuningSpecOrDict = Union[FullFineTuningSpec, FullFineTuningSpecDict] + + +class VeoHyperParameters(_common.BaseModel): + """Hyperparameters for Veo. This data type is not supported in Gemini API.""" + + epoch_count: Optional[int] = Field( + default=None, + description="""Optional. Number of complete passes the model makes over the entire training dataset during training.""", + ) + learning_rate_multiplier: Optional[float] = Field( + default=None, + description="""Optional. Multiplier for adjusting the default learning rate.""", + ) + tuning_task: Optional[TuningTask] = Field( + default=None, + description="""Optional. The tuning task. Either I2V or T2V.""", + ) + veo_data_mixture_ratio: Optional[float] = Field( + default=None, + description="""Optional. The ratio of Google internal dataset to use in the training mixture, in range of `[0, 1)`. If `0.2`, it means 20% of Google internal dataset and 80% of user dataset will be used for training. If not set, the default value is 0.1.""", + ) + + +class VeoHyperParametersDict(TypedDict, total=False): + """Hyperparameters for Veo. This data type is not supported in Gemini API.""" + + epoch_count: Optional[int] + """Optional. Number of complete passes the model makes over the entire training dataset during training.""" + + learning_rate_multiplier: Optional[float] + """Optional. Multiplier for adjusting the default learning rate.""" + + tuning_task: Optional[TuningTask] + """Optional. The tuning task. Either I2V or T2V.""" + + veo_data_mixture_ratio: Optional[float] + """Optional. The ratio of Google internal dataset to use in the training mixture, in range of `[0, 1)`. If `0.2`, it means 20% of Google internal dataset and 80% of user dataset will be used for training. If not set, the default value is 0.1.""" + + +VeoHyperParametersOrDict = Union[VeoHyperParameters, VeoHyperParametersDict] + + +class VeoTuningSpec(_common.BaseModel): + """Tuning Spec for Veo Model Tuning. + + This data type is not supported in Gemini API. + """ + + hyper_parameters: Optional[VeoHyperParameters] = Field( + default=None, description="""Optional. Hyperparameters for Veo.""" + ) + training_dataset_uri: Optional[str] = Field( + default=None, + description="""Required. Training dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset.""", + ) + validation_dataset_uri: Optional[str] = Field( + default=None, + description="""Optional. Validation dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset.""", + ) + + +class VeoTuningSpecDict(TypedDict, total=False): + """Tuning Spec for Veo Model Tuning. + + This data type is not supported in Gemini API. + """ + + hyper_parameters: Optional[VeoHyperParametersDict] + """Optional. Hyperparameters for Veo.""" + + training_dataset_uri: Optional[str] + """Required. Training dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset.""" + + validation_dataset_uri: Optional[str] + """Optional. Validation dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset.""" + + +VeoTuningSpecOrDict = Union[VeoTuningSpec, VeoTuningSpecDict] + + +class DistillationSamplingSpec(_common.BaseModel): + """Spec for creating a distilled dataset in Vertex Dataset. + + This data type is not supported in Gemini API. + """ + + base_teacher_model: Optional[str] = Field( + default=None, + description="""Optional. The base teacher model that is being distilled. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/tuning#supported_models).""", + ) + tuned_teacher_model_source: Optional[str] = Field( + default=None, + description="""Optional. The resource name of the Tuned teacher model. Format: `projects/{project}/locations/{location}/models/{model}`.""", + ) + validation_dataset_uri: Optional[str] = Field( + default=None, + description="""Optional. Cloud Storage path to file containing validation dataset for distillation. The dataset must be formatted as a JSONL file.""", + ) + + +class DistillationSamplingSpecDict(TypedDict, total=False): + """Spec for creating a distilled dataset in Vertex Dataset. + + This data type is not supported in Gemini API. + """ + + base_teacher_model: Optional[str] + """Optional. The base teacher model that is being distilled. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/tuning#supported_models).""" + + tuned_teacher_model_source: Optional[str] + """Optional. The resource name of the Tuned teacher model. Format: `projects/{project}/locations/{location}/models/{model}`.""" + + validation_dataset_uri: Optional[str] + """Optional. Cloud Storage path to file containing validation dataset for distillation. The dataset must be formatted as a JSONL file.""" + + +DistillationSamplingSpecOrDict = Union[ + DistillationSamplingSpec, DistillationSamplingSpecDict +] + + +class TuningJobMetadata(_common.BaseModel): + """Tuning job metadata. This data type is not supported in Gemini API.""" + + completed_epoch_count: Optional[int] = Field( + default=None, + description="""Output only. The number of epochs that have been completed.""", + ) + completed_step_count: Optional[int] = Field( + default=None, + description="""Output only. The number of steps that have been completed. Set for Multi-Step RL.""", + ) + + +class TuningJobMetadataDict(TypedDict, total=False): + """Tuning job metadata. This data type is not supported in Gemini API.""" + + completed_epoch_count: Optional[int] + """Output only. The number of epochs that have been completed.""" + + completed_step_count: Optional[int] + """Output only. The number of steps that have been completed. Set for Multi-Step RL.""" + + +TuningJobMetadataOrDict = Union[TuningJobMetadata, TuningJobMetadataDict] + + +class TuningJob(_common.BaseModel): + """A tuning job.""" + + sdk_http_response: Optional[HttpResponse] = Field( + default=None, description="""Used to retain the full HTTP response.""" + ) + name: Optional[str] = Field( + default=None, + description="""Output only. Identifier. Resource name of a TuningJob. Format: `projects/{project}/locations/{location}/tuningJobs/{tuning_job}`""", + ) + state: Optional[JobState] = Field( + default=None, + description="""Output only. The detailed state of the job.""", + ) + create_time: Optional[datetime.datetime] = Field( + default=None, + description="""Output only. Time when the TuningJob was created.""", + ) + start_time: Optional[datetime.datetime] = Field( + default=None, + description="""Output only. Time when the TuningJob for the first time entered the `JOB_STATE_RUNNING` state.""", + ) + end_time: Optional[datetime.datetime] = Field( + default=None, + description="""Output only. Time when the TuningJob entered any of the following JobStates: `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED`, `JOB_STATE_CANCELLED`, `JOB_STATE_EXPIRED`.""", + ) + update_time: Optional[datetime.datetime] = Field( + default=None, + description="""Output only. Time when the TuningJob was most recently updated.""", + ) + error: Optional[GoogleRpcStatus] = Field( + default=None, + description="""Output only. Only populated when job's state is `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`.""", + ) + description: Optional[str] = Field( + default=None, + description="""Optional. The description of the TuningJob.""", + ) + base_model: Optional[str] = Field( + default=None, + description="""The base model that is being tuned. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/tuning#supported_models).""", + ) + tuned_model: Optional[TunedModel] = Field( + default=None, + description="""Output only. The tuned model resources associated with this TuningJob.""", + ) + pre_tuned_model: Optional[PreTunedModel] = Field( + default=None, description="""The pre-tuned model for continuous tuning.""" + ) + supervised_tuning_spec: Optional[SupervisedTuningSpec] = Field( + default=None, description="""Tuning Spec for Supervised Fine Tuning.""" + ) + preference_optimization_spec: Optional[PreferenceOptimizationSpec] = Field( + default=None, description="""Tuning Spec for Preference Optimization.""" + ) + distillation_spec: Optional[DistillationSpec] = Field( + default=None, description="""Tuning Spec for Distillation.""" + ) + tuning_data_stats: Optional[TuningDataStats] = Field( + default=None, + description="""Output only. The tuning data statistics associated with this TuningJob.""", + ) + encryption_spec: Optional[EncryptionSpec] = Field( + default=None, + description="""Customer-managed encryption key options for a TuningJob. If this is set, then all resources created by the TuningJob will be encrypted with the provided encryption key.""", + ) + partner_model_tuning_spec: Optional[PartnerModelTuningSpec] = Field( + default=None, + description="""Tuning Spec for open sourced and third party Partner models.""", + ) + evaluation_config: Optional[EvaluationConfig] = Field( + default=None, description="""Evaluation config for the tuning job.""" + ) + custom_base_model: Optional[str] = Field( + default=None, + description="""Optional. The user-provided path to custom model weights. Set this field to tune a custom model. The path must be a Cloud Storage directory that contains the model weights in .safetensors format along with associated model metadata files. If this field is set, the base_model field must still be set to indicate which base model the custom model is derived from. This feature is only available for open source models.""", + ) + evaluate_dataset_runs: Optional[list[EvaluateDatasetRun]] = Field( + default=None, + description="""Output only. Evaluation runs for the Tuning Job.""", + ) + experiment: Optional[str] = Field( + default=None, + description="""Output only. The Experiment associated with this TuningJob.""", + ) + full_fine_tuning_spec: Optional[FullFineTuningSpec] = Field( + default=None, description="""Tuning Spec for Full Fine Tuning.""" + ) + labels: Optional[dict[str, str]] = Field( + default=None, + description="""Optional. The labels with user-defined metadata to organize TuningJob and generated resources such as Model and Endpoint. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels.""", + ) + output_uri: Optional[str] = Field( + default=None, + description="""Optional. Cloud Storage path to the directory where tuning job outputs are written to. This field is only available and required for open source models.""", + ) + pipeline_job: Optional[str] = Field( + default=None, + description="""Output only. The resource name of the PipelineJob associated with the TuningJob. Format: `projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}`.""", + ) + service_account: Optional[str] = Field( + default=None, + description="""The service account that the tuningJob workload runs as. If not specified, the Vertex AI Secure Fine-Tuned Service Agent in the project will be used. See https://cloud.google.com/iam/docs/service-agents#vertex-ai-secure-fine-tuning-service-agent Users starting the pipeline must have the `iam.serviceAccounts.actAs` permission on this service account.""", + ) + tuned_model_display_name: Optional[str] = Field( + default=None, + description="""Optional. The display name of the TunedModel. The name can be up to 128 characters long and can consist of any UTF-8 characters. For continuous tuning, tuned_model_display_name will by default use the same display name as the pre-tuned model. If a new display name is provided, the tuning job will create a new model instead of a new version.""", + ) + tuning_job_state: Optional[TuningJobState] = Field( + default=None, + description="""Output only. The detail state of the tuning job (while the overall `JobState` is running).""", + ) + veo_tuning_spec: Optional[VeoTuningSpec] = Field( + default=None, description="""Tuning Spec for Veo Tuning.""" + ) + distillation_sampling_spec: Optional[DistillationSamplingSpec] = Field( + default=None, + description="""Optional. Spec for creating a distillation dataset.""", + ) + tuning_job_metadata: Optional[TuningJobMetadata] = Field( + default=None, description="""Output only. Tuning Job metadata.""" + ) + + @property + def has_ended(self) -> bool: + """Whether the tuning job has ended.""" + return self.state in JOB_STATES_ENDED + + @property + def has_succeeded(self) -> bool: + """Whether the tuning job has succeeded.""" + return self.state in JOB_STATES_SUCCEEDED + + +class TuningJobDict(TypedDict, total=False): + """A tuning job.""" + + sdk_http_response: Optional[HttpResponseDict] + """Used to retain the full HTTP response.""" + + name: Optional[str] + """Output only. Identifier. Resource name of a TuningJob. Format: `projects/{project}/locations/{location}/tuningJobs/{tuning_job}`""" + + state: Optional[JobState] + """Output only. The detailed state of the job.""" + + create_time: Optional[datetime.datetime] + """Output only. Time when the TuningJob was created.""" + + start_time: Optional[datetime.datetime] + """Output only. Time when the TuningJob for the first time entered the `JOB_STATE_RUNNING` state.""" + + end_time: Optional[datetime.datetime] + """Output only. Time when the TuningJob entered any of the following JobStates: `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED`, `JOB_STATE_CANCELLED`, `JOB_STATE_EXPIRED`.""" + + update_time: Optional[datetime.datetime] + """Output only. Time when the TuningJob was most recently updated.""" + + error: Optional[GoogleRpcStatusDict] + """Output only. Only populated when job's state is `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`.""" + + description: Optional[str] + """Optional. The description of the TuningJob.""" + + base_model: Optional[str] + """The base model that is being tuned. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/tuning#supported_models).""" + + tuned_model: Optional[TunedModelDict] + """Output only. The tuned model resources associated with this TuningJob.""" + + pre_tuned_model: Optional[PreTunedModelDict] + """The pre-tuned model for continuous tuning.""" + + supervised_tuning_spec: Optional[SupervisedTuningSpecDict] + """Tuning Spec for Supervised Fine Tuning.""" + + preference_optimization_spec: Optional[PreferenceOptimizationSpecDict] + """Tuning Spec for Preference Optimization.""" + + distillation_spec: Optional[DistillationSpecDict] + """Tuning Spec for Distillation.""" + + tuning_data_stats: Optional[TuningDataStatsDict] + """Output only. The tuning data statistics associated with this TuningJob.""" + + encryption_spec: Optional[EncryptionSpecDict] + """Customer-managed encryption key options for a TuningJob. If this is set, then all resources created by the TuningJob will be encrypted with the provided encryption key.""" + + partner_model_tuning_spec: Optional[PartnerModelTuningSpecDict] + """Tuning Spec for open sourced and third party Partner models.""" + + evaluation_config: Optional[EvaluationConfigDict] + """Evaluation config for the tuning job.""" + + custom_base_model: Optional[str] + """Optional. The user-provided path to custom model weights. Set this field to tune a custom model. The path must be a Cloud Storage directory that contains the model weights in .safetensors format along with associated model metadata files. If this field is set, the base_model field must still be set to indicate which base model the custom model is derived from. This feature is only available for open source models.""" + + evaluate_dataset_runs: Optional[list[EvaluateDatasetRunDict]] + """Output only. Evaluation runs for the Tuning Job.""" + + experiment: Optional[str] + """Output only. The Experiment associated with this TuningJob.""" + + full_fine_tuning_spec: Optional[FullFineTuningSpecDict] + """Tuning Spec for Full Fine Tuning.""" + + labels: Optional[dict[str, str]] + """Optional. The labels with user-defined metadata to organize TuningJob and generated resources such as Model and Endpoint. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels.""" + + output_uri: Optional[str] + """Optional. Cloud Storage path to the directory where tuning job outputs are written to. This field is only available and required for open source models.""" + + pipeline_job: Optional[str] + """Output only. The resource name of the PipelineJob associated with the TuningJob. Format: `projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}`.""" + + service_account: Optional[str] + """The service account that the tuningJob workload runs as. If not specified, the Vertex AI Secure Fine-Tuned Service Agent in the project will be used. See https://cloud.google.com/iam/docs/service-agents#vertex-ai-secure-fine-tuning-service-agent Users starting the pipeline must have the `iam.serviceAccounts.actAs` permission on this service account.""" + + tuned_model_display_name: Optional[str] + """Optional. The display name of the TunedModel. The name can be up to 128 characters long and can consist of any UTF-8 characters. For continuous tuning, tuned_model_display_name will by default use the same display name as the pre-tuned model. If a new display name is provided, the tuning job will create a new model instead of a new version.""" + + tuning_job_state: Optional[TuningJobState] + """Output only. The detail state of the tuning job (while the overall `JobState` is running).""" + + veo_tuning_spec: Optional[VeoTuningSpecDict] + """Tuning Spec for Veo Tuning.""" + + distillation_sampling_spec: Optional[DistillationSamplingSpecDict] + """Optional. Spec for creating a distillation dataset.""" + + tuning_job_metadata: Optional[TuningJobMetadataDict] + """Output only. Tuning Job metadata.""" + + +TuningJobOrDict = Union[TuningJob, TuningJobDict] + + +class ListTuningJobsConfig(_common.BaseModel): + """Configuration for the list tuning jobs method.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + page_size: Optional[int] = Field(default=None, description="""""") + page_token: Optional[str] = Field(default=None, description="""""") + filter: Optional[str] = Field(default=None, description="""""") + + +class ListTuningJobsConfigDict(TypedDict, total=False): + """Configuration for the list tuning jobs method.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + page_size: Optional[int] + """""" + + page_token: Optional[str] + """""" + + filter: Optional[str] + """""" + + +ListTuningJobsConfigOrDict = Union[ + ListTuningJobsConfig, ListTuningJobsConfigDict +] + + +class _ListTuningJobsParameters(_common.BaseModel): + """Parameters for the list tuning jobs method.""" + + config: Optional[ListTuningJobsConfig] = Field( + default=None, description="""""" + ) + + +class _ListTuningJobsParametersDict(TypedDict, total=False): + """Parameters for the list tuning jobs method.""" + + config: Optional[ListTuningJobsConfigDict] + """""" + + +_ListTuningJobsParametersOrDict = Union[ + _ListTuningJobsParameters, _ListTuningJobsParametersDict +] + + +class ListTuningJobsResponse(_common.BaseModel): + """Response for the list tuning jobs method.""" + + sdk_http_response: Optional[HttpResponse] = Field( + default=None, description="""Used to retain the full HTTP response.""" + ) + next_page_token: Optional[str] = Field( + default=None, + description="""A token to retrieve the next page of results. Pass this token in a subsequent [GenAiTuningService.ListTuningJobs] call to retrieve the next page of results.""", + ) + tuning_jobs: Optional[list[TuningJob]] = Field( + default=None, description="""The tuning jobs that match the request.""" + ) + + +class ListTuningJobsResponseDict(TypedDict, total=False): + """Response for the list tuning jobs method.""" + + sdk_http_response: Optional[HttpResponseDict] + """Used to retain the full HTTP response.""" + + next_page_token: Optional[str] + """A token to retrieve the next page of results. Pass this token in a subsequent [GenAiTuningService.ListTuningJobs] call to retrieve the next page of results.""" + + tuning_jobs: Optional[list[TuningJobDict]] + """The tuning jobs that match the request.""" + + +ListTuningJobsResponseOrDict = Union[ + ListTuningJobsResponse, ListTuningJobsResponseDict +] + + +class CancelTuningJobConfig(_common.BaseModel): + """Optional parameters for tunings.cancel method.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + + +class CancelTuningJobConfigDict(TypedDict, total=False): + """Optional parameters for tunings.cancel method.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + +CancelTuningJobConfigOrDict = Union[ + CancelTuningJobConfig, CancelTuningJobConfigDict +] + + +class _CancelTuningJobParameters(_common.BaseModel): + """Parameters for the cancel method.""" + + name: Optional[str] = Field( + default=None, description="""The resource name of the tuning job.""" + ) + config: Optional[CancelTuningJobConfig] = Field( + default=None, description="""Optional parameters for the request.""" + ) + + +class _CancelTuningJobParametersDict(TypedDict, total=False): + """Parameters for the cancel method.""" + + name: Optional[str] + """The resource name of the tuning job.""" + + config: Optional[CancelTuningJobConfigDict] + """Optional parameters for the request.""" + + +_CancelTuningJobParametersOrDict = Union[ + _CancelTuningJobParameters, _CancelTuningJobParametersDict +] + + +class CancelTuningJobResponse(_common.BaseModel): + """Empty response for tunings.cancel method.""" + + sdk_http_response: Optional[HttpResponse] = Field( + default=None, description="""Used to retain the full HTTP response.""" + ) + + +class CancelTuningJobResponseDict(TypedDict, total=False): + """Empty response for tunings.cancel method.""" + + sdk_http_response: Optional[HttpResponseDict] + """Used to retain the full HTTP response.""" + + +CancelTuningJobResponseOrDict = Union[ + CancelTuningJobResponse, CancelTuningJobResponseDict +] + + +class TuningExample(_common.BaseModel): + """A single example for tuning. + + This data type is not supported in Vertex AI. + """ + + output: Optional[str] = Field( + default=None, description="""Required. The expected model output.""" + ) + text_input: Optional[str] = Field( + default=None, description="""Optional. Text model input.""" + ) + + +class TuningExampleDict(TypedDict, total=False): + """A single example for tuning. + + This data type is not supported in Vertex AI. + """ + + output: Optional[str] + """Required. The expected model output.""" + + text_input: Optional[str] + """Optional. Text model input.""" + + +TuningExampleOrDict = Union[TuningExample, TuningExampleDict] + + +class TuningDataset(_common.BaseModel): + """Supervised fine-tuning training dataset.""" + + gcs_uri: Optional[str] = Field( + default=None, + description="""GCS URI of the file containing training dataset in JSONL format.""", + ) + vertex_dataset_resource: Optional[str] = Field( + default=None, + description="""The resource name of the Vertex Multimodal Dataset that is used as training dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'.""", + ) + examples: Optional[list[TuningExample]] = Field( + default=None, + description="""Inline examples with simple input/output text.""", + ) + + +class TuningDatasetDict(TypedDict, total=False): + """Supervised fine-tuning training dataset.""" + + gcs_uri: Optional[str] + """GCS URI of the file containing training dataset in JSONL format.""" + + vertex_dataset_resource: Optional[str] + """The resource name of the Vertex Multimodal Dataset that is used as training dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'.""" + + examples: Optional[list[TuningExampleDict]] + """Inline examples with simple input/output text.""" + + +TuningDatasetOrDict = Union[TuningDataset, TuningDatasetDict] + + +class TuningValidationDataset(_common.BaseModel): + + gcs_uri: Optional[str] = Field( + default=None, + description="""GCS URI of the file containing validation dataset in JSONL format.""", + ) + vertex_dataset_resource: Optional[str] = Field( + default=None, + description="""The resource name of the Vertex Multimodal Dataset that is used as validation dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'.""", + ) + + +class TuningValidationDatasetDict(TypedDict, total=False): + + gcs_uri: Optional[str] + """GCS URI of the file containing validation dataset in JSONL format.""" + + vertex_dataset_resource: Optional[str] + """The resource name of the Vertex Multimodal Dataset that is used as validation dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'.""" + + +TuningValidationDatasetOrDict = Union[ + TuningValidationDataset, TuningValidationDatasetDict +] + + +class CreateTuningJobConfig(_common.BaseModel): + """Fine-tuning job creation request - optional fields.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + method: Optional[TuningMethod] = Field( + default=None, + description="""The method to use for tuning (SUPERVISED_FINE_TUNING or PREFERENCE_TUNING or DISTILLATION). If not set, the default method (SFT) will be used.""", + ) + validation_dataset: Optional[TuningValidationDataset] = Field( + default=None, + description="""Validation dataset for tuning. The dataset must be formatted as a JSONL file.""", + ) + tuned_model_display_name: Optional[str] = Field( + default=None, + description="""The display name of the tuned Model. The name can be up to 128 characters long and can consist of any UTF-8 characters.""", + ) + description: Optional[str] = Field( + default=None, description="""The description of the TuningJob""" + ) + epoch_count: Optional[int] = Field( + default=None, + description="""Number of complete passes the model makes over the entire training dataset during training.""", + ) + learning_rate_multiplier: Optional[float] = Field( + default=None, + description="""Multiplier for adjusting the default learning rate. 1P models only. Mutually exclusive with learning_rate.""", + ) + export_last_checkpoint_only: Optional[bool] = Field( + default=None, + description="""If set to true, disable intermediate checkpoints and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints.""", + ) + pre_tuned_model_checkpoint_id: Optional[str] = Field( + default=None, + description="""The optional checkpoint id of the pre-tuned model to use for tuning, if applicable.""", + ) + adapter_size: Optional[AdapterSize] = Field( + default=None, description="""Adapter size for tuning.""" + ) + tuning_mode: Optional[TuningMode] = Field( + default=None, description="""Tuning mode for tuning.""" + ) + custom_base_model: Optional[str] = Field( + default=None, + description="""Custom base model for tuning. This is only supported for OSS models in Vertex.""", + ) + batch_size: Optional[int] = Field( + default=None, + description="""The batch size hyperparameter for tuning. This is only supported for OSS models in Vertex.""", + ) + learning_rate: Optional[float] = Field( + default=None, + description="""The learning rate for tuning. OSS models only. Mutually exclusive with learning_rate_multiplier.""", + ) + evaluation_config: Optional[EvaluationConfig] = Field( + default=None, description="""Evaluation config for the tuning job.""" + ) + labels: Optional[dict[str, str]] = Field( + default=None, + description="""Optional. The labels with user-defined metadata to organize TuningJob and generated resources such as Model and Endpoint. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels.""", + ) + beta: Optional[float] = Field( + default=None, + description="""Weight for KL Divergence regularization, Preference Optimization tuning only.""", + ) + base_teacher_model: Optional[str] = Field( + default=None, + description="""The base teacher model that is being distilled. Distillation only.""", + ) + tuned_teacher_model_source: Optional[str] = Field( + default=None, + description="""The resource name of the Tuned teacher model. Distillation only.""", + ) + sft_loss_weight_multiplier: Optional[float] = Field( + default=None, + description="""Multiplier for adjusting the weight of the SFT loss. Distillation only.""", + ) + output_uri: Optional[str] = Field( + default=None, + description="""The Google Cloud Storage location where the tuning job outputs are written.""", + ) + encryption_spec: Optional[EncryptionSpec] = Field( + default=None, + description="""The encryption spec of the tuning job. Customer-managed encryption key options for a TuningJob. If this is set, then all resources created by the TuningJob will be encrypted with provided encryption key.""", + ) + + +class CreateTuningJobConfigDict(TypedDict, total=False): + """Fine-tuning job creation request - optional fields.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + method: Optional[TuningMethod] + """The method to use for tuning (SUPERVISED_FINE_TUNING or PREFERENCE_TUNING or DISTILLATION). If not set, the default method (SFT) will be used.""" + + validation_dataset: Optional[TuningValidationDatasetDict] + """Validation dataset for tuning. The dataset must be formatted as a JSONL file.""" + + tuned_model_display_name: Optional[str] + """The display name of the tuned Model. The name can be up to 128 characters long and can consist of any UTF-8 characters.""" + + description: Optional[str] + """The description of the TuningJob""" + + epoch_count: Optional[int] + """Number of complete passes the model makes over the entire training dataset during training.""" + + learning_rate_multiplier: Optional[float] + """Multiplier for adjusting the default learning rate. 1P models only. Mutually exclusive with learning_rate.""" + + export_last_checkpoint_only: Optional[bool] + """If set to true, disable intermediate checkpoints and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints.""" + + pre_tuned_model_checkpoint_id: Optional[str] + """The optional checkpoint id of the pre-tuned model to use for tuning, if applicable.""" + + adapter_size: Optional[AdapterSize] + """Adapter size for tuning.""" + + tuning_mode: Optional[TuningMode] + """Tuning mode for tuning.""" + + custom_base_model: Optional[str] + """Custom base model for tuning. This is only supported for OSS models in Vertex.""" + + batch_size: Optional[int] + """The batch size hyperparameter for tuning. This is only supported for OSS models in Vertex.""" + + learning_rate: Optional[float] + """The learning rate for tuning. OSS models only. Mutually exclusive with learning_rate_multiplier.""" + + evaluation_config: Optional[EvaluationConfigDict] + """Evaluation config for the tuning job.""" + + labels: Optional[dict[str, str]] + """Optional. The labels with user-defined metadata to organize TuningJob and generated resources such as Model and Endpoint. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels.""" + + beta: Optional[float] + """Weight for KL Divergence regularization, Preference Optimization tuning only.""" + + base_teacher_model: Optional[str] + """The base teacher model that is being distilled. Distillation only.""" + + tuned_teacher_model_source: Optional[str] + """The resource name of the Tuned teacher model. Distillation only.""" + + sft_loss_weight_multiplier: Optional[float] + """Multiplier for adjusting the weight of the SFT loss. Distillation only.""" + + output_uri: Optional[str] + """The Google Cloud Storage location where the tuning job outputs are written.""" + + encryption_spec: Optional[EncryptionSpecDict] + """The encryption spec of the tuning job. Customer-managed encryption key options for a TuningJob. If this is set, then all resources created by the TuningJob will be encrypted with provided encryption key.""" + + +CreateTuningJobConfigOrDict = Union[ + CreateTuningJobConfig, CreateTuningJobConfigDict +] + + +class _CreateTuningJobParametersPrivate(_common.BaseModel): + """Fine-tuning job creation parameters - optional fields.""" + + base_model: Optional[str] = Field( + default=None, + description="""The base model that is being tuned, e.g., "gemini-2.5-flash".""", + ) + pre_tuned_model: Optional[PreTunedModel] = Field( + default=None, description="""The PreTunedModel that is being tuned.""" + ) + training_dataset: Optional[TuningDataset] = Field( + default=None, + description="""Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file.""", + ) + config: Optional[CreateTuningJobConfig] = Field( + default=None, description="""Configuration for the tuning job.""" + ) + + +class _CreateTuningJobParametersPrivateDict(TypedDict, total=False): + """Fine-tuning job creation parameters - optional fields.""" + + base_model: Optional[str] + """The base model that is being tuned, e.g., "gemini-2.5-flash".""" + + pre_tuned_model: Optional[PreTunedModelDict] + """The PreTunedModel that is being tuned.""" + + training_dataset: Optional[TuningDatasetDict] + """Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file.""" + + config: Optional[CreateTuningJobConfigDict] + """Configuration for the tuning job.""" + + +_CreateTuningJobParametersPrivateOrDict = Union[ + _CreateTuningJobParametersPrivate, _CreateTuningJobParametersPrivateDict +] + + +class TuningOperation(_common.BaseModel): + """A long-running operation.""" + + sdk_http_response: Optional[HttpResponse] = Field( + default=None, description="""Used to retain the full HTTP response.""" + ) + name: Optional[str] = Field( + default=None, + description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""", + ) + metadata: Optional[dict[str, Any]] = Field( + default=None, + description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.""", + ) + done: Optional[bool] = Field( + default=None, + description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""", + ) + error: Optional[dict[str, Any]] = Field( + default=None, + description="""The error result of the operation in case of failure or cancellation.""", + ) + + +class TuningOperationDict(TypedDict, total=False): + """A long-running operation.""" + + sdk_http_response: Optional[HttpResponseDict] + """Used to retain the full HTTP response.""" + + name: Optional[str] + """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""" + + metadata: Optional[dict[str, Any]] + """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.""" + + done: Optional[bool] + """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""" + + error: Optional[dict[str, Any]] + """The error result of the operation in case of failure or cancellation.""" + + +TuningOperationOrDict = Union[TuningOperation, TuningOperationDict] + + +class CreateCachedContentConfig(_common.BaseModel): + """Optional configuration for cached content creation.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + ttl: Optional[str] = Field( + default=None, + description="""The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: "3.5s".""", + ) + expire_time: Optional[datetime.datetime] = Field( + default=None, + description="""Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z.""", + ) + display_name: Optional[str] = Field( + default=None, + description="""The user-generated meaningful display name of the cached content. + """, + ) + contents: Optional[ContentListUnion] = Field( + default=None, + description="""The content to cache. + """, + ) + system_instruction: Optional[ContentUnion] = Field( + default=None, + description="""Developer set system instruction. + """, + ) + tools: Optional[list[Tool]] = Field( + default=None, + description="""A list of `Tools` the model may use to generate the next response. + """, + ) + tool_config: Optional[ToolConfig] = Field( + default=None, + description="""Configuration for the tools to use. This config is shared for all tools. + """, + ) + kms_key_name: Optional[str] = Field( + default=None, + description="""The Cloud KMS resource identifier of the customer managed + encryption key used to protect a resource. + The key needs to be in the same region as where the compute resource is + created. See + https://cloud.google.com/vertex-ai/docs/general/cmek for more + details. If this is set, then all created CachedContent objects + will be encrypted with the provided encryption key. + Allowed formats: projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key} + """, + ) + + +class CreateCachedContentConfigDict(TypedDict, total=False): + """Optional configuration for cached content creation.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + ttl: Optional[str] + """The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: "3.5s".""" + + expire_time: Optional[datetime.datetime] + """Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z.""" + + display_name: Optional[str] + """The user-generated meaningful display name of the cached content. + """ + + contents: Optional[ContentListUnionDict] + """The content to cache. + """ + + system_instruction: Optional[ContentUnionDict] + """Developer set system instruction. + """ + + tools: Optional[list[ToolDict]] + """A list of `Tools` the model may use to generate the next response. + """ + + tool_config: Optional[ToolConfigDict] + """Configuration for the tools to use. This config is shared for all tools. + """ + + kms_key_name: Optional[str] + """The Cloud KMS resource identifier of the customer managed + encryption key used to protect a resource. + The key needs to be in the same region as where the compute resource is + created. See + https://cloud.google.com/vertex-ai/docs/general/cmek for more + details. If this is set, then all created CachedContent objects + will be encrypted with the provided encryption key. + Allowed formats: projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key} + """ + + +CreateCachedContentConfigOrDict = Union[ + CreateCachedContentConfig, CreateCachedContentConfigDict +] + + +class _CreateCachedContentParameters(_common.BaseModel): + """Parameters for caches.create method.""" + + model: Optional[str] = Field( + default=None, + description="""ID of the model to use. Example: gemini-2.0-flash""", + ) + config: Optional[CreateCachedContentConfig] = Field( + default=None, + description="""Configuration that contains optional parameters. + """, + ) + + +class _CreateCachedContentParametersDict(TypedDict, total=False): + """Parameters for caches.create method.""" + + model: Optional[str] + """ID of the model to use. Example: gemini-2.0-flash""" + + config: Optional[CreateCachedContentConfigDict] + """Configuration that contains optional parameters. + """ + + +_CreateCachedContentParametersOrDict = Union[ + _CreateCachedContentParameters, _CreateCachedContentParametersDict +] + + +class CachedContentUsageMetadata(_common.BaseModel): + """Metadata on the usage of the cached content.""" + + audio_duration_seconds: Optional[int] = Field( + default=None, + description="""Duration of audio in seconds. This field is not supported in Gemini API.""", + ) + image_count: Optional[int] = Field( + default=None, + description="""Number of images. This field is not supported in Gemini API.""", + ) + text_count: Optional[int] = Field( + default=None, + description="""Number of text characters. This field is not supported in Gemini API.""", + ) + total_token_count: Optional[int] = Field( + default=None, + description="""Total number of tokens that the cached content consumes.""", + ) + video_duration_seconds: Optional[int] = Field( + default=None, + description="""Duration of video in seconds. This field is not supported in Gemini API.""", + ) + + +class CachedContentUsageMetadataDict(TypedDict, total=False): + """Metadata on the usage of the cached content.""" + + audio_duration_seconds: Optional[int] + """Duration of audio in seconds. This field is not supported in Gemini API.""" + + image_count: Optional[int] + """Number of images. This field is not supported in Gemini API.""" + + text_count: Optional[int] + """Number of text characters. This field is not supported in Gemini API.""" + + total_token_count: Optional[int] + """Total number of tokens that the cached content consumes.""" + + video_duration_seconds: Optional[int] + """Duration of video in seconds. This field is not supported in Gemini API.""" + + +CachedContentUsageMetadataOrDict = Union[ + CachedContentUsageMetadata, CachedContentUsageMetadataDict +] + + +class CachedContent(_common.BaseModel): + """A resource used in LLM queries for users to explicitly specify what to cache.""" + + name: Optional[str] = Field( + default=None, + description="""The server-generated resource name of the cached content.""", + ) + display_name: Optional[str] = Field( + default=None, + description="""The user-generated meaningful display name of the cached content.""", + ) + model: Optional[str] = Field( + default=None, + description="""The name of the publisher model to use for cached content.""", + ) + create_time: Optional[datetime.datetime] = Field( + default=None, description="""Creation time of the cache entry.""" + ) + update_time: Optional[datetime.datetime] = Field( + default=None, + description="""When the cache entry was last updated in UTC time.""", + ) + expire_time: Optional[datetime.datetime] = Field( + default=None, description="""Expiration time of the cached content.""" + ) + usage_metadata: Optional[CachedContentUsageMetadata] = Field( + default=None, + description="""Metadata on the usage of the cached content.""", + ) + + +class CachedContentDict(TypedDict, total=False): + """A resource used in LLM queries for users to explicitly specify what to cache.""" + + name: Optional[str] + """The server-generated resource name of the cached content.""" + + display_name: Optional[str] + """The user-generated meaningful display name of the cached content.""" + + model: Optional[str] + """The name of the publisher model to use for cached content.""" + + create_time: Optional[datetime.datetime] + """Creation time of the cache entry.""" + + update_time: Optional[datetime.datetime] + """When the cache entry was last updated in UTC time.""" + + expire_time: Optional[datetime.datetime] + """Expiration time of the cached content.""" + + usage_metadata: Optional[CachedContentUsageMetadataDict] + """Metadata on the usage of the cached content.""" + + +CachedContentOrDict = Union[CachedContent, CachedContentDict] + + +class GetCachedContentConfig(_common.BaseModel): + """Optional parameters for caches.get method.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + + +class GetCachedContentConfigDict(TypedDict, total=False): + """Optional parameters for caches.get method.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + +GetCachedContentConfigOrDict = Union[ + GetCachedContentConfig, GetCachedContentConfigDict +] + + +class _GetCachedContentParameters(_common.BaseModel): + """Parameters for caches.get method.""" + + name: Optional[str] = Field( + default=None, + description="""The server-generated resource name of the cached content. + """, + ) + config: Optional[GetCachedContentConfig] = Field( + default=None, + description="""Optional parameters for the request. + """, + ) + + +class _GetCachedContentParametersDict(TypedDict, total=False): + """Parameters for caches.get method.""" + + name: Optional[str] + """The server-generated resource name of the cached content. + """ + + config: Optional[GetCachedContentConfigDict] + """Optional parameters for the request. + """ + + +_GetCachedContentParametersOrDict = Union[ + _GetCachedContentParameters, _GetCachedContentParametersDict +] + + +class DeleteCachedContentConfig(_common.BaseModel): + """Optional parameters for caches.delete method.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + + +class DeleteCachedContentConfigDict(TypedDict, total=False): + """Optional parameters for caches.delete method.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + +DeleteCachedContentConfigOrDict = Union[ + DeleteCachedContentConfig, DeleteCachedContentConfigDict +] + + +class _DeleteCachedContentParameters(_common.BaseModel): + """Parameters for caches.delete method.""" + + name: Optional[str] = Field( + default=None, + description="""The server-generated resource name of the cached content. + """, + ) + config: Optional[DeleteCachedContentConfig] = Field( + default=None, + description="""Optional parameters for the request. + """, + ) + + +class _DeleteCachedContentParametersDict(TypedDict, total=False): + """Parameters for caches.delete method.""" + + name: Optional[str] + """The server-generated resource name of the cached content. + """ + + config: Optional[DeleteCachedContentConfigDict] + """Optional parameters for the request. + """ + + +_DeleteCachedContentParametersOrDict = Union[ + _DeleteCachedContentParameters, _DeleteCachedContentParametersDict +] + + +class DeleteCachedContentResponse(_common.BaseModel): + """Empty response for caches.delete method.""" + + sdk_http_response: Optional[HttpResponse] = Field( + default=None, description="""Used to retain the full HTTP response.""" + ) + + +class DeleteCachedContentResponseDict(TypedDict, total=False): + """Empty response for caches.delete method.""" + + sdk_http_response: Optional[HttpResponseDict] + """Used to retain the full HTTP response.""" + + +DeleteCachedContentResponseOrDict = Union[ + DeleteCachedContentResponse, DeleteCachedContentResponseDict +] + + +class UpdateCachedContentConfig(_common.BaseModel): + """Optional parameters for caches.update method.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + ttl: Optional[str] = Field( + default=None, + description="""The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: "3.5s".""", + ) + expire_time: Optional[datetime.datetime] = Field( + default=None, + description="""Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z.""", + ) + + +class UpdateCachedContentConfigDict(TypedDict, total=False): + """Optional parameters for caches.update method.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + ttl: Optional[str] + """The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: "3.5s".""" + + expire_time: Optional[datetime.datetime] + """Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z.""" + + +UpdateCachedContentConfigOrDict = Union[ + UpdateCachedContentConfig, UpdateCachedContentConfigDict +] + + +class _UpdateCachedContentParameters(_common.BaseModel): + + name: Optional[str] = Field( + default=None, + description="""The server-generated resource name of the cached content. + """, + ) + config: Optional[UpdateCachedContentConfig] = Field( + default=None, + description="""Configuration that contains optional parameters. + """, + ) + + +class _UpdateCachedContentParametersDict(TypedDict, total=False): + + name: Optional[str] + """The server-generated resource name of the cached content. + """ + + config: Optional[UpdateCachedContentConfigDict] + """Configuration that contains optional parameters. + """ + + +_UpdateCachedContentParametersOrDict = Union[ + _UpdateCachedContentParameters, _UpdateCachedContentParametersDict +] + + +class ListCachedContentsConfig(_common.BaseModel): + """Config for caches.list method.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + page_size: Optional[int] = Field(default=None, description="""""") + page_token: Optional[str] = Field(default=None, description="""""") + + +class ListCachedContentsConfigDict(TypedDict, total=False): + """Config for caches.list method.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + page_size: Optional[int] + """""" + + page_token: Optional[str] + """""" + + +ListCachedContentsConfigOrDict = Union[ + ListCachedContentsConfig, ListCachedContentsConfigDict +] + + +class _ListCachedContentsParameters(_common.BaseModel): + """Parameters for caches.list method.""" + + config: Optional[ListCachedContentsConfig] = Field( + default=None, + description="""Configuration that contains optional parameters. + """, + ) + + +class _ListCachedContentsParametersDict(TypedDict, total=False): + """Parameters for caches.list method.""" + + config: Optional[ListCachedContentsConfigDict] + """Configuration that contains optional parameters. + """ + + +_ListCachedContentsParametersOrDict = Union[ + _ListCachedContentsParameters, _ListCachedContentsParametersDict +] + + +class ListCachedContentsResponse(_common.BaseModel): + + sdk_http_response: Optional[HttpResponse] = Field( + default=None, description="""Used to retain the full HTTP response.""" + ) + next_page_token: Optional[str] = Field(default=None, description="""""") + cached_contents: Optional[list[CachedContent]] = Field( + default=None, + description="""List of cached contents. + """, + ) + + +class ListCachedContentsResponseDict(TypedDict, total=False): + + sdk_http_response: Optional[HttpResponseDict] + """Used to retain the full HTTP response.""" + + next_page_token: Optional[str] + """""" + + cached_contents: Optional[list[CachedContentDict]] + """List of cached contents. + """ + + +ListCachedContentsResponseOrDict = Union[ + ListCachedContentsResponse, ListCachedContentsResponseDict +] + + +class GetDocumentConfig(_common.BaseModel): + """Optional Config.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + + +class GetDocumentConfigDict(TypedDict, total=False): + """Optional Config.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + +GetDocumentConfigOrDict = Union[GetDocumentConfig, GetDocumentConfigDict] + + +class _GetDocumentParameters(_common.BaseModel): + """Parameters for documents.get.""" + + name: Optional[str] = Field( + default=None, + description="""The resource name of the Document. + Example: fileSearchStores/file-search-store-foo/documents/documents-bar""", + ) + config: Optional[GetDocumentConfig] = Field( + default=None, description="""Optional parameters for the request.""" + ) + + +class _GetDocumentParametersDict(TypedDict, total=False): + """Parameters for documents.get.""" + + name: Optional[str] + """The resource name of the Document. + Example: fileSearchStores/file-search-store-foo/documents/documents-bar""" + + config: Optional[GetDocumentConfigDict] + """Optional parameters for the request.""" + + +_GetDocumentParametersOrDict = Union[ + _GetDocumentParameters, _GetDocumentParametersDict +] + + +class StringList(_common.BaseModel): + """User provided string values assigned to a single metadata key. + + This data type is not supported in Vertex AI. + """ + + values: Optional[list[str]] = Field( + default=None, + description="""The string values of the metadata to store.""", + ) + + +class StringListDict(TypedDict, total=False): + """User provided string values assigned to a single metadata key. + + This data type is not supported in Vertex AI. + """ + + values: Optional[list[str]] + """The string values of the metadata to store.""" + + +StringListOrDict = Union[StringList, StringListDict] + + +class CustomMetadata(_common.BaseModel): + """User provided metadata stored as key-value pairs. + + This data type is not supported in Vertex AI. + """ + + key: Optional[str] = Field( + default=None, + description="""Required. The key of the metadata to store.""", + ) + numeric_value: Optional[float] = Field( + default=None, + description="""The numeric value of the metadata to store.""", + ) + string_list_value: Optional[StringList] = Field( + default=None, + description="""The StringList value of the metadata to store.""", + ) + string_value: Optional[str] = Field( + default=None, description="""The string value of the metadata to store.""" + ) + + +class CustomMetadataDict(TypedDict, total=False): + """User provided metadata stored as key-value pairs. + + This data type is not supported in Vertex AI. + """ + + key: Optional[str] + """Required. The key of the metadata to store.""" + + numeric_value: Optional[float] + """The numeric value of the metadata to store.""" + + string_list_value: Optional[StringListDict] + """The StringList value of the metadata to store.""" + + string_value: Optional[str] + """The string value of the metadata to store.""" + + +CustomMetadataOrDict = Union[CustomMetadata, CustomMetadataDict] + + +class Document(_common.BaseModel): + """A Document is a collection of Chunks.""" + + name: Optional[str] = Field( + default=None, + description="""Immutable. Identifier. The `Document` resource name. The ID (name excluding the "fileSearchStores/*/documents/" prefix) can contain up to 40 characters that are lowercase alphanumeric or dashes (-). The ID cannot start or end with a dash. If the name is empty on create, a unique name will be derived from `display_name` along with a 12 character random suffix. Example: `fileSearchStores/{file_search_store_id}/documents/my-awesome-doc-123a456b789c`""", + ) + display_name: Optional[str] = Field( + default=None, + description="""Optional. The human-readable display name for the `Document`. The display name must be no more than 512 characters in length, including spaces. Example: "Semantic Retriever Documentation".""", + ) + state: Optional[DocumentState] = Field( + default=None, + description="""Output only. Current state of the `Document`.""", + ) + size_bytes: Optional[int] = Field( + default=None, + description="""Output only. The size of raw bytes ingested into the Document.""", + ) + mime_type: Optional[str] = Field( + default=None, + description="""Output only. The mime type of the Document.""", + ) + create_time: Optional[datetime.datetime] = Field( + default=None, + description="""Output only. The Timestamp of when the `Document` was created.""", + ) + custom_metadata: Optional[list[CustomMetadata]] = Field( + default=None, + description="""Optional. User provided custom metadata stored as key-value pairs used for querying. A `Document` can have a maximum of 20 `CustomMetadata`.""", + ) + update_time: Optional[datetime.datetime] = Field( + default=None, + description="""Output only. The Timestamp of when the `Document` was last updated.""", + ) + + +class DocumentDict(TypedDict, total=False): + """A Document is a collection of Chunks.""" + + name: Optional[str] + """Immutable. Identifier. The `Document` resource name. The ID (name excluding the "fileSearchStores/*/documents/" prefix) can contain up to 40 characters that are lowercase alphanumeric or dashes (-). The ID cannot start or end with a dash. If the name is empty on create, a unique name will be derived from `display_name` along with a 12 character random suffix. Example: `fileSearchStores/{file_search_store_id}/documents/my-awesome-doc-123a456b789c`""" + + display_name: Optional[str] + """Optional. The human-readable display name for the `Document`. The display name must be no more than 512 characters in length, including spaces. Example: "Semantic Retriever Documentation".""" + + state: Optional[DocumentState] + """Output only. Current state of the `Document`.""" + + size_bytes: Optional[int] + """Output only. The size of raw bytes ingested into the Document.""" + + mime_type: Optional[str] + """Output only. The mime type of the Document.""" + + create_time: Optional[datetime.datetime] + """Output only. The Timestamp of when the `Document` was created.""" + + custom_metadata: Optional[list[CustomMetadataDict]] + """Optional. User provided custom metadata stored as key-value pairs used for querying. A `Document` can have a maximum of 20 `CustomMetadata`.""" + + update_time: Optional[datetime.datetime] + """Output only. The Timestamp of when the `Document` was last updated.""" + + +DocumentOrDict = Union[Document, DocumentDict] + + +class DeleteDocumentConfig(_common.BaseModel): + """Config for optional parameters.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + force: Optional[bool] = Field( + default=None, + description="""If set to true, any `Chunk`s and objects related to this `Document` will + also be deleted. + """, + ) + + +class DeleteDocumentConfigDict(TypedDict, total=False): + """Config for optional parameters.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + force: Optional[bool] + """If set to true, any `Chunk`s and objects related to this `Document` will + also be deleted. + """ + + +DeleteDocumentConfigOrDict = Union[ + DeleteDocumentConfig, DeleteDocumentConfigDict +] + + +class _DeleteDocumentParameters(_common.BaseModel): + """Config for documents.delete parameters.""" + + name: Optional[str] = Field( + default=None, + description="""The resource name of the Document. + Example: fileSearchStores/file-search-store-foo/documents/documents-bar""", + ) + config: Optional[DeleteDocumentConfig] = Field( + default=None, description="""Optional parameters for the request.""" + ) + + +class _DeleteDocumentParametersDict(TypedDict, total=False): + """Config for documents.delete parameters.""" + + name: Optional[str] + """The resource name of the Document. + Example: fileSearchStores/file-search-store-foo/documents/documents-bar""" + + config: Optional[DeleteDocumentConfigDict] + """Optional parameters for the request.""" + + +_DeleteDocumentParametersOrDict = Union[ + _DeleteDocumentParameters, _DeleteDocumentParametersDict +] + + +class ListDocumentsConfig(_common.BaseModel): + """Config for optional parameters.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + page_size: Optional[int] = Field(default=None, description="""""") + page_token: Optional[str] = Field(default=None, description="""""") + + +class ListDocumentsConfigDict(TypedDict, total=False): + """Config for optional parameters.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + page_size: Optional[int] + """""" + + page_token: Optional[str] + """""" + + +ListDocumentsConfigOrDict = Union[ListDocumentsConfig, ListDocumentsConfigDict] + + +class _ListDocumentsParameters(_common.BaseModel): + """Config for documents.list parameters.""" + + parent: Optional[str] = Field( + default=None, + description="""The resource name of the FileSearchStores. Example: `fileSearchStore/file-search-store-foo`""", + ) + config: Optional[ListDocumentsConfig] = Field( + default=None, description="""""" + ) + + +class _ListDocumentsParametersDict(TypedDict, total=False): + """Config for documents.list parameters.""" + + parent: Optional[str] + """The resource name of the FileSearchStores. Example: `fileSearchStore/file-search-store-foo`""" + + config: Optional[ListDocumentsConfigDict] + """""" + + +_ListDocumentsParametersOrDict = Union[ + _ListDocumentsParameters, _ListDocumentsParametersDict +] + + +class ListDocumentsResponse(_common.BaseModel): + """Config for documents.list return value.""" + + sdk_http_response: Optional[HttpResponse] = Field( + default=None, description="""Used to retain the full HTTP response.""" + ) + next_page_token: Optional[str] = Field( + default=None, + description="""A token, which can be sent as `page_token` to retrieve the next page. If this field is omitted, there are no more pages.""", + ) + documents: Optional[list[Document]] = Field( + default=None, description="""The returned `Document`s.""" + ) + + +class ListDocumentsResponseDict(TypedDict, total=False): + """Config for documents.list return value.""" + + sdk_http_response: Optional[HttpResponseDict] + """Used to retain the full HTTP response.""" + + next_page_token: Optional[str] + """A token, which can be sent as `page_token` to retrieve the next page. If this field is omitted, there are no more pages.""" + + documents: Optional[list[DocumentDict]] + """The returned `Document`s.""" + + +ListDocumentsResponseOrDict = Union[ + ListDocumentsResponse, ListDocumentsResponseDict +] + + +class CreateFileSearchStoreConfig(_common.BaseModel): + """Optional parameters for creating a file search store.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + display_name: Optional[str] = Field( + default=None, + description="""The human-readable display name for the file search store. + """, + ) + + +class CreateFileSearchStoreConfigDict(TypedDict, total=False): + """Optional parameters for creating a file search store.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + display_name: Optional[str] + """The human-readable display name for the file search store. + """ + + +CreateFileSearchStoreConfigOrDict = Union[ + CreateFileSearchStoreConfig, CreateFileSearchStoreConfigDict +] + + +class _CreateFileSearchStoreParameters(_common.BaseModel): + """Config for file_search_stores.create parameters.""" + + config: Optional[CreateFileSearchStoreConfig] = Field( + default=None, + description="""Optional parameters for creating a file search store. + """, + ) + + +class _CreateFileSearchStoreParametersDict(TypedDict, total=False): + """Config for file_search_stores.create parameters.""" + + config: Optional[CreateFileSearchStoreConfigDict] + """Optional parameters for creating a file search store. + """ + + +_CreateFileSearchStoreParametersOrDict = Union[ + _CreateFileSearchStoreParameters, _CreateFileSearchStoreParametersDict +] + + +class FileSearchStore(_common.BaseModel): + """A collection of Documents.""" + + name: Optional[str] = Field( + default=None, + description="""The resource name of the FileSearchStore. Example: `fileSearchStores/my-file-search-store-123`""", + ) + display_name: Optional[str] = Field( + default=None, + description="""The human-readable display name for the FileSearchStore.""", + ) + create_time: Optional[datetime.datetime] = Field( + default=None, + description="""The Timestamp of when the FileSearchStore was created.""", + ) + update_time: Optional[datetime.datetime] = Field( + default=None, + description="""The Timestamp of when the FileSearchStore was last updated.""", + ) + active_documents_count: Optional[int] = Field( + default=None, + description="""The number of documents in the FileSearchStore that are active and ready for retrieval.""", + ) + pending_documents_count: Optional[int] = Field( + default=None, + description="""The number of documents in the FileSearchStore that are being processed.""", + ) + failed_documents_count: Optional[int] = Field( + default=None, + description="""The number of documents in the FileSearchStore that have failed processing.""", + ) + size_bytes: Optional[int] = Field( + default=None, + description="""The size of raw bytes ingested into the FileSearchStore. This is the + total size of all the documents in the FileSearchStore.""", + ) + + +class FileSearchStoreDict(TypedDict, total=False): + """A collection of Documents.""" + + name: Optional[str] + """The resource name of the FileSearchStore. Example: `fileSearchStores/my-file-search-store-123`""" + + display_name: Optional[str] + """The human-readable display name for the FileSearchStore.""" + + create_time: Optional[datetime.datetime] + """The Timestamp of when the FileSearchStore was created.""" + + update_time: Optional[datetime.datetime] + """The Timestamp of when the FileSearchStore was last updated.""" + + active_documents_count: Optional[int] + """The number of documents in the FileSearchStore that are active and ready for retrieval.""" + + pending_documents_count: Optional[int] + """The number of documents in the FileSearchStore that are being processed.""" + + failed_documents_count: Optional[int] + """The number of documents in the FileSearchStore that have failed processing.""" + + size_bytes: Optional[int] + """The size of raw bytes ingested into the FileSearchStore. This is the + total size of all the documents in the FileSearchStore.""" + + +FileSearchStoreOrDict = Union[FileSearchStore, FileSearchStoreDict] + + +class GetFileSearchStoreConfig(_common.BaseModel): + """Optional parameters for getting a FileSearchStore.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + + +class GetFileSearchStoreConfigDict(TypedDict, total=False): + """Optional parameters for getting a FileSearchStore.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + +GetFileSearchStoreConfigOrDict = Union[ + GetFileSearchStoreConfig, GetFileSearchStoreConfigDict +] + + +class _GetFileSearchStoreParameters(_common.BaseModel): + """Config for file_search_stores.get parameters.""" + + name: Optional[str] = Field( + default=None, + description="""The resource name of the FileSearchStore. Example: `fileSearchStores/my-file-search-store-123`""", + ) + config: Optional[GetFileSearchStoreConfig] = Field( + default=None, description="""Optional parameters for the request.""" + ) + + +class _GetFileSearchStoreParametersDict(TypedDict, total=False): + """Config for file_search_stores.get parameters.""" + + name: Optional[str] + """The resource name of the FileSearchStore. Example: `fileSearchStores/my-file-search-store-123`""" + + config: Optional[GetFileSearchStoreConfigDict] + """Optional parameters for the request.""" + + +_GetFileSearchStoreParametersOrDict = Union[ + _GetFileSearchStoreParameters, _GetFileSearchStoreParametersDict +] + + +class DeleteFileSearchStoreConfig(_common.BaseModel): + """Optional parameters for deleting a FileSearchStore.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + force: Optional[bool] = Field( + default=None, + description="""If set to true, any Documents and objects related to this FileSearchStore will also be deleted. + If false (the default), a FAILED_PRECONDITION error will be returned if + the FileSearchStore contains any Documents. + """, + ) + + +class DeleteFileSearchStoreConfigDict(TypedDict, total=False): + """Optional parameters for deleting a FileSearchStore.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + force: Optional[bool] + """If set to true, any Documents and objects related to this FileSearchStore will also be deleted. + If false (the default), a FAILED_PRECONDITION error will be returned if + the FileSearchStore contains any Documents. + """ + + +DeleteFileSearchStoreConfigOrDict = Union[ + DeleteFileSearchStoreConfig, DeleteFileSearchStoreConfigDict +] + + +class _DeleteFileSearchStoreParameters(_common.BaseModel): + """Config for file_search_stores.delete parameters.""" + + name: Optional[str] = Field( + default=None, + description="""The resource name of the FileSearchStore. Example: `fileSearchStores/my-file-search-store-123`""", + ) + config: Optional[DeleteFileSearchStoreConfig] = Field( + default=None, description="""Optional parameters for the request.""" + ) + + +class _DeleteFileSearchStoreParametersDict(TypedDict, total=False): + """Config for file_search_stores.delete parameters.""" + + name: Optional[str] + """The resource name of the FileSearchStore. Example: `fileSearchStores/my-file-search-store-123`""" + + config: Optional[DeleteFileSearchStoreConfigDict] + """Optional parameters for the request.""" + + +_DeleteFileSearchStoreParametersOrDict = Union[ + _DeleteFileSearchStoreParameters, _DeleteFileSearchStoreParametersDict +] + + +class ListFileSearchStoresConfig(_common.BaseModel): + """Optional parameters for listing FileSearchStore.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + page_size: Optional[int] = Field(default=None, description="""""") + page_token: Optional[str] = Field(default=None, description="""""") + + +class ListFileSearchStoresConfigDict(TypedDict, total=False): + """Optional parameters for listing FileSearchStore.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + page_size: Optional[int] + """""" + + page_token: Optional[str] + """""" + + +ListFileSearchStoresConfigOrDict = Union[ + ListFileSearchStoresConfig, ListFileSearchStoresConfigDict +] + + +class _ListFileSearchStoresParameters(_common.BaseModel): + """Config for file_search_stores.list parameters.""" + + config: Optional[ListFileSearchStoresConfig] = Field( + default=None, description="""Optional parameters for the list request.""" + ) + + +class _ListFileSearchStoresParametersDict(TypedDict, total=False): + """Config for file_search_stores.list parameters.""" + + config: Optional[ListFileSearchStoresConfigDict] + """Optional parameters for the list request.""" + + +_ListFileSearchStoresParametersOrDict = Union[ + _ListFileSearchStoresParameters, _ListFileSearchStoresParametersDict +] + + +class ListFileSearchStoresResponse(_common.BaseModel): + """Config for file_search_stores.list return value.""" + + sdk_http_response: Optional[HttpResponse] = Field( + default=None, description="""Used to retain the full HTTP response.""" + ) + next_page_token: Optional[str] = Field( + default=None, + description="""A token, which can be sent as `page_token` to retrieve the next page. If this field is omitted, there are no more pages.""", + ) + file_search_stores: Optional[list[FileSearchStore]] = Field( + default=None, description="""The returned file search stores.""" + ) + + +class ListFileSearchStoresResponseDict(TypedDict, total=False): + """Config for file_search_stores.list return value.""" + + sdk_http_response: Optional[HttpResponseDict] + """Used to retain the full HTTP response.""" + + next_page_token: Optional[str] + """A token, which can be sent as `page_token` to retrieve the next page. If this field is omitted, there are no more pages.""" + + file_search_stores: Optional[list[FileSearchStoreDict]] + """The returned file search stores.""" + + +ListFileSearchStoresResponseOrDict = Union[ + ListFileSearchStoresResponse, ListFileSearchStoresResponseDict +] + + +class WhiteSpaceConfig(_common.BaseModel): + """Configuration for a white space chunking algorithm.""" + + max_tokens_per_chunk: Optional[int] = Field( + default=None, description="""Maximum number of tokens per chunk.""" + ) + max_overlap_tokens: Optional[int] = Field( + default=None, + description="""Maximum number of overlapping tokens between two adjacent chunks.""", + ) + + +class WhiteSpaceConfigDict(TypedDict, total=False): + """Configuration for a white space chunking algorithm.""" + + max_tokens_per_chunk: Optional[int] + """Maximum number of tokens per chunk.""" + + max_overlap_tokens: Optional[int] + """Maximum number of overlapping tokens between two adjacent chunks.""" + + +WhiteSpaceConfigOrDict = Union[WhiteSpaceConfig, WhiteSpaceConfigDict] + + +class ChunkingConfig(_common.BaseModel): + """Config for telling the service how to chunk the file.""" + + white_space_config: Optional[WhiteSpaceConfig] = Field( + default=None, description="""White space chunking configuration.""" + ) + + +class ChunkingConfigDict(TypedDict, total=False): + """Config for telling the service how to chunk the file.""" + + white_space_config: Optional[WhiteSpaceConfigDict] + """White space chunking configuration.""" + + +ChunkingConfigOrDict = Union[ChunkingConfig, ChunkingConfigDict] + + +class UploadToFileSearchStoreConfig(_common.BaseModel): + """Optional parameters for uploading a file to a FileSearchStore.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + should_return_http_response: Optional[bool] = Field( + default=None, + description=""" If true, the raw HTTP response will be returned in the 'sdk_http_response' field.""", + ) + mime_type: Optional[str] = Field( + default=None, + description="""MIME type of the file to be uploaded. If not provided, it will be inferred from the file extension.""", + ) + display_name: Optional[str] = Field( + default=None, description="""Display name of the created document.""" + ) + custom_metadata: Optional[list[CustomMetadata]] = Field( + default=None, + description="""User provided custom metadata stored as key-value pairs used for querying.""", + ) + chunking_config: Optional[ChunkingConfig] = Field( + default=None, + description="""Config for telling the service how to chunk the file.""", + ) + + +class UploadToFileSearchStoreConfigDict(TypedDict, total=False): + """Optional parameters for uploading a file to a FileSearchStore.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + should_return_http_response: Optional[bool] + """ If true, the raw HTTP response will be returned in the 'sdk_http_response' field.""" + + mime_type: Optional[str] + """MIME type of the file to be uploaded. If not provided, it will be inferred from the file extension.""" + + display_name: Optional[str] + """Display name of the created document.""" + + custom_metadata: Optional[list[CustomMetadataDict]] + """User provided custom metadata stored as key-value pairs used for querying.""" + + chunking_config: Optional[ChunkingConfigDict] + """Config for telling the service how to chunk the file.""" + + +UploadToFileSearchStoreConfigOrDict = Union[ + UploadToFileSearchStoreConfig, UploadToFileSearchStoreConfigDict +] + + +class _UploadToFileSearchStoreParameters(_common.BaseModel): + """Generates the parameters for the private _upload_to_file_search_store method.""" + + file_search_store_name: Optional[str] = Field( + default=None, + description="""The resource name of the FileSearchStore. Example: `fileSearchStores/my-file-search-store-123`""", + ) + config: Optional[UploadToFileSearchStoreConfig] = Field( + default=None, + description="""Used to override the default configuration.""", + ) + + +class _UploadToFileSearchStoreParametersDict(TypedDict, total=False): + """Generates the parameters for the private _upload_to_file_search_store method.""" + + file_search_store_name: Optional[str] + """The resource name of the FileSearchStore. Example: `fileSearchStores/my-file-search-store-123`""" + + config: Optional[UploadToFileSearchStoreConfigDict] + """Used to override the default configuration.""" + + +_UploadToFileSearchStoreParametersOrDict = Union[ + _UploadToFileSearchStoreParameters, _UploadToFileSearchStoreParametersDict +] + + +class UploadToFileSearchStoreResumableResponse(_common.BaseModel): + """Response for the resumable upload method.""" + + sdk_http_response: Optional[HttpResponse] = Field( + default=None, description="""Used to retain the full HTTP response.""" + ) + + +class UploadToFileSearchStoreResumableResponseDict(TypedDict, total=False): + """Response for the resumable upload method.""" + + sdk_http_response: Optional[HttpResponseDict] + """Used to retain the full HTTP response.""" + + +UploadToFileSearchStoreResumableResponseOrDict = Union[ + UploadToFileSearchStoreResumableResponse, + UploadToFileSearchStoreResumableResponseDict, +] + + +class ImportFileConfig(_common.BaseModel): + """Optional parameters for importing a file.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + custom_metadata: Optional[list[CustomMetadata]] = Field( + default=None, + description="""User provided custom metadata stored as key-value pairs used for querying.""", + ) + chunking_config: Optional[ChunkingConfig] = Field( + default=None, + description="""Config for telling the service how to chunk the file.""", + ) + + +class ImportFileConfigDict(TypedDict, total=False): + """Optional parameters for importing a file.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + custom_metadata: Optional[list[CustomMetadataDict]] + """User provided custom metadata stored as key-value pairs used for querying.""" + + chunking_config: Optional[ChunkingConfigDict] + """Config for telling the service how to chunk the file.""" + + +ImportFileConfigOrDict = Union[ImportFileConfig, ImportFileConfigDict] + + +class _ImportFileParameters(_common.BaseModel): + """Config for file_search_stores.import_file parameters.""" + + file_search_store_name: Optional[str] = Field( + default=None, + description="""The resource name of the FileSearchStore. Example: `fileSearchStores/my-file-search-store-123`""", + ) + file_name: Optional[str] = Field( + default=None, + description="""The name of the File API File to import. Example: `files/abc-123`""", + ) + config: Optional[ImportFileConfig] = Field( + default=None, description="""Optional parameters for the request.""" + ) + + +class _ImportFileParametersDict(TypedDict, total=False): + """Config for file_search_stores.import_file parameters.""" + + file_search_store_name: Optional[str] + """The resource name of the FileSearchStore. Example: `fileSearchStores/my-file-search-store-123`""" + + file_name: Optional[str] + """The name of the File API File to import. Example: `files/abc-123`""" + + config: Optional[ImportFileConfigDict] + """Optional parameters for the request.""" + + +_ImportFileParametersOrDict = Union[ + _ImportFileParameters, _ImportFileParametersDict +] + + +class ImportFileResponse(_common.BaseModel): + """Response for ImportFile to import a File API file with a file search store.""" + + sdk_http_response: Optional[HttpResponse] = Field( + default=None, description="""Used to retain the full HTTP response.""" + ) + parent: Optional[str] = Field( + default=None, + description="""The name of the FileSearchStore containing Documents.""", + ) + document_name: Optional[str] = Field( + default=None, description="""The identifier for the Document imported.""" + ) + + +class ImportFileResponseDict(TypedDict, total=False): + """Response for ImportFile to import a File API file with a file search store.""" + + sdk_http_response: Optional[HttpResponseDict] + """Used to retain the full HTTP response.""" + + parent: Optional[str] + """The name of the FileSearchStore containing Documents.""" + + document_name: Optional[str] + """The identifier for the Document imported.""" + + +ImportFileResponseOrDict = Union[ImportFileResponse, ImportFileResponseDict] + + +class ImportFileOperation(_common.BaseModel, Operation): + """Long-running operation for importing a file to a FileSearchStore.""" + + response: Optional[ImportFileResponse] = Field( + default=None, + description="""The result of the ImportFile operation, available when the operation is done.""", + ) + + @classmethod + def from_api_response( + cls, api_response: Any, is_vertex_ai: bool = False + ) -> Self: + """Instantiates a ImportFileOperation from an API response.""" + + response_dict = _ImportFileOperation_from_mldev(api_response) + return cls._from_response(response=response_dict, kwargs={}) + + +class ListFilesConfig(_common.BaseModel): + """Used to override the default configuration.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + page_size: Optional[int] = Field(default=None, description="""""") + page_token: Optional[str] = Field(default=None, description="""""") + + +class ListFilesConfigDict(TypedDict, total=False): + """Used to override the default configuration.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + page_size: Optional[int] + """""" + + page_token: Optional[str] + """""" + + +ListFilesConfigOrDict = Union[ListFilesConfig, ListFilesConfigDict] + + +class _ListFilesParameters(_common.BaseModel): + """Generates the parameters for the list method.""" + + config: Optional[ListFilesConfig] = Field( + default=None, + description="""Used to override the default configuration.""", + ) + + +class _ListFilesParametersDict(TypedDict, total=False): + """Generates the parameters for the list method.""" + + config: Optional[ListFilesConfigDict] + """Used to override the default configuration.""" + + +_ListFilesParametersOrDict = Union[ + _ListFilesParameters, _ListFilesParametersDict +] + + +class ListFilesResponse(_common.BaseModel): + """Response for the list files method.""" + + sdk_http_response: Optional[HttpResponse] = Field( + default=None, description="""Used to retain the full HTTP response.""" + ) + next_page_token: Optional[str] = Field( + default=None, + description="""A token that can be sent as a `page_token` into a subsequent `ListFiles` call.""", + ) + files: Optional[list[File]] = Field( + default=None, description="""The list of `File`s.""" + ) + + +class ListFilesResponseDict(TypedDict, total=False): + """Response for the list files method.""" + + sdk_http_response: Optional[HttpResponseDict] + """Used to retain the full HTTP response.""" + + next_page_token: Optional[str] + """A token that can be sent as a `page_token` into a subsequent `ListFiles` call.""" + + files: Optional[list[FileDict]] + """The list of `File`s.""" + + +ListFilesResponseOrDict = Union[ListFilesResponse, ListFilesResponseDict] + + +class CreateFileConfig(_common.BaseModel): + """Used to override the default configuration.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + should_return_http_response: Optional[bool] = Field( + default=None, + description=""" If true, the raw HTTP response will be returned in the 'sdk_http_response' field.""", + ) + + +class CreateFileConfigDict(TypedDict, total=False): + """Used to override the default configuration.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + should_return_http_response: Optional[bool] + """ If true, the raw HTTP response will be returned in the 'sdk_http_response' field.""" + + +CreateFileConfigOrDict = Union[CreateFileConfig, CreateFileConfigDict] + + +class _CreateFileParameters(_common.BaseModel): + """Generates the parameters for the private _create method.""" + + file: Optional[File] = Field( + default=None, + description="""The file to be uploaded. + mime_type: (Required) The MIME type of the file. Must be provided. + name: (Optional) The name of the file in the destination (e.g. + 'files/sample-image'). + display_name: (Optional) The display name of the file. + """, + ) + config: Optional[CreateFileConfig] = Field( + default=None, + description="""Used to override the default configuration.""", + ) + + +class _CreateFileParametersDict(TypedDict, total=False): + """Generates the parameters for the private _create method.""" + + file: Optional[FileDict] + """The file to be uploaded. + mime_type: (Required) The MIME type of the file. Must be provided. + name: (Optional) The name of the file in the destination (e.g. + 'files/sample-image'). + display_name: (Optional) The display name of the file. + """ + + config: Optional[CreateFileConfigDict] + """Used to override the default configuration.""" + + +_CreateFileParametersOrDict = Union[ + _CreateFileParameters, _CreateFileParametersDict +] + + +class CreateFileResponse(_common.BaseModel): + """Response for the create file method.""" + + sdk_http_response: Optional[HttpResponse] = Field( + default=None, description="""Used to retain the full HTTP response.""" + ) + + +class CreateFileResponseDict(TypedDict, total=False): + """Response for the create file method.""" + + sdk_http_response: Optional[HttpResponseDict] + """Used to retain the full HTTP response.""" + + +CreateFileResponseOrDict = Union[CreateFileResponse, CreateFileResponseDict] + + +class GetFileConfig(_common.BaseModel): + """Used to override the default configuration.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + + +class GetFileConfigDict(TypedDict, total=False): + """Used to override the default configuration.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + +GetFileConfigOrDict = Union[GetFileConfig, GetFileConfigDict] + + +class _GetFileParameters(_common.BaseModel): + """Generates the parameters for the get method.""" + + name: Optional[str] = Field( + default=None, + description="""The name identifier for the file to retrieve.""", + ) + config: Optional[GetFileConfig] = Field( + default=None, + description="""Used to override the default configuration.""", + ) + + +class _GetFileParametersDict(TypedDict, total=False): + """Generates the parameters for the get method.""" + + name: Optional[str] + """The name identifier for the file to retrieve.""" + + config: Optional[GetFileConfigDict] + """Used to override the default configuration.""" + + +_GetFileParametersOrDict = Union[_GetFileParameters, _GetFileParametersDict] + + +class DeleteFileConfig(_common.BaseModel): + """Used to override the default configuration.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + + +class DeleteFileConfigDict(TypedDict, total=False): + """Used to override the default configuration.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + +DeleteFileConfigOrDict = Union[DeleteFileConfig, DeleteFileConfigDict] + + +class _DeleteFileParameters(_common.BaseModel): + """Generates the parameters for the get method.""" + + name: Optional[str] = Field( + default=None, + description="""The name identifier for the file to be deleted.""", + ) + config: Optional[DeleteFileConfig] = Field( + default=None, + description="""Used to override the default configuration.""", + ) + + +class _DeleteFileParametersDict(TypedDict, total=False): + """Generates the parameters for the get method.""" + + name: Optional[str] + """The name identifier for the file to be deleted.""" + + config: Optional[DeleteFileConfigDict] + """Used to override the default configuration.""" + + +_DeleteFileParametersOrDict = Union[ + _DeleteFileParameters, _DeleteFileParametersDict +] + + +class DeleteFileResponse(_common.BaseModel): + """Response for the delete file method.""" + + sdk_http_response: Optional[HttpResponse] = Field( + default=None, description="""Used to retain the full HTTP response.""" + ) + + +class DeleteFileResponseDict(TypedDict, total=False): + """Response for the delete file method.""" + + sdk_http_response: Optional[HttpResponseDict] + """Used to retain the full HTTP response.""" + + +DeleteFileResponseOrDict = Union[DeleteFileResponse, DeleteFileResponseDict] + + +class RegisterFilesConfig(_common.BaseModel): + """Used to override the default configuration.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + should_return_http_response: Optional[bool] = Field( + default=None, + description=""" If true, the raw HTTP response will be returned in the 'sdk_http_response' field.""", + ) + + +class RegisterFilesConfigDict(TypedDict, total=False): + """Used to override the default configuration.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + should_return_http_response: Optional[bool] + """ If true, the raw HTTP response will be returned in the 'sdk_http_response' field.""" + + +RegisterFilesConfigOrDict = Union[RegisterFilesConfig, RegisterFilesConfigDict] + + +class _InternalRegisterFilesParameters(_common.BaseModel): + """Parameters for the private _Register method.""" + + uris: Optional[list[str]] = Field( + default=None, + description="""The Google Cloud Storage URIs to register. Example: `gs://bucket/object`.""", + ) + config: Optional[RegisterFilesConfig] = Field( + default=None, + description="""Used to override the default configuration.""", + ) + + +class _InternalRegisterFilesParametersDict(TypedDict, total=False): + """Parameters for the private _Register method.""" + + uris: Optional[list[str]] + """The Google Cloud Storage URIs to register. Example: `gs://bucket/object`.""" + + config: Optional[RegisterFilesConfigDict] + """Used to override the default configuration.""" + + +_InternalRegisterFilesParametersOrDict = Union[ + _InternalRegisterFilesParameters, _InternalRegisterFilesParametersDict +] + + +class RegisterFilesResponse(_common.BaseModel): + """Response for the _register file method.""" + + sdk_http_response: Optional[HttpResponse] = Field( + default=None, description="""Used to retain the full HTTP response.""" + ) + files: Optional[list[File]] = Field( + default=None, description="""The registered files.""" + ) + + +class RegisterFilesResponseDict(TypedDict, total=False): + """Response for the _register file method.""" + + sdk_http_response: Optional[HttpResponseDict] + """Used to retain the full HTTP response.""" + + files: Optional[list[FileDict]] + """The registered files.""" + + +RegisterFilesResponseOrDict = Union[ + RegisterFilesResponse, RegisterFilesResponseDict +] + + +class InlinedRequest(_common.BaseModel): + """Config for inlined request.""" + + model: Optional[str] = Field( + default=None, + description="""ID of the model to use. For a list of models, see `Google models + `_.""", + ) + contents: Optional[ContentListUnion] = Field( + default=None, + description="""Content of the request. + """, + ) + metadata: Optional[dict[str, str]] = Field( + default=None, + description="""The metadata to be associated with the request.""", + ) + config: Optional[GenerateContentConfig] = Field( + default=None, + description="""Configuration that contains optional model parameters. + """, + ) + + +class InlinedRequestDict(TypedDict, total=False): + """Config for inlined request.""" + + model: Optional[str] + """ID of the model to use. For a list of models, see `Google models + `_.""" + + contents: Optional[ContentListUnionDict] + """Content of the request. + """ + + metadata: Optional[dict[str, str]] + """The metadata to be associated with the request.""" + + config: Optional[GenerateContentConfigDict] + """Configuration that contains optional model parameters. + """ + + +InlinedRequestOrDict = Union[InlinedRequest, InlinedRequestDict] + + +class BatchJobSource(_common.BaseModel): + """Config for `src` parameter.""" + + format: Optional[str] = Field( + default=None, + description="""Storage format of the input files. Must be one of: + 'jsonl', 'bigquery'. + """, + ) + gcs_uri: Optional[list[str]] = Field( + default=None, + description="""The Google Cloud Storage URIs to input files. + """, + ) + bigquery_uri: Optional[str] = Field( + default=None, + description="""The BigQuery URI to input table. + """, + ) + file_name: Optional[str] = Field( + default=None, + description="""The Gemini Developer API's file resource name of the input data + (e.g. "files/12345"). + """, + ) + inlined_requests: Optional[list[InlinedRequest]] = Field( + default=None, + description="""The Gemini Developer API's inlined input data to run batch job. + """, + ) + + +class BatchJobSourceDict(TypedDict, total=False): + """Config for `src` parameter.""" + + format: Optional[str] + """Storage format of the input files. Must be one of: + 'jsonl', 'bigquery'. + """ + + gcs_uri: Optional[list[str]] + """The Google Cloud Storage URIs to input files. + """ + + bigquery_uri: Optional[str] + """The BigQuery URI to input table. + """ + + file_name: Optional[str] + """The Gemini Developer API's file resource name of the input data + (e.g. "files/12345"). + """ + + inlined_requests: Optional[list[InlinedRequestDict]] + """The Gemini Developer API's inlined input data to run batch job. + """ + + +BatchJobSourceOrDict = Union[BatchJobSource, BatchJobSourceDict] + + +class JobError(_common.BaseModel): + """Job error.""" + + details: Optional[list[str]] = Field( + default=None, + description="""A list of messages that carry the error details. There is a common set of message types for APIs to use.""", + ) + code: Optional[int] = Field(default=None, description="""The status code.""") + message: Optional[str] = Field( + default=None, + description="""A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the `details` field.""", + ) + + +class JobErrorDict(TypedDict, total=False): + """Job error.""" + + details: Optional[list[str]] + """A list of messages that carry the error details. There is a common set of message types for APIs to use.""" + + code: Optional[int] + """The status code.""" + + message: Optional[str] + """A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the `details` field.""" + + +JobErrorOrDict = Union[JobError, JobErrorDict] + + +class InlinedResponse(_common.BaseModel): + """Config for `inlined_responses` parameter.""" + + response: Optional[GenerateContentResponse] = Field( + default=None, + description="""The response to the request. + """, + ) + metadata: Optional[dict[str, str]] = Field( + default=None, + description="""The metadata to be associated with the request.""", + ) + error: Optional[JobError] = Field( + default=None, + description="""The error encountered while processing the request. + """, + ) + + +class InlinedResponseDict(TypedDict, total=False): + """Config for `inlined_responses` parameter.""" + + response: Optional[GenerateContentResponseDict] + """The response to the request. + """ + + metadata: Optional[dict[str, str]] + """The metadata to be associated with the request.""" + + error: Optional[JobErrorDict] + """The error encountered while processing the request. + """ + + +InlinedResponseOrDict = Union[InlinedResponse, InlinedResponseDict] + + +class SingleEmbedContentResponse(_common.BaseModel): + """Config for `response` parameter.""" + + embedding: Optional[ContentEmbedding] = Field( + default=None, + description="""The response to the request. + """, + ) + token_count: Optional[int] = Field( + default=None, + description="""The error encountered while processing the request. + """, + ) + + +class SingleEmbedContentResponseDict(TypedDict, total=False): + """Config for `response` parameter.""" + + embedding: Optional[ContentEmbeddingDict] + """The response to the request. + """ + + token_count: Optional[int] + """The error encountered while processing the request. + """ + + +SingleEmbedContentResponseOrDict = Union[ + SingleEmbedContentResponse, SingleEmbedContentResponseDict +] + + +class InlinedEmbedContentResponse(_common.BaseModel): + """Config for `inlined_embedding_responses` parameter.""" + + response: Optional[SingleEmbedContentResponse] = Field( + default=None, description="""Output only. The response to the request.""" + ) + error: Optional[JobError] = Field( + default=None, + description="""Output only. The error encountered while processing the request.""", + ) + metadata: Optional[dict[str, Any]] = Field( + default=None, + description="""Output only. The metadata associated with the request.""", + ) + + +class InlinedEmbedContentResponseDict(TypedDict, total=False): + """Config for `inlined_embedding_responses` parameter.""" + + response: Optional[SingleEmbedContentResponseDict] + """Output only. The response to the request.""" + + error: Optional[JobErrorDict] + """Output only. The error encountered while processing the request.""" + + metadata: Optional[dict[str, Any]] + """Output only. The metadata associated with the request.""" + + +InlinedEmbedContentResponseOrDict = Union[ + InlinedEmbedContentResponse, InlinedEmbedContentResponseDict +] + + +class BatchJobDestination(_common.BaseModel): + """Config for `des` parameter.""" + + format: Optional[str] = Field( + default=None, + description="""Storage format of the output files. Must be one of: + 'jsonl', 'bigquery'. + """, + ) + gcs_uri: Optional[str] = Field( + default=None, + description="""The Google Cloud Storage URI to the output file. + """, + ) + bigquery_uri: Optional[str] = Field( + default=None, + description="""The BigQuery URI to the output table. + """, + ) + file_name: Optional[str] = Field( + default=None, + description="""The Gemini Developer API's file resource name of the output data + (e.g. "files/12345"). The file will be a JSONL file with a single response + per line. The responses will be GenerateContentResponse messages formatted + as JSON. The responses will be written in the same order as the input + requests. + """, + ) + inlined_responses: Optional[list[InlinedResponse]] = Field( + default=None, + description="""The responses to the requests in the batch. Returned when the batch was + built using inlined requests. The responses will be in the same order as + the input requests. + """, + ) + inlined_embed_content_responses: Optional[ + list[InlinedEmbedContentResponse] + ] = Field( + default=None, + description="""The responses to the requests in the batch. Returned when the batch was + built using inlined requests. The responses will be in the same order as + the input requests. + """, + ) + + +class BatchJobDestinationDict(TypedDict, total=False): + """Config for `des` parameter.""" + + format: Optional[str] + """Storage format of the output files. Must be one of: + 'jsonl', 'bigquery'. + """ + + gcs_uri: Optional[str] + """The Google Cloud Storage URI to the output file. + """ + + bigquery_uri: Optional[str] + """The BigQuery URI to the output table. + """ + + file_name: Optional[str] + """The Gemini Developer API's file resource name of the output data + (e.g. "files/12345"). The file will be a JSONL file with a single response + per line. The responses will be GenerateContentResponse messages formatted + as JSON. The responses will be written in the same order as the input + requests. + """ + + inlined_responses: Optional[list[InlinedResponseDict]] + """The responses to the requests in the batch. Returned when the batch was + built using inlined requests. The responses will be in the same order as + the input requests. + """ + + inlined_embed_content_responses: Optional[ + list[InlinedEmbedContentResponseDict] + ] + """The responses to the requests in the batch. Returned when the batch was + built using inlined requests. The responses will be in the same order as + the input requests. + """ + + +BatchJobDestinationOrDict = Union[BatchJobDestination, BatchJobDestinationDict] + + +BatchJobDestinationUnion = Union[BatchJobDestination, str] + + +BatchJobDestinationUnionDict = Union[ + BatchJobDestinationUnion, BatchJobDestinationDict +] + + +class CreateBatchJobConfig(_common.BaseModel): + """Config for optional parameters.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + display_name: Optional[str] = Field( + default=None, + description="""The user-defined name of this BatchJob. + """, + ) + dest: Optional[BatchJobDestinationUnion] = Field( + default=None, + description="""GCS or BigQuery URI prefix for the output predictions. Example: + "gs://path/to/output/data" or "bq://projectId.bqDatasetId.bqTableId". + """, + ) + webhook_config: Optional[WebhookConfig] = Field( + default=None, + description="""Webhook configuration for receiving notifications when the batch + operation completes. + """, + ) + + +class CreateBatchJobConfigDict(TypedDict, total=False): + """Config for optional parameters.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + display_name: Optional[str] + """The user-defined name of this BatchJob. + """ + + dest: Optional[BatchJobDestinationUnionDict] + """GCS or BigQuery URI prefix for the output predictions. Example: + "gs://path/to/output/data" or "bq://projectId.bqDatasetId.bqTableId". + """ + + webhook_config: Optional[WebhookConfigDict] + """Webhook configuration for receiving notifications when the batch + operation completes. + """ + + +CreateBatchJobConfigOrDict = Union[ + CreateBatchJobConfig, CreateBatchJobConfigDict +] + + +BatchJobSourceUnion = Union[BatchJobSource, list[InlinedRequest], str] + + +BatchJobSourceUnionDict = Union[ + BatchJobSourceUnion, BatchJobSourceDict, list[InlinedRequestDict] +] + + +class _CreateBatchJobParameters(_common.BaseModel): + """Config for batches.create parameters.""" + + model: Optional[str] = Field( + default=None, + description="""The name of the model to produces the predictions via the BatchJob. + """, + ) + src: Optional[BatchJobSourceUnion] = Field( + default=None, + description="""GCS URI(-s) or BigQuery URI to your input data to run batch job. + Example: "gs://path/to/input/data" or "bq://projectId.bqDatasetId.bqTableId". + """, + ) + config: Optional[CreateBatchJobConfig] = Field( + default=None, + description="""Optional parameters for creating a BatchJob. + """, + ) + + +class _CreateBatchJobParametersDict(TypedDict, total=False): + """Config for batches.create parameters.""" + + model: Optional[str] + """The name of the model to produces the predictions via the BatchJob. + """ + + src: Optional[BatchJobSourceUnionDict] + """GCS URI(-s) or BigQuery URI to your input data to run batch job. + Example: "gs://path/to/input/data" or "bq://projectId.bqDatasetId.bqTableId". + """ + + config: Optional[CreateBatchJobConfigDict] + """Optional parameters for creating a BatchJob. + """ + + +_CreateBatchJobParametersOrDict = Union[ + _CreateBatchJobParameters, _CreateBatchJobParametersDict +] + + +class CompletionStats(_common.BaseModel): + """Success and error statistics of processing multiple entities (for example, DataItems or structured data rows) in batch. + + This data type is not supported in Gemini API. + """ + + failed_count: Optional[int] = Field( + default=None, + description="""Output only. The number of entities for which any error was encountered.""", + ) + incomplete_count: Optional[int] = Field( + default=None, + description="""Output only. In cases when enough errors are encountered a job, pipeline, or operation may be failed as a whole. Below is the number of entities for which the processing had not been finished (either in successful or failed state). Set to -1 if the number is unknown (for example, the operation failed before the total entity number could be collected).""", + ) + successful_count: Optional[int] = Field( + default=None, + description="""Output only. The number of entities that had been processed successfully.""", + ) + successful_forecast_point_count: Optional[int] = Field( + default=None, + description="""Output only. The number of the successful forecast points that are generated by the forecasting model. This is ONLY used by the forecasting batch prediction.""", + ) + + +class CompletionStatsDict(TypedDict, total=False): + """Success and error statistics of processing multiple entities (for example, DataItems or structured data rows) in batch. + + This data type is not supported in Gemini API. + """ + + failed_count: Optional[int] + """Output only. The number of entities for which any error was encountered.""" + + incomplete_count: Optional[int] + """Output only. In cases when enough errors are encountered a job, pipeline, or operation may be failed as a whole. Below is the number of entities for which the processing had not been finished (either in successful or failed state). Set to -1 if the number is unknown (for example, the operation failed before the total entity number could be collected).""" + + successful_count: Optional[int] + """Output only. The number of entities that had been processed successfully.""" + + successful_forecast_point_count: Optional[int] + """Output only. The number of the successful forecast points that are generated by the forecasting model. This is ONLY used by the forecasting batch prediction.""" + + +CompletionStatsOrDict = Union[CompletionStats, CompletionStatsDict] + + +class BatchJob(_common.BaseModel): + """Config for batches.create return value.""" + + name: Optional[str] = Field( + default=None, + description="""The resource name of the BatchJob. Output only.". + """, + ) + display_name: Optional[str] = Field( + default=None, + description="""The display name of the BatchJob. + """, + ) + state: Optional[JobState] = Field( + default=None, + description="""The state of the BatchJob. + """, + ) + error: Optional[JobError] = Field( + default=None, + description="""Output only. Only populated when the job's state is JOB_STATE_FAILED or JOB_STATE_CANCELLED.""", + ) + create_time: Optional[datetime.datetime] = Field( + default=None, + description="""The time when the BatchJob was created. + """, + ) + start_time: Optional[datetime.datetime] = Field( + default=None, + description="""Output only. Time when the Job for the first time entered the `JOB_STATE_RUNNING` state.""", + ) + end_time: Optional[datetime.datetime] = Field( + default=None, + description="""The time when the BatchJob was completed. This field is for Vertex AI only. + """, + ) + update_time: Optional[datetime.datetime] = Field( + default=None, + description="""The time when the BatchJob was last updated. + """, + ) + model: Optional[str] = Field( + default=None, + description="""The name of the model that produces the predictions via the BatchJob. + """, + ) + src: Optional[BatchJobSource] = Field( + default=None, + description="""Configuration for the input data. This field is for Vertex AI only. + """, + ) + dest: Optional[BatchJobDestination] = Field( + default=None, + description="""Configuration for the output data. + """, + ) + completion_stats: Optional[CompletionStats] = Field( + default=None, + description="""Statistics on completed and failed prediction instances. This field is for Vertex AI only. + """, + ) + + @property + def done(self) -> bool: + """Returns True if the batch job has ended.""" + if self.state is None: + return False + return self.state.name in JOB_STATES_ENDED + + +class GenerationConfigThinkingConfig(ThinkingConfig): + """Config for thinking feature. + + This class will be deprecated. Please use `ThinkingConfig` instead. + """ + + +class GenerationConfigThinkingConfigDict(ThinkingConfigDict): + """Config for thinking feature. + + This class will be deprecated. Please use `ThinkingConfig` instead. + """ + + +GenerationConfigThinkingConfigOrDict = Union[ + GenerationConfigThinkingConfig, GenerationConfigThinkingConfigDict +] + + +class BatchJobDict(TypedDict, total=False): + """Config for batches.create return value.""" + + name: Optional[str] + """The resource name of the BatchJob. Output only.". + """ + + display_name: Optional[str] + """The display name of the BatchJob. + """ + + state: Optional[JobState] + """The state of the BatchJob. + """ + + error: Optional[JobErrorDict] + """Output only. Only populated when the job's state is JOB_STATE_FAILED or JOB_STATE_CANCELLED.""" + + create_time: Optional[datetime.datetime] + """The time when the BatchJob was created. + """ + + start_time: Optional[datetime.datetime] + """Output only. Time when the Job for the first time entered the `JOB_STATE_RUNNING` state.""" + + end_time: Optional[datetime.datetime] + """The time when the BatchJob was completed. This field is for Vertex AI only. + """ + + update_time: Optional[datetime.datetime] + """The time when the BatchJob was last updated. + """ + + model: Optional[str] + """The name of the model that produces the predictions via the BatchJob. + """ + + src: Optional[BatchJobSourceDict] + """Configuration for the input data. This field is for Vertex AI only. + """ + + dest: Optional[BatchJobDestinationDict] + """Configuration for the output data. + """ + + completion_stats: Optional[CompletionStatsDict] + """Statistics on completed and failed prediction instances. This field is for Vertex AI only. + """ + + +BatchJobOrDict = Union[BatchJob, BatchJobDict] + + +class EmbedContentBatch(_common.BaseModel): + """Parameters for the embed_content method.""" + + contents: Optional[ContentListUnion] = Field( + default=None, + description="""The content to embed. Only the `parts.text` fields will be counted. + """, + ) + config: Optional[EmbedContentConfig] = Field( + default=None, + description="""Configuration that contains optional parameters. + """, + ) + + +class EmbedContentBatchDict(TypedDict, total=False): + """Parameters for the embed_content method.""" + + contents: Optional[ContentListUnionDict] + """The content to embed. Only the `parts.text` fields will be counted. + """ + + config: Optional[EmbedContentConfigDict] + """Configuration that contains optional parameters. + """ + + +EmbedContentBatchOrDict = Union[EmbedContentBatch, EmbedContentBatchDict] + + +class EmbeddingsBatchJobSource(_common.BaseModel): + + file_name: Optional[str] = Field( + default=None, + description="""The Gemini Developer API's file resource name of the input data + (e.g. "files/12345"). + """, + ) + inlined_requests: Optional[EmbedContentBatch] = Field( + default=None, + description="""The Gemini Developer API's inlined input data to run batch job. + """, + ) + + +class EmbeddingsBatchJobSourceDict(TypedDict, total=False): + + file_name: Optional[str] + """The Gemini Developer API's file resource name of the input data + (e.g. "files/12345"). + """ + + inlined_requests: Optional[EmbedContentBatchDict] + """The Gemini Developer API's inlined input data to run batch job. + """ + + +EmbeddingsBatchJobSourceOrDict = Union[ + EmbeddingsBatchJobSource, EmbeddingsBatchJobSourceDict +] + + +class CreateEmbeddingsBatchJobConfig(_common.BaseModel): + """Config for optional parameters.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + display_name: Optional[str] = Field( + default=None, + description="""The user-defined name of this BatchJob. + """, + ) + + +class CreateEmbeddingsBatchJobConfigDict(TypedDict, total=False): + """Config for optional parameters.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + display_name: Optional[str] + """The user-defined name of this BatchJob. + """ + + +CreateEmbeddingsBatchJobConfigOrDict = Union[ + CreateEmbeddingsBatchJobConfig, CreateEmbeddingsBatchJobConfigDict +] + + +class _CreateEmbeddingsBatchJobParameters(_common.BaseModel): + """Config for batches.create parameters.""" + + model: Optional[str] = Field( + default=None, + description="""The name of the model to produces the predictions via the BatchJob. + """, + ) + src: Optional[EmbeddingsBatchJobSource] = Field( + default=None, + description="""input data to run batch job". + """, + ) + config: Optional[CreateEmbeddingsBatchJobConfig] = Field( + default=None, + description="""Optional parameters for creating a BatchJob. + """, + ) + + +class _CreateEmbeddingsBatchJobParametersDict(TypedDict, total=False): + """Config for batches.create parameters.""" + + model: Optional[str] + """The name of the model to produces the predictions via the BatchJob. + """ + + src: Optional[EmbeddingsBatchJobSourceDict] + """input data to run batch job". + """ + + config: Optional[CreateEmbeddingsBatchJobConfigDict] + """Optional parameters for creating a BatchJob. + """ + + +_CreateEmbeddingsBatchJobParametersOrDict = Union[ + _CreateEmbeddingsBatchJobParameters, _CreateEmbeddingsBatchJobParametersDict +] + + +class GetBatchJobConfig(_common.BaseModel): + """Optional parameters.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + + +class GetBatchJobConfigDict(TypedDict, total=False): + """Optional parameters.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + +GetBatchJobConfigOrDict = Union[GetBatchJobConfig, GetBatchJobConfigDict] + + +class _GetBatchJobParameters(_common.BaseModel): + """Config for batches.get parameters.""" + + name: Optional[str] = Field( + default=None, + description="""A fully-qualified BatchJob resource name or ID. + Example: "projects/.../locations/.../batchPredictionJobs/456" + or "456" when project and location are initialized in the client. + """, + ) + config: Optional[GetBatchJobConfig] = Field( + default=None, description="""Optional parameters for the request.""" + ) + + +class _GetBatchJobParametersDict(TypedDict, total=False): + """Config for batches.get parameters.""" + + name: Optional[str] + """A fully-qualified BatchJob resource name or ID. + Example: "projects/.../locations/.../batchPredictionJobs/456" + or "456" when project and location are initialized in the client. + """ + + config: Optional[GetBatchJobConfigDict] + """Optional parameters for the request.""" + + +_GetBatchJobParametersOrDict = Union[ + _GetBatchJobParameters, _GetBatchJobParametersDict +] + + +class CancelBatchJobConfig(_common.BaseModel): + """Optional parameters.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + + +class CancelBatchJobConfigDict(TypedDict, total=False): + """Optional parameters.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + +CancelBatchJobConfigOrDict = Union[ + CancelBatchJobConfig, CancelBatchJobConfigDict +] + + +class _CancelBatchJobParameters(_common.BaseModel): + """Config for batches.cancel parameters.""" + + name: Optional[str] = Field( + default=None, + description="""A fully-qualified BatchJob resource name or ID. + Example: "projects/.../locations/.../batchPredictionJobs/456" + or "456" when project and location are initialized in the client. + """, + ) + config: Optional[CancelBatchJobConfig] = Field( + default=None, description="""Optional parameters for the request.""" + ) + + +class _CancelBatchJobParametersDict(TypedDict, total=False): + """Config for batches.cancel parameters.""" + + name: Optional[str] + """A fully-qualified BatchJob resource name or ID. + Example: "projects/.../locations/.../batchPredictionJobs/456" + or "456" when project and location are initialized in the client. + """ + + config: Optional[CancelBatchJobConfigDict] + """Optional parameters for the request.""" + + +_CancelBatchJobParametersOrDict = Union[ + _CancelBatchJobParameters, _CancelBatchJobParametersDict +] + + +class ListBatchJobsConfig(_common.BaseModel): + """Config for optional parameters.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + page_size: Optional[int] = Field(default=None, description="""""") + page_token: Optional[str] = Field(default=None, description="""""") + filter: Optional[str] = Field(default=None, description="""""") + + +class ListBatchJobsConfigDict(TypedDict, total=False): + """Config for optional parameters.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + page_size: Optional[int] + """""" + + page_token: Optional[str] + """""" + + filter: Optional[str] + """""" + + +ListBatchJobsConfigOrDict = Union[ListBatchJobsConfig, ListBatchJobsConfigDict] + + +class _ListBatchJobsParameters(_common.BaseModel): + """Config for batches.list parameters.""" + + config: Optional[ListBatchJobsConfig] = Field( + default=None, description="""""" + ) + + +class _ListBatchJobsParametersDict(TypedDict, total=False): + """Config for batches.list parameters.""" + + config: Optional[ListBatchJobsConfigDict] + """""" + + +_ListBatchJobsParametersOrDict = Union[ + _ListBatchJobsParameters, _ListBatchJobsParametersDict +] + + +class ListBatchJobsResponse(_common.BaseModel): + """Config for batches.list return value.""" + + sdk_http_response: Optional[HttpResponse] = Field( + default=None, description="""Used to retain the full HTTP response.""" + ) + next_page_token: Optional[str] = Field(default=None, description="""""") + batch_jobs: Optional[list[BatchJob]] = Field(default=None, description="""""") + + +class ListBatchJobsResponseDict(TypedDict, total=False): + """Config for batches.list return value.""" + + sdk_http_response: Optional[HttpResponseDict] + """Used to retain the full HTTP response.""" + + next_page_token: Optional[str] + """""" + + batch_jobs: Optional[list[BatchJobDict]] + """""" + + +ListBatchJobsResponseOrDict = Union[ + ListBatchJobsResponse, ListBatchJobsResponseDict +] + + +class DeleteBatchJobConfig(_common.BaseModel): + """Optional parameters for models.get method.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + + +class DeleteBatchJobConfigDict(TypedDict, total=False): + """Optional parameters for models.get method.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + +DeleteBatchJobConfigOrDict = Union[ + DeleteBatchJobConfig, DeleteBatchJobConfigDict +] + + +class _DeleteBatchJobParameters(_common.BaseModel): + """Config for batches.delete parameters.""" + + name: Optional[str] = Field( + default=None, + description="""A fully-qualified BatchJob resource name or ID. + Example: "projects/.../locations/.../batchPredictionJobs/456" + or "456" when project and location are initialized in the client. + """, + ) + config: Optional[DeleteBatchJobConfig] = Field( + default=None, description="""Optional parameters for the request.""" + ) + + +class _DeleteBatchJobParametersDict(TypedDict, total=False): + """Config for batches.delete parameters.""" + + name: Optional[str] + """A fully-qualified BatchJob resource name or ID. + Example: "projects/.../locations/.../batchPredictionJobs/456" + or "456" when project and location are initialized in the client. + """ + + config: Optional[DeleteBatchJobConfigDict] + """Optional parameters for the request.""" + + +_DeleteBatchJobParametersOrDict = Union[ + _DeleteBatchJobParameters, _DeleteBatchJobParametersDict +] + + +class DeleteResourceJob(_common.BaseModel): + """The return value of delete operation.""" + + sdk_http_response: Optional[HttpResponse] = Field( + default=None, description="""Used to retain the full HTTP response.""" + ) + name: Optional[str] = Field(default=None, description="""""") + done: Optional[bool] = Field(default=None, description="""""") + error: Optional[JobError] = Field(default=None, description="""""") + + +class DeleteResourceJobDict(TypedDict, total=False): + """The return value of delete operation.""" + + sdk_http_response: Optional[HttpResponseDict] + """Used to retain the full HTTP response.""" + + name: Optional[str] + """""" + + done: Optional[bool] + """""" + + error: Optional[JobErrorDict] + """""" + + +DeleteResourceJobOrDict = Union[DeleteResourceJob, DeleteResourceJobDict] + + +class GetOperationConfig(_common.BaseModel): + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + + +class GetOperationConfigDict(TypedDict, total=False): + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + +GetOperationConfigOrDict = Union[GetOperationConfig, GetOperationConfigDict] + + +class _GetOperationParameters(_common.BaseModel): + """Parameters for the GET method.""" + + operation_name: Optional[str] = Field( + default=None, + description="""The server-assigned name for the operation.""", + ) + config: Optional[GetOperationConfig] = Field( + default=None, + description="""Used to override the default configuration.""", + ) + + +class _GetOperationParametersDict(TypedDict, total=False): + """Parameters for the GET method.""" + + operation_name: Optional[str] + """The server-assigned name for the operation.""" + + config: Optional[GetOperationConfigDict] + """Used to override the default configuration.""" + + +_GetOperationParametersOrDict = Union[ + _GetOperationParameters, _GetOperationParametersDict +] + + +class FetchPredictOperationConfig(_common.BaseModel): + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + + +class FetchPredictOperationConfigDict(TypedDict, total=False): + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + +FetchPredictOperationConfigOrDict = Union[ + FetchPredictOperationConfig, FetchPredictOperationConfigDict +] + + +class _FetchPredictOperationParameters(_common.BaseModel): + """Parameters for the fetchPredictOperation method.""" + + operation_name: Optional[str] = Field( + default=None, + description="""The server-assigned name for the operation.""", + ) + resource_name: Optional[str] = Field(default=None, description="""""") + config: Optional[FetchPredictOperationConfig] = Field( + default=None, + description="""Used to override the default configuration.""", + ) + + +class _FetchPredictOperationParametersDict(TypedDict, total=False): + """Parameters for the fetchPredictOperation method.""" + + operation_name: Optional[str] + """The server-assigned name for the operation.""" + + resource_name: Optional[str] + """""" + + config: Optional[FetchPredictOperationConfigDict] + """Used to override the default configuration.""" + + +_FetchPredictOperationParametersOrDict = Union[ + _FetchPredictOperationParameters, _FetchPredictOperationParametersDict +] + + +class _GetProjectOperationParameters(_common.BaseModel): + """Parameters for the getProjectOperation method.""" + + operation_id: Optional[str] = Field( + default=None, + description="""The ID of the project-level Vertex operation to get. For example if the operation resource name is + projects/123/locations/us-central1/operations/456, the operation_id is + 456.""", + ) + config: Optional[GetOperationConfig] = Field( + default=None, + description="""Used to override the default configuration.""", + ) + + +class _GetProjectOperationParametersDict(TypedDict, total=False): + """Parameters for the getProjectOperation method.""" + + operation_id: Optional[str] + """The ID of the project-level Vertex operation to get. For example if the operation resource name is + projects/123/locations/us-central1/operations/456, the operation_id is + 456.""" + + config: Optional[GetOperationConfigDict] + """Used to override the default configuration.""" + + +_GetProjectOperationParametersOrDict = Union[ + _GetProjectOperationParameters, _GetProjectOperationParametersDict +] + + +class ProjectOperation(_common.BaseModel): + """A project-level operation in Vertex.""" + + name: Optional[str] = Field( + default=None, + description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""", + ) + metadata: Optional[dict[str, Any]] = Field( + default=None, + description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.""", + ) + done: Optional[bool] = Field( + default=None, + description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""", + ) + error: Optional[dict[str, Any]] = Field( + default=None, + description="""The error result of the operation in case of failure or cancellation.""", + ) + + +class ProjectOperationDict(TypedDict, total=False): + """A project-level operation in Vertex.""" + + name: Optional[str] + """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""" + + metadata: Optional[dict[str, Any]] + """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.""" + + done: Optional[bool] + """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""" + + error: Optional[dict[str, Any]] + """The error result of the operation in case of failure or cancellation.""" + + +ProjectOperationOrDict = Union[ProjectOperation, ProjectOperationDict] + + +class TestTableItem(_common.BaseModel): + + name: Optional[str] = Field( + default=None, + description="""The name of the test. This is used to derive the replay id.""", + ) + parameters: Optional[dict[str, Any]] = Field( + default=None, + description="""The parameters to the test. Use pydantic models.""", + ) + exception_if_mldev: Optional[str] = Field( + default=None, + description="""Expects an exception for MLDev matching the string.""", + ) + exception_if_vertex: Optional[str] = Field( + default=None, + description="""Expects an exception for Vertex matching the string.""", + ) + override_replay_id: Optional[str] = Field( + default=None, + description="""Use if you don't want to use the default replay id which is derived from the test name.""", + ) + has_union: Optional[bool] = Field( + default=None, + description="""True if the parameters contain an unsupported union type. This test will be skipped for languages that do not support the union type.""", + ) + skip_in_api_mode: Optional[str] = Field( + default=None, + description="""When set to a reason string, this test will be skipped in the API mode. Use this flag for tests that can not be reproduced with the real API. E.g. a test that deletes a resource.""", + ) + ignore_keys: Optional[list[str]] = Field( + default=None, + description="""Keys to ignore when comparing the request and response. This is useful for tests that are not deterministic.""", + ) + + +class TestTableItemDict(TypedDict, total=False): + + name: Optional[str] + """The name of the test. This is used to derive the replay id.""" + + parameters: Optional[dict[str, Any]] + """The parameters to the test. Use pydantic models.""" + + exception_if_mldev: Optional[str] + """Expects an exception for MLDev matching the string.""" + + exception_if_vertex: Optional[str] + """Expects an exception for Vertex matching the string.""" + + override_replay_id: Optional[str] + """Use if you don't want to use the default replay id which is derived from the test name.""" + + has_union: Optional[bool] + """True if the parameters contain an unsupported union type. This test will be skipped for languages that do not support the union type.""" + + skip_in_api_mode: Optional[str] + """When set to a reason string, this test will be skipped in the API mode. Use this flag for tests that can not be reproduced with the real API. E.g. a test that deletes a resource.""" + + ignore_keys: Optional[list[str]] + """Keys to ignore when comparing the request and response. This is useful for tests that are not deterministic.""" + + +TestTableItemOrDict = Union[TestTableItem, TestTableItemDict] + + +class TestTableFile(_common.BaseModel): + + comment: Optional[str] = Field(default=None, description="""""") + test_method: Optional[str] = Field(default=None, description="""""") + parameter_names: Optional[list[str]] = Field(default=None, description="""""") + test_table: Optional[list[TestTableItem]] = Field( + default=None, description="""""" + ) + + +class TestTableFileDict(TypedDict, total=False): + + comment: Optional[str] + """""" + + test_method: Optional[str] + """""" + + parameter_names: Optional[list[str]] + """""" + + test_table: Optional[list[TestTableItemDict]] + """""" + + +TestTableFileOrDict = Union[TestTableFile, TestTableFileDict] + + +class ReplayRequest(_common.BaseModel): + """Represents a single request in a replay.""" + + method: Optional[str] = Field(default=None, description="""""") + url: Optional[str] = Field(default=None, description="""""") + headers: Optional[dict[str, str]] = Field(default=None, description="""""") + body_segments: Optional[list[dict[str, Any]]] = Field( + default=None, description="""""" + ) + + +class ReplayRequestDict(TypedDict, total=False): + """Represents a single request in a replay.""" + + method: Optional[str] + """""" + + url: Optional[str] + """""" + + headers: Optional[dict[str, str]] + """""" + + body_segments: Optional[list[dict[str, Any]]] + """""" + + +ReplayRequestOrDict = Union[ReplayRequest, ReplayRequestDict] + + +class ReplayResponse(_common.BaseModel): + """Represents a single response in a replay.""" + + status_code: Optional[int] = Field(default=None, description="""""") + headers: Optional[dict[str, str]] = Field(default=None, description="""""") + body_segments: Optional[list[dict[str, Any]]] = Field( + default=None, description="""""" + ) + sdk_response_segments: Optional[list[dict[str, Any]]] = Field( + default=None, description="""""" + ) + + +class ReplayResponseDict(TypedDict, total=False): + """Represents a single response in a replay.""" + + status_code: Optional[int] + """""" + + headers: Optional[dict[str, str]] + """""" + + body_segments: Optional[list[dict[str, Any]]] + """""" + + sdk_response_segments: Optional[list[dict[str, Any]]] + """""" + + +ReplayResponseOrDict = Union[ReplayResponse, ReplayResponseDict] + + +class ReplayInteraction(_common.BaseModel): + """Represents a single interaction, request and response in a replay.""" + + request: Optional[ReplayRequest] = Field(default=None, description="""""") + response: Optional[ReplayResponse] = Field(default=None, description="""""") + + +class ReplayInteractionDict(TypedDict, total=False): + """Represents a single interaction, request and response in a replay.""" + + request: Optional[ReplayRequestDict] + """""" + + response: Optional[ReplayResponseDict] + """""" + + +ReplayInteractionOrDict = Union[ReplayInteraction, ReplayInteractionDict] + + +class ReplayFile(_common.BaseModel): + """Represents a recorded session.""" + + replay_id: Optional[str] = Field(default=None, description="""""") + interactions: Optional[list[ReplayInteraction]] = Field( + default=None, description="""""" + ) + + +class ReplayFileDict(TypedDict, total=False): + """Represents a recorded session.""" + + replay_id: Optional[str] + """""" + + interactions: Optional[list[ReplayInteractionDict]] + """""" + + +ReplayFileOrDict = Union[ReplayFile, ReplayFileDict] + + +class UploadFileConfig(_common.BaseModel): + """Used to override the default configuration.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + name: Optional[str] = Field( + default=None, + description="""The name of the file in the destination (e.g., 'files/sample-image'. If not provided one will be generated.""", + ) + mime_type: Optional[str] = Field( + default=None, + description="""mime_type: The MIME type of the file. If not provided, it will be inferred from the file extension.""", + ) + display_name: Optional[str] = Field( + default=None, description="""Optional display name of the file.""" + ) + + +class UploadFileConfigDict(TypedDict, total=False): + """Used to override the default configuration.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + name: Optional[str] + """The name of the file in the destination (e.g., 'files/sample-image'. If not provided one will be generated.""" + + mime_type: Optional[str] + """mime_type: The MIME type of the file. If not provided, it will be inferred from the file extension.""" + + display_name: Optional[str] + """Optional display name of the file.""" + + +UploadFileConfigOrDict = Union[UploadFileConfig, UploadFileConfigDict] + + +class DownloadFileConfig(_common.BaseModel): + """Used to override the default configuration.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + + +class DownloadFileConfigDict(TypedDict, total=False): + """Used to override the default configuration.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + +DownloadFileConfigOrDict = Union[DownloadFileConfig, DownloadFileConfigDict] + + +class UpscaleImageConfig(_common.BaseModel): + """Configuration for upscaling an image. + + For more information on this configuration, refer to + the `Imagen API reference documentation + `_. + """ + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + output_gcs_uri: Optional[str] = Field( + default=None, + description="""Cloud Storage URI used to store the generated images.""", + ) + safety_filter_level: Optional[SafetyFilterLevel] = Field( + default=None, description="""Filter level for safety filtering.""" + ) + person_generation: Optional[PersonGeneration] = Field( + default=None, description="""Allows generation of people by the model.""" + ) + include_rai_reason: Optional[bool] = Field( + default=None, + description="""Whether to include a reason for filtered-out images in the + response.""", + ) + output_mime_type: Optional[str] = Field( + default=None, + description="""The image format that the output should be saved as.""", + ) + output_compression_quality: Optional[int] = Field( + default=None, + description="""The level of compression. Only applicable if the + ``output_mime_type`` is ``image/jpeg``.""", + ) + enhance_input_image: Optional[bool] = Field( + default=None, + description="""Whether to add an image enhancing step before upscaling. + It is expected to suppress the noise and JPEG compression artifacts + from the input image.""", + ) + image_preservation_factor: Optional[float] = Field( + default=None, + description="""With a higher image preservation factor, the original image + pixels are more respected. With a lower image preservation factor, the + output image will have be more different from the input image, but + with finer details and less noise.""", + ) + labels: Optional[dict[str, str]] = Field( + default=None, + description="""User specified labels to track billing usage.""", + ) + + +class UpscaleImageConfigDict(TypedDict, total=False): + """Configuration for upscaling an image. + + For more information on this configuration, refer to + the `Imagen API reference documentation + `_. + """ + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + output_gcs_uri: Optional[str] + """Cloud Storage URI used to store the generated images.""" + + safety_filter_level: Optional[SafetyFilterLevel] + """Filter level for safety filtering.""" + + person_generation: Optional[PersonGeneration] + """Allows generation of people by the model.""" + + include_rai_reason: Optional[bool] + """Whether to include a reason for filtered-out images in the + response.""" + + output_mime_type: Optional[str] + """The image format that the output should be saved as.""" + + output_compression_quality: Optional[int] + """The level of compression. Only applicable if the + ``output_mime_type`` is ``image/jpeg``.""" + + enhance_input_image: Optional[bool] + """Whether to add an image enhancing step before upscaling. + It is expected to suppress the noise and JPEG compression artifacts + from the input image.""" + + image_preservation_factor: Optional[float] + """With a higher image preservation factor, the original image + pixels are more respected. With a lower image preservation factor, the + output image will have be more different from the input image, but + with finer details and less noise.""" + + labels: Optional[dict[str, str]] + """User specified labels to track billing usage.""" + + +UpscaleImageConfigOrDict = Union[UpscaleImageConfig, UpscaleImageConfigDict] + + +class UpscaleImageParameters(_common.BaseModel): + """User-facing config UpscaleImageParameters.""" + + model: Optional[str] = Field( + default=None, description="""The model to use.""" + ) + image: Optional[Image] = Field( + default=None, description="""The input image to upscale.""" + ) + upscale_factor: Optional[str] = Field( + default=None, + description="""The factor to upscale the image (x2 or x4).""", + ) + config: Optional[UpscaleImageConfig] = Field( + default=None, description="""Configuration for upscaling.""" + ) + + +class UpscaleImageParametersDict(TypedDict, total=False): + """User-facing config UpscaleImageParameters.""" + + model: Optional[str] + """The model to use.""" + + image: Optional[ImageDict] + """The input image to upscale.""" + + upscale_factor: Optional[str] + """The factor to upscale the image (x2 or x4).""" + + config: Optional[UpscaleImageConfigDict] + """Configuration for upscaling.""" + + +UpscaleImageParametersOrDict = Union[ + UpscaleImageParameters, UpscaleImageParametersDict +] + + +class RawReferenceImage(_common.BaseModel): + """A raw reference image. + + A raw reference image represents the base image to edit, provided by the user. + It can optionally be provided in addition to a mask reference image or + a style reference image. + """ + + reference_image: Optional[Image] = Field( + default=None, + description="""The reference image for the editing operation.""", + ) + reference_id: Optional[int] = Field( + default=None, description="""The id of the reference image.""" + ) + reference_type: Optional[str] = Field( + default=None, + description="""The type of the reference image. Only set by the SDK.""", + ) + + @pydantic.model_validator(mode='before') + @classmethod + def _validate_mask_image_config(self, values: Any) -> Any: + if 'reference_type' in values: + raise ValueError('Cannot set internal reference_type field directly.') + values['reference_type'] = 'REFERENCE_TYPE_RAW' + return values + + +class RawReferenceImageDict(TypedDict, total=False): + """A raw reference image. + + A raw reference image represents the base image to edit, provided by the user. + It can optionally be provided in addition to a mask reference image or + a style reference image. + """ + + reference_image: Optional[ImageDict] + """The reference image for the editing operation.""" + + reference_id: Optional[int] + """The id of the reference image.""" + + reference_type: Optional[str] + """The type of the reference image. Only set by the SDK.""" + + +RawReferenceImageOrDict = Union[RawReferenceImage, RawReferenceImageDict] + + +class MaskReferenceImage(_common.BaseModel): + """A mask reference image. + + This encapsulates either a mask image provided by the user and configs for + the user provided mask, or only config parameters for the model to generate + a mask. + + A mask image is an image whose non-zero values indicate where to edit the base + image. If the user provides a mask image, the mask must be in the same + dimensions as the raw image. + """ + + reference_image: Optional[Image] = Field( + default=None, + description="""The reference image for the editing operation.""", + ) + reference_id: Optional[int] = Field( + default=None, description="""The id of the reference image.""" + ) + reference_type: Optional[str] = Field( + default=None, + description="""The type of the reference image. Only set by the SDK.""", + ) + config: Optional[MaskReferenceConfig] = Field( + default=None, + description="""Configuration for the mask reference image.""", + ) + """Re-map config to mask_reference_config to send to API.""" + mask_image_config: Optional['MaskReferenceConfig'] = Field( + default=None, description="""""" + ) + + @pydantic.model_validator(mode='before') + @classmethod + def _validate_mask_image_config(self, values: Any) -> Any: + config = values.get('config', None) + values['mask_image_config'] = config + if 'reference_type' in values: + raise ValueError('Cannot set internal reference_type field directly.') + values['reference_type'] = 'REFERENCE_TYPE_MASK' + return values + + +class MaskReferenceImageDict(TypedDict, total=False): + """A mask reference image. + + This encapsulates either a mask image provided by the user and configs for + the user provided mask, or only config parameters for the model to generate + a mask. + + A mask image is an image whose non-zero values indicate where to edit the base + image. If the user provides a mask image, the mask must be in the same + dimensions as the raw image. + """ + + reference_image: Optional[ImageDict] + """The reference image for the editing operation.""" + + reference_id: Optional[int] + """The id of the reference image.""" + + reference_type: Optional[str] + """The type of the reference image. Only set by the SDK.""" + + config: Optional[MaskReferenceConfigDict] + """Configuration for the mask reference image.""" + + +MaskReferenceImageOrDict = Union[MaskReferenceImage, MaskReferenceImageDict] + + +class ControlReferenceImage(_common.BaseModel): + """A control reference image. + + The image of the control reference image is either a control image provided + by the user, or a regular image which the backend will use to generate a + control image of. In the case of the latter, the + enable_control_image_computation field in the config should be set to True. + + A control image is an image that represents a sketch image of areas for the + model to fill in based on the prompt. + """ + + reference_image: Optional[Image] = Field( + default=None, + description="""The reference image for the editing operation.""", + ) + reference_id: Optional[int] = Field( + default=None, description="""The id of the reference image.""" + ) + reference_type: Optional[str] = Field( + default=None, + description="""The type of the reference image. Only set by the SDK.""", + ) + config: Optional[ControlReferenceConfig] = Field( + default=None, + description="""Configuration for the control reference image.""", + ) + """Re-map config to control_reference_config to send to API.""" + control_image_config: Optional['ControlReferenceConfig'] = Field( + default=None, description="""""" + ) + + @pydantic.model_validator(mode='before') + @classmethod + def _validate_mask_image_config(self, values: Any) -> Any: + config = values.get('config', None) + values['control_image_config'] = config + if 'reference_type' in values: + raise ValueError('Cannot set internal reference_type field directly.') + values['reference_type'] = 'REFERENCE_TYPE_CONTROL' + return values + + +class ControlReferenceImageDict(TypedDict, total=False): + """A control reference image. + + The image of the control reference image is either a control image provided + by the user, or a regular image which the backend will use to generate a + control image of. In the case of the latter, the + enable_control_image_computation field in the config should be set to True. + + A control image is an image that represents a sketch image of areas for the + model to fill in based on the prompt. + """ + + reference_image: Optional[ImageDict] + """The reference image for the editing operation.""" + + reference_id: Optional[int] + """The id of the reference image.""" + + reference_type: Optional[str] + """The type of the reference image. Only set by the SDK.""" + + config: Optional[ControlReferenceConfigDict] + """Configuration for the control reference image.""" + + +ControlReferenceImageOrDict = Union[ + ControlReferenceImage, ControlReferenceImageDict +] + + +class StyleReferenceImage(_common.BaseModel): + """A style reference image. + + This encapsulates a style reference image provided by the user, and + additionally optional config parameters for the style reference image. + + A raw reference image can also be provided as a destination for the style to + be applied to. + """ + + reference_image: Optional[Image] = Field( + default=None, + description="""The reference image for the editing operation.""", + ) + reference_id: Optional[int] = Field( + default=None, description="""The id of the reference image.""" + ) + reference_type: Optional[str] = Field( + default=None, + description="""The type of the reference image. Only set by the SDK.""", + ) + config: Optional[StyleReferenceConfig] = Field( + default=None, + description="""Configuration for the style reference image.""", + ) + """Re-map config to style_reference_config to send to API.""" + style_image_config: Optional['StyleReferenceConfig'] = Field( + default=None, description="""""" + ) + + @pydantic.model_validator(mode='before') + @classmethod + def _validate_mask_image_config(self, values: Any) -> Any: + config = values.get('config', None) + values['style_image_config'] = config + if 'reference_type' in values: + raise ValueError('Cannot set internal reference_type field directly.') + values['reference_type'] = 'REFERENCE_TYPE_STYLE' + return values + + +class StyleReferenceImageDict(TypedDict, total=False): + """A style reference image. + + This encapsulates a style reference image provided by the user, and + additionally optional config parameters for the style reference image. + + A raw reference image can also be provided as a destination for the style to + be applied to. + """ + + reference_image: Optional[ImageDict] + """The reference image for the editing operation.""" + + reference_id: Optional[int] + """The id of the reference image.""" + + reference_type: Optional[str] + """The type of the reference image. Only set by the SDK.""" + + config: Optional[StyleReferenceConfigDict] + """Configuration for the style reference image.""" + + +StyleReferenceImageOrDict = Union[StyleReferenceImage, StyleReferenceImageDict] + + +class SubjectReferenceImage(_common.BaseModel): + """A subject reference image. + + This encapsulates a subject reference image provided by the user, and + additionally optional config parameters for the subject reference image. + + A raw reference image can also be provided as a destination for the subject to + be applied to. + """ + + reference_image: Optional[Image] = Field( + default=None, + description="""The reference image for the editing operation.""", + ) + reference_id: Optional[int] = Field( + default=None, description="""The id of the reference image.""" + ) + reference_type: Optional[str] = Field( + default=None, + description="""The type of the reference image. Only set by the SDK.""", + ) + config: Optional[SubjectReferenceConfig] = Field( + default=None, + description="""Configuration for the subject reference image.""", + ) + """Re-map config to subject_reference_config to send to API.""" + subject_image_config: Optional['SubjectReferenceConfig'] = Field( + default=None, description="""""" + ) + + @pydantic.model_validator(mode='before') + @classmethod + def _validate_mask_image_config(self, values: Any) -> Any: + config = values.get('config', None) + values['subject_image_config'] = config + if 'reference_type' in values: + raise ValueError('Cannot set internal reference_type field directly.') + values['reference_type'] = 'REFERENCE_TYPE_SUBJECT' + return values + + +class SubjectReferenceImageDict(TypedDict, total=False): + """A subject reference image. + + This encapsulates a subject reference image provided by the user, and + additionally optional config parameters for the subject reference image. + + A raw reference image can also be provided as a destination for the subject to + be applied to. + """ + + reference_image: Optional[ImageDict] + """The reference image for the editing operation.""" + + reference_id: Optional[int] + """The id of the reference image.""" + + reference_type: Optional[str] + """The type of the reference image. Only set by the SDK.""" + + config: Optional[SubjectReferenceConfigDict] + """Configuration for the subject reference image.""" + + +SubjectReferenceImageOrDict = Union[ + SubjectReferenceImage, SubjectReferenceImageDict +] + + +class ContentReferenceImage(_common.BaseModel): + """A content reference image. + + A content reference image represents a subject to reference (ex. person, + product, animal) provided by the user. It can optionally be provided in + addition to a style reference image (ex. background, style reference). + """ + + reference_image: Optional[Image] = Field( + default=None, + description="""The reference image for the editing operation.""", + ) + reference_id: Optional[int] = Field( + default=None, description="""The id of the reference image.""" + ) + reference_type: Optional[str] = Field( + default=None, + description="""The type of the reference image. Only set by the SDK.""", + ) + + @pydantic.model_validator(mode='before') + @classmethod + def _validate_mask_image_config(self, values: Any) -> Any: + if 'reference_type' in values: + raise ValueError('Cannot set internal reference_type field directly.') + values['reference_type'] = 'REFERENCE_TYPE_CONTENT' + return values + + +class ContentReferenceImageDict(TypedDict, total=False): + """A content reference image. + + A content reference image represents a subject to reference (ex. person, + product, animal) provided by the user. It can optionally be provided in + addition to a style reference image (ex. background, style reference). + """ + + reference_image: Optional[ImageDict] + """The reference image for the editing operation.""" + + reference_id: Optional[int] + """The id of the reference image.""" + + reference_type: Optional[str] + """The type of the reference image. Only set by the SDK.""" + + +ContentReferenceImageOrDict = Union[ + ContentReferenceImage, ContentReferenceImageDict +] + + +class LiveServerSetupComplete(_common.BaseModel): + """Sent in response to a `LiveGenerateContentSetup` message from the client.""" + + session_id: Optional[str] = Field( + default=None, description="""The session id of the live session.""" + ) + voice_consent_signature: Optional[VoiceConsentSignature] = Field( + default=None, + description="""Signature of the verified consent audio. This is populated when the + request has a ReplicatedVoiceConfig with consent_audio set, if the consent + verification was successful. This may be used in a subsequent request + instead of the consent_audio to verify the same consent.""", + ) + + +class LiveServerSetupCompleteDict(TypedDict, total=False): + """Sent in response to a `LiveGenerateContentSetup` message from the client.""" + + session_id: Optional[str] + """The session id of the live session.""" + + voice_consent_signature: Optional[VoiceConsentSignatureDict] + """Signature of the verified consent audio. This is populated when the + request has a ReplicatedVoiceConfig with consent_audio set, if the consent + verification was successful. This may be used in a subsequent request + instead of the consent_audio to verify the same consent.""" + + +LiveServerSetupCompleteOrDict = Union[ + LiveServerSetupComplete, LiveServerSetupCompleteDict +] + + +class Transcription(_common.BaseModel): + """Audio transcription in Server Conent.""" + + text: Optional[str] = Field( + default=None, description="""Optional. Transcription text.""" + ) + finished: Optional[bool] = Field( + default=None, + description="""Optional. The bool indicates the end of the transcription.""", + ) + + +class TranscriptionDict(TypedDict, total=False): + """Audio transcription in Server Conent.""" + + text: Optional[str] + """Optional. Transcription text.""" + + finished: Optional[bool] + """Optional. The bool indicates the end of the transcription.""" + + +TranscriptionOrDict = Union[Transcription, TranscriptionDict] + + +class LiveServerContent(_common.BaseModel): + """Incremental server update generated by the model in response to client messages. + + Content is generated as quickly as possible, and not in real time. Clients + may choose to buffer and play it out in real time. + """ + + model_turn: Optional[Content] = Field( + default=None, + description="""The content that the model has generated as part of the current conversation with the user.""", + ) + turn_complete: Optional[bool] = Field( + default=None, + description="""If true, indicates that the model is done generating. Generation will only start in response to additional client messages. Can be set alongside `content`, indicating that the `content` is the last in the turn.""", + ) + interrupted: Optional[bool] = Field( + default=None, + description="""If true, indicates that a client message has interrupted current model generation. If the client is playing out the content in realtime, this is a good signal to stop and empty the current queue.""", + ) + grounding_metadata: Optional[GroundingMetadata] = Field( + default=None, + description="""Metadata returned to client when grounding is enabled.""", + ) + generation_complete: Optional[bool] = Field( + default=None, + description="""If true, indicates that the model is done generating. When model is + interrupted while generating there will be no generation_complete message + in interrupted turn, it will go through interrupted > turn_complete. + When model assumes realtime playback there will be delay between + generation_complete and turn_complete that is caused by model + waiting for playback to finish. If true, indicates that the model + has finished generating all content. This is a signal to the client + that it can stop sending messages.""", + ) + input_transcription: Optional[Transcription] = Field( + default=None, + description="""Input transcription. The transcription is independent to the model + turn which means it doesn’t imply any ordering between transcription and + model turn.""", + ) + output_transcription: Optional[Transcription] = Field( + default=None, + description="""Output transcription. The transcription is independent to the model + turn which means it doesn’t imply any ordering between transcription and + model turn. + """, + ) + url_context_metadata: Optional[UrlContextMetadata] = Field( + default=None, + description="""Metadata related to url context retrieval tool.""", + ) + turn_complete_reason: Optional[TurnCompleteReason] = Field( + default=None, description="""Reason for the turn is complete.""" + ) + waiting_for_input: Optional[bool] = Field( + default=None, + description="""If true, indicates that the model is not generating content because + it is waiting for more input from the user, e.g. because it expects the + user to continue talking.""", + ) + + +class LiveServerContentDict(TypedDict, total=False): + """Incremental server update generated by the model in response to client messages. + + Content is generated as quickly as possible, and not in real time. Clients + may choose to buffer and play it out in real time. + """ + + model_turn: Optional[ContentDict] + """The content that the model has generated as part of the current conversation with the user.""" + + turn_complete: Optional[bool] + """If true, indicates that the model is done generating. Generation will only start in response to additional client messages. Can be set alongside `content`, indicating that the `content` is the last in the turn.""" + + interrupted: Optional[bool] + """If true, indicates that a client message has interrupted current model generation. If the client is playing out the content in realtime, this is a good signal to stop and empty the current queue.""" + + grounding_metadata: Optional[GroundingMetadataDict] + """Metadata returned to client when grounding is enabled.""" + + generation_complete: Optional[bool] + """If true, indicates that the model is done generating. When model is + interrupted while generating there will be no generation_complete message + in interrupted turn, it will go through interrupted > turn_complete. + When model assumes realtime playback there will be delay between + generation_complete and turn_complete that is caused by model + waiting for playback to finish. If true, indicates that the model + has finished generating all content. This is a signal to the client + that it can stop sending messages.""" + + input_transcription: Optional[TranscriptionDict] + """Input transcription. The transcription is independent to the model + turn which means it doesn’t imply any ordering between transcription and + model turn.""" + + output_transcription: Optional[TranscriptionDict] + """Output transcription. The transcription is independent to the model + turn which means it doesn’t imply any ordering between transcription and + model turn. + """ + + url_context_metadata: Optional[UrlContextMetadataDict] + """Metadata related to url context retrieval tool.""" + + turn_complete_reason: Optional[TurnCompleteReason] + """Reason for the turn is complete.""" + + waiting_for_input: Optional[bool] + """If true, indicates that the model is not generating content because + it is waiting for more input from the user, e.g. because it expects the + user to continue talking.""" + + +LiveServerContentOrDict = Union[LiveServerContent, LiveServerContentDict] + + +class LiveServerToolCall(_common.BaseModel): + """Request for the client to execute the `function_calls` and return the responses with the matching `id`s.""" + + function_calls: Optional[list[FunctionCall]] = Field( + default=None, description="""The function call to be executed.""" + ) + + +class LiveServerToolCallDict(TypedDict, total=False): + """Request for the client to execute the `function_calls` and return the responses with the matching `id`s.""" + + function_calls: Optional[list[FunctionCallDict]] + """The function call to be executed.""" + + +LiveServerToolCallOrDict = Union[LiveServerToolCall, LiveServerToolCallDict] + + +class LiveServerToolCallCancellation(_common.BaseModel): + """Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled. + + If there were side-effects to those tool calls, clients may attempt to undo + the tool calls. This message occurs only in cases where the clients interrupt + server turns. + """ + + ids: Optional[list[str]] = Field( + default=None, description="""The ids of the tool calls to be cancelled.""" + ) + + +class LiveServerToolCallCancellationDict(TypedDict, total=False): + """Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled. + + If there were side-effects to those tool calls, clients may attempt to undo + the tool calls. This message occurs only in cases where the clients interrupt + server turns. + """ + + ids: Optional[list[str]] + """The ids of the tool calls to be cancelled.""" + + +LiveServerToolCallCancellationOrDict = Union[ + LiveServerToolCallCancellation, LiveServerToolCallCancellationDict +] + + +class UsageMetadata(_common.BaseModel): + """Usage metadata about response(s).""" + + prompt_token_count: Optional[int] = Field( + default=None, + description="""Number of tokens in the prompt. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content.""", + ) + cached_content_token_count: Optional[int] = Field( + default=None, + description="""Number of tokens in the cached part of the prompt (the cached content).""", + ) + response_token_count: Optional[int] = Field( + default=None, + description="""Total number of tokens across all the generated response candidates.""", + ) + tool_use_prompt_token_count: Optional[int] = Field( + default=None, + description="""Number of tokens present in tool-use prompt(s).""", + ) + thoughts_token_count: Optional[int] = Field( + default=None, + description="""Number of tokens of thoughts for thinking models.""", + ) + total_token_count: Optional[int] = Field( + default=None, + description="""Total token count for prompt, response candidates, and tool-use prompts(if present).""", + ) + prompt_tokens_details: Optional[list[ModalityTokenCount]] = Field( + default=None, + description="""List of modalities that were processed in the request input.""", + ) + cache_tokens_details: Optional[list[ModalityTokenCount]] = Field( + default=None, + description="""List of modalities that were processed in the cache input.""", + ) + response_tokens_details: Optional[list[ModalityTokenCount]] = Field( + default=None, + description="""List of modalities that were returned in the response.""", + ) + tool_use_prompt_tokens_details: Optional[list[ModalityTokenCount]] = Field( + default=None, + description="""List of modalities that were processed in the tool-use prompt.""", + ) + traffic_type: Optional[TrafficType] = Field( + default=None, + description="""Traffic type. This shows whether a request consumes Pay-As-You-Go + or Provisioned Throughput quota.""", + ) + + +class UsageMetadataDict(TypedDict, total=False): + """Usage metadata about response(s).""" + + prompt_token_count: Optional[int] + """Number of tokens in the prompt. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content.""" + + cached_content_token_count: Optional[int] + """Number of tokens in the cached part of the prompt (the cached content).""" + + response_token_count: Optional[int] + """Total number of tokens across all the generated response candidates.""" + + tool_use_prompt_token_count: Optional[int] + """Number of tokens present in tool-use prompt(s).""" + + thoughts_token_count: Optional[int] + """Number of tokens of thoughts for thinking models.""" + + total_token_count: Optional[int] + """Total token count for prompt, response candidates, and tool-use prompts(if present).""" + + prompt_tokens_details: Optional[list[ModalityTokenCountDict]] + """List of modalities that were processed in the request input.""" + + cache_tokens_details: Optional[list[ModalityTokenCountDict]] + """List of modalities that were processed in the cache input.""" + + response_tokens_details: Optional[list[ModalityTokenCountDict]] + """List of modalities that were returned in the response.""" + + tool_use_prompt_tokens_details: Optional[list[ModalityTokenCountDict]] + """List of modalities that were processed in the tool-use prompt.""" + + traffic_type: Optional[TrafficType] + """Traffic type. This shows whether a request consumes Pay-As-You-Go + or Provisioned Throughput quota.""" + + +UsageMetadataOrDict = Union[UsageMetadata, UsageMetadataDict] + + +class LiveServerGoAway(_common.BaseModel): + """Server will not be able to service client soon.""" + + time_left: Optional[str] = Field( + default=None, + description="""The remaining time before the connection will be terminated as ABORTED. The minimal time returned here is specified differently together with the rate limits for a given model.""", + ) + + +class LiveServerGoAwayDict(TypedDict, total=False): + """Server will not be able to service client soon.""" + + time_left: Optional[str] + """The remaining time before the connection will be terminated as ABORTED. The minimal time returned here is specified differently together with the rate limits for a given model.""" + + +LiveServerGoAwayOrDict = Union[LiveServerGoAway, LiveServerGoAwayDict] + + +class LiveServerSessionResumptionUpdate(_common.BaseModel): + """Update of the session resumption state. + + Only sent if `session_resumption` was set in the connection config. + """ + + new_handle: Optional[str] = Field( + default=None, + description="""New handle that represents state that can be resumed. Empty if `resumable`=false.""", + ) + resumable: Optional[bool] = Field( + default=None, + description="""True if session can be resumed at this point. It might be not possible to resume session at some points. In that case we send update empty new_handle and resumable=false. Example of such case could be model executing function calls or just generating. Resuming session (using previous session token) in such state will result in some data loss.""", + ) + last_consumed_client_message_index: Optional[int] = Field( + default=None, + description="""Index of last message sent by client that is included in state represented by this SessionResumptionToken. Only sent when `SessionResumptionConfig.transparent` is set. + +Presence of this index allows users to transparently reconnect and avoid issue of losing some part of realtime audio input/video. If client wishes to temporarily disconnect (for example as result of receiving GoAway) they can do it without losing state by buffering messages sent since last `SessionResmumptionTokenUpdate`. This field will enable them to limit buffering (avoid keeping all requests in RAM). + +Note: This should not be used for when resuming a session at some time later -- in those cases partial audio and video frames arelikely not needed.""", + ) + + +class LiveServerSessionResumptionUpdateDict(TypedDict, total=False): + """Update of the session resumption state. + + Only sent if `session_resumption` was set in the connection config. + """ + + new_handle: Optional[str] + """New handle that represents state that can be resumed. Empty if `resumable`=false.""" + + resumable: Optional[bool] + """True if session can be resumed at this point. It might be not possible to resume session at some points. In that case we send update empty new_handle and resumable=false. Example of such case could be model executing function calls or just generating. Resuming session (using previous session token) in such state will result in some data loss.""" + + last_consumed_client_message_index: Optional[int] + """Index of last message sent by client that is included in state represented by this SessionResumptionToken. Only sent when `SessionResumptionConfig.transparent` is set. + +Presence of this index allows users to transparently reconnect and avoid issue of losing some part of realtime audio input/video. If client wishes to temporarily disconnect (for example as result of receiving GoAway) they can do it without losing state by buffering messages sent since last `SessionResmumptionTokenUpdate`. This field will enable them to limit buffering (avoid keeping all requests in RAM). + +Note: This should not be used for when resuming a session at some time later -- in those cases partial audio and video frames arelikely not needed.""" + + +LiveServerSessionResumptionUpdateOrDict = Union[ + LiveServerSessionResumptionUpdate, LiveServerSessionResumptionUpdateDict +] + + +class VoiceActivityDetectionSignal(_common.BaseModel): + + vad_signal_type: Optional[VadSignalType] = Field( + default=None, description="""The type of the VAD signal.""" + ) + + +class VoiceActivityDetectionSignalDict(TypedDict, total=False): + + vad_signal_type: Optional[VadSignalType] + """The type of the VAD signal.""" + + +VoiceActivityDetectionSignalOrDict = Union[ + VoiceActivityDetectionSignal, VoiceActivityDetectionSignalDict +] + + +class VoiceActivity(_common.BaseModel): + """Voice activity signal.""" + + voice_activity_type: Optional[VoiceActivityType] = Field( + default=None, description="""The type of the voice activity signal.""" + ) + + +class VoiceActivityDict(TypedDict, total=False): + """Voice activity signal.""" + + voice_activity_type: Optional[VoiceActivityType] + """The type of the voice activity signal.""" + + +VoiceActivityOrDict = Union[VoiceActivity, VoiceActivityDict] + + +class LiveServerMessage(_common.BaseModel): + """Response message for API call.""" + + setup_complete: Optional[LiveServerSetupComplete] = Field( + default=None, + description="""Sent in response to a `LiveClientSetup` message from the client.""", + ) + server_content: Optional[LiveServerContent] = Field( + default=None, + description="""Content generated by the model in response to client messages.""", + ) + tool_call: Optional[LiveServerToolCall] = Field( + default=None, + description="""Request for the client to execute the `function_calls` and return the responses with the matching `id`s.""", + ) + tool_call_cancellation: Optional[LiveServerToolCallCancellation] = Field( + default=None, + description="""Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled.""", + ) + usage_metadata: Optional[UsageMetadata] = Field( + default=None, description="""Usage metadata about model response(s).""" + ) + go_away: Optional[LiveServerGoAway] = Field( + default=None, description="""Server will disconnect soon.""" + ) + session_resumption_update: Optional[LiveServerSessionResumptionUpdate] = ( + Field( + default=None, + description="""Update of the session resumption state.""", + ) + ) + voice_activity_detection_signal: Optional[VoiceActivityDetectionSignal] = ( + Field( + default=None, + description="""Voice activity detection signal. Allowlisted only.""", + ) + ) + voice_activity: Optional[VoiceActivity] = Field( + default=None, description="""Voice activity signal.""" + ) + + @property + def text(self) -> Optional[str]: + """Returns the concatenation of all text parts in the response. + + If there are non-text parts in the response, only the concatenated text + result from text parts will be returned. + """ + if ( + not self.server_content + or not self.server_content + or not self.server_content.model_turn + or not self.server_content.model_turn.parts + ): + return None + text = '' + non_text_parts = [] + for part in self.server_content.model_turn.parts: + for field_name, field_value in part.model_dump( + exclude={'text', 'thought'} + ).items(): + if field_value is not None: + non_text_parts.append(field_name) + if isinstance(part.text, str): + if isinstance(part.thought, bool) and part.thought: + continue + text += part.text + global _live_server_text_warning_logged + if non_text_parts and not _live_server_text_warning_logged: + logger.warning( + 'Warning: there are non-text parts in the response:' + f' {non_text_parts}, returning concatenated text result from text' + ' parts, check out the non text parts for full response from model.' + ) + _live_server_text_warning_logged = True + return text if text else None + + @property + def data(self) -> Optional[bytes]: + """Returns the concatenation of all inline data parts in the response. + + If there are non-data parts in the response, only the concatenated data + result from the data parts will be returned. + """ + if ( + not self.server_content + or not self.server_content + or not self.server_content.model_turn + or not self.server_content.model_turn.parts + ): + return None + concatenated_data = b'' + non_data_parts = [] + for part in self.server_content.model_turn.parts: + for field_name, field_value in part.model_dump( + exclude={'inline_data'} + ).items(): + if field_value is not None: + non_data_parts.append(field_name) + if part.inline_data and isinstance(part.inline_data.data, bytes): + concatenated_data += part.inline_data.data + global _live_server_data_warning_logged + if non_data_parts and not _live_server_data_warning_logged: + logger.warning( + 'Warning: there are non-data parts in the response:' + f' {non_data_parts}, returning concatenated data result from data' + ' parts, check out the non data parts for full response from model.' + ) + _live_server_data_warning_logged = True + return concatenated_data if len(concatenated_data) > 0 else None + + +class LiveServerMessageDict(TypedDict, total=False): + """Response message for API call.""" + + setup_complete: Optional[LiveServerSetupCompleteDict] + """Sent in response to a `LiveClientSetup` message from the client.""" + + server_content: Optional[LiveServerContentDict] + """Content generated by the model in response to client messages.""" + + tool_call: Optional[LiveServerToolCallDict] + """Request for the client to execute the `function_calls` and return the responses with the matching `id`s.""" + + tool_call_cancellation: Optional[LiveServerToolCallCancellationDict] + """Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled.""" + + usage_metadata: Optional[UsageMetadataDict] + """Usage metadata about model response(s).""" + + go_away: Optional[LiveServerGoAwayDict] + """Server will disconnect soon.""" + + session_resumption_update: Optional[LiveServerSessionResumptionUpdateDict] + """Update of the session resumption state.""" + + voice_activity_detection_signal: Optional[VoiceActivityDetectionSignalDict] + """Voice activity detection signal. Allowlisted only.""" + + voice_activity: Optional[VoiceActivityDict] + """Voice activity signal.""" + + +LiveServerMessageOrDict = Union[LiveServerMessage, LiveServerMessageDict] + + +class SessionResumptionConfig(_common.BaseModel): + """Configuration of session resumption mechanism. + + Included in `LiveConnectConfig.session_resumption`. If included server + will send `LiveServerSessionResumptionUpdate` messages. + """ + + handle: Optional[str] = Field( + default=None, + description="""Session resumption handle of previous session (session to restore). + +If not present new session will be started.""", + ) + transparent: Optional[bool] = Field( + default=None, + description="""If set the server will send `last_consumed_client_message_index` in the `session_resumption_update` messages to allow for transparent reconnections.""", + ) + + +class SessionResumptionConfigDict(TypedDict, total=False): + """Configuration of session resumption mechanism. + + Included in `LiveConnectConfig.session_resumption`. If included server + will send `LiveServerSessionResumptionUpdate` messages. + """ + + handle: Optional[str] + """Session resumption handle of previous session (session to restore). + +If not present new session will be started.""" + + transparent: Optional[bool] + """If set the server will send `last_consumed_client_message_index` in the `session_resumption_update` messages to allow for transparent reconnections.""" + + +SessionResumptionConfigOrDict = Union[ + SessionResumptionConfig, SessionResumptionConfigDict +] + + +class SlidingWindow(_common.BaseModel): + """Context window will be truncated by keeping only suffix of it. + + Context window will always be cut at start of USER role turn. System + instructions and `BidiGenerateContentSetup.prefix_turns` will not be + subject to the sliding window mechanism, they will always stay at the + beginning of context window. + """ + + target_tokens: Optional[int] = Field( + default=None, + description="""Session reduction target -- how many tokens we should keep. Window shortening operation has some latency costs, so we should avoid running it on every turn. Should be < trigger_tokens. If not set, trigger_tokens/2 is assumed.""", + ) + + +class SlidingWindowDict(TypedDict, total=False): + """Context window will be truncated by keeping only suffix of it. + + Context window will always be cut at start of USER role turn. System + instructions and `BidiGenerateContentSetup.prefix_turns` will not be + subject to the sliding window mechanism, they will always stay at the + beginning of context window. + """ + + target_tokens: Optional[int] + """Session reduction target -- how many tokens we should keep. Window shortening operation has some latency costs, so we should avoid running it on every turn. Should be < trigger_tokens. If not set, trigger_tokens/2 is assumed.""" + + +SlidingWindowOrDict = Union[SlidingWindow, SlidingWindowDict] + + +class ContextWindowCompressionConfig(_common.BaseModel): + """Enables context window compression -- mechanism managing model context window so it does not exceed given length.""" + + trigger_tokens: Optional[int] = Field( + default=None, + description="""Number of tokens (before running turn) that triggers context window compression mechanism.""", + ) + sliding_window: Optional[SlidingWindow] = Field( + default=None, description="""Sliding window compression mechanism.""" + ) + + +class ContextWindowCompressionConfigDict(TypedDict, total=False): + """Enables context window compression -- mechanism managing model context window so it does not exceed given length.""" + + trigger_tokens: Optional[int] + """Number of tokens (before running turn) that triggers context window compression mechanism.""" + + sliding_window: Optional[SlidingWindowDict] + """Sliding window compression mechanism.""" + + +ContextWindowCompressionConfigOrDict = Union[ + ContextWindowCompressionConfig, ContextWindowCompressionConfigDict +] + + +class AudioTranscriptionConfig(_common.BaseModel): + """The audio transcription configuration in Setup.""" + + language_codes: Optional[list[str]] = Field( + default=None, + description="""The language codes of the audio. BCP-47 language code. If not set, the transcription will be in the language detected by the model. If set, the server will use the language code specified in the model config as a hint for the language of the audio + """, + ) + + +class AudioTranscriptionConfigDict(TypedDict, total=False): + """The audio transcription configuration in Setup.""" + + language_codes: Optional[list[str]] + """The language codes of the audio. BCP-47 language code. If not set, the transcription will be in the language detected by the model. If set, the server will use the language code specified in the model config as a hint for the language of the audio + """ + + +AudioTranscriptionConfigOrDict = Union[ + AudioTranscriptionConfig, AudioTranscriptionConfigDict +] + + +class ProactivityConfig(_common.BaseModel): + """Config for proactivity features.""" + + proactive_audio: Optional[bool] = Field( + default=None, + description="""If enabled, the model can reject responding to the last prompt. For + example, this allows the model to ignore out of context speech or to stay + silent if the user did not make a request, yet.""", + ) + + +class ProactivityConfigDict(TypedDict, total=False): + """Config for proactivity features.""" + + proactive_audio: Optional[bool] + """If enabled, the model can reject responding to the last prompt. For + example, this allows the model to ignore out of context speech or to stay + silent if the user did not make a request, yet.""" + + +ProactivityConfigOrDict = Union[ProactivityConfig, ProactivityConfigDict] + + +class HistoryConfig(_common.BaseModel): + """Configuration for history exchange between client and server.""" + + initial_history_in_client_content: Optional[bool] = Field( + default=None, + description="""If true, after sending `setup_complete`, the server will wait + and at first process `client_content` messages until `turn_complete` is + `true`. This initial history will not trigger a model call and + may end with model content. After `turn_complete` is `true`, the client + can start the realtime conversation via `realtime_input`.""", + ) + + +class HistoryConfigDict(TypedDict, total=False): + """Configuration for history exchange between client and server.""" + + initial_history_in_client_content: Optional[bool] + """If true, after sending `setup_complete`, the server will wait + and at first process `client_content` messages until `turn_complete` is + `true`. This initial history will not trigger a model call and + may end with model content. After `turn_complete` is `true`, the client + can start the realtime conversation via `realtime_input`.""" + + +HistoryConfigOrDict = Union[HistoryConfig, HistoryConfigDict] + + +class CustomizedAvatar(_common.BaseModel): + """Configures the customized avatar to be used in the session.""" + + image_mime_type: Optional[str] = Field( + default=None, + description="""The mime type of the reference image, e.g., "image/jpeg".""", + ) + image_data: Optional[bytes] = Field( + default=None, + description="""The data of the reference image. The dimensions of the reference + image should be 9:16 (portrait) with a minimum resolution of 704x1280.""", + ) + + +class CustomizedAvatarDict(TypedDict, total=False): + """Configures the customized avatar to be used in the session.""" + + image_mime_type: Optional[str] + """The mime type of the reference image, e.g., "image/jpeg".""" + + image_data: Optional[bytes] + """The data of the reference image. The dimensions of the reference + image should be 9:16 (portrait) with a minimum resolution of 704x1280.""" + + +CustomizedAvatarOrDict = Union[CustomizedAvatar, CustomizedAvatarDict] + + +class AvatarConfig(_common.BaseModel): + """Configures the avatar to be used in the session.""" + + avatar_name: Optional[str] = Field( + default=None, description="""Pre-built avatar id.""" + ) + customized_avatar: Optional[CustomizedAvatar] = Field( + default=None, + description="""Customized avatar appearance with a reference image.""", + ) + audio_bitrate_bps: Optional[int] = Field( + default=None, description="""The bitrate of compressed audio.""" + ) + video_bitrate_bps: Optional[int] = Field( + default=None, description="""The bitrate of compressed video output.""" + ) + + +class AvatarConfigDict(TypedDict, total=False): + """Configures the avatar to be used in the session.""" + + avatar_name: Optional[str] + """Pre-built avatar id.""" + + customized_avatar: Optional[CustomizedAvatarDict] + """Customized avatar appearance with a reference image.""" + + audio_bitrate_bps: Optional[int] + """The bitrate of compressed audio.""" + + video_bitrate_bps: Optional[int] + """The bitrate of compressed video output.""" + + +AvatarConfigOrDict = Union[AvatarConfig, AvatarConfigDict] + + +class LiveClientSetup(_common.BaseModel): + """Message contains configuration that will apply for the duration of the streaming session.""" + + model: Optional[str] = Field( + default=None, + description=""" + The fully qualified name of the publisher model or tuned model endpoint to + use. + """, + ) + generation_config: Optional[GenerationConfig] = Field( + default=None, + description="""The generation configuration for the session. + Note: only a subset of fields are supported. + """, + ) + system_instruction: Optional[ContentUnion] = Field( + default=None, + description="""The user provided system instructions for the model. + Note: only text should be used in parts and content in each part will be + in a separate paragraph.""", + ) + tools: Optional[ToolListUnion] = Field( + default=None, + description=""" A list of `Tools` the model may use to generate the next response. + + A `Tool` is a piece of code that enables the system to interact with + external systems to perform an action, or set of actions, outside of + knowledge and scope of the model.""", + ) + session_resumption: Optional[SessionResumptionConfig] = Field( + default=None, + description="""Configures session resumption mechanism. + + If included server will send SessionResumptionUpdate messages.""", + ) + context_window_compression: Optional[ContextWindowCompressionConfig] = Field( + default=None, + description="""Configures context window compression mechanism. + + If included, server will compress context window to fit into given length.""", + ) + input_audio_transcription: Optional[AudioTranscriptionConfig] = Field( + default=None, + description="""The transcription of the input aligns with the input audio language. + """, + ) + output_audio_transcription: Optional[AudioTranscriptionConfig] = Field( + default=None, + description="""The transcription of the output aligns with the language code + specified for the output audio. + """, + ) + proactivity: Optional[ProactivityConfig] = Field( + default=None, + description="""Configures the proactivity of the model. This allows the model to respond proactively to + the input and to ignore irrelevant input.""", + ) + explicit_vad_signal: Optional[bool] = Field( + default=None, + description="""Configures the explicit VAD signal. If enabled, the client will send + vad_signal to indicate the start and end of speech. This allows the server + to process the audio more efficiently.""", + ) + history_config: Optional[HistoryConfig] = Field( + default=None, + description="""Configures the exchange of history between the client and the server.""", + ) + avatar_config: Optional[AvatarConfig] = Field( + default=None, description="""Configures the avatar model behavior.""" + ) + safety_settings: Optional[list[SafetySetting]] = Field( + default=None, + description="""Safety settings in the request to block unsafe content in the + response. + """, + ) + + +class LiveClientSetupDict(TypedDict, total=False): + """Message contains configuration that will apply for the duration of the streaming session.""" + + model: Optional[str] + """ + The fully qualified name of the publisher model or tuned model endpoint to + use. + """ + + generation_config: Optional[GenerationConfigDict] + """The generation configuration for the session. + Note: only a subset of fields are supported. + """ + + system_instruction: Optional[ContentUnionDict] + """The user provided system instructions for the model. + Note: only text should be used in parts and content in each part will be + in a separate paragraph.""" + + tools: Optional[ToolListUnionDict] + """ A list of `Tools` the model may use to generate the next response. + + A `Tool` is a piece of code that enables the system to interact with + external systems to perform an action, or set of actions, outside of + knowledge and scope of the model.""" + + session_resumption: Optional[SessionResumptionConfigDict] + """Configures session resumption mechanism. + + If included server will send SessionResumptionUpdate messages.""" + + context_window_compression: Optional[ContextWindowCompressionConfigDict] + """Configures context window compression mechanism. + + If included, server will compress context window to fit into given length.""" + + input_audio_transcription: Optional[AudioTranscriptionConfigDict] + """The transcription of the input aligns with the input audio language. + """ + + output_audio_transcription: Optional[AudioTranscriptionConfigDict] + """The transcription of the output aligns with the language code + specified for the output audio. + """ + + proactivity: Optional[ProactivityConfigDict] + """Configures the proactivity of the model. This allows the model to respond proactively to + the input and to ignore irrelevant input.""" + + explicit_vad_signal: Optional[bool] + """Configures the explicit VAD signal. If enabled, the client will send + vad_signal to indicate the start and end of speech. This allows the server + to process the audio more efficiently.""" + + history_config: Optional[HistoryConfigDict] + """Configures the exchange of history between the client and the server.""" + + avatar_config: Optional[AvatarConfigDict] + """Configures the avatar model behavior.""" + + safety_settings: Optional[list[SafetySettingDict]] + """Safety settings in the request to block unsafe content in the + response. + """ + + +LiveClientSetupOrDict = Union[LiveClientSetup, LiveClientSetupDict] + + +class LiveClientContent(_common.BaseModel): + """Incremental update of the current conversation delivered from the client. + + All the content here will unconditionally be appended to the conversation + history and used as part of the prompt to the model to generate content. + + A message here will interrupt any current model generation. + """ + + turns: Optional[list[Content]] = Field( + default=None, + description="""The content appended to the current conversation with the model. + + For single-turn queries, this is a single instance. For multi-turn + queries, this is a repeated field that contains conversation history and + latest request. + """, + ) + turn_complete: Optional[bool] = Field( + default=None, + description="""If true, indicates that the server content generation should start with + the currently accumulated prompt. Otherwise, the server will await + additional messages before starting generation.""", + ) + + +class LiveClientContentDict(TypedDict, total=False): + """Incremental update of the current conversation delivered from the client. + + All the content here will unconditionally be appended to the conversation + history and used as part of the prompt to the model to generate content. + + A message here will interrupt any current model generation. + """ + + turns: Optional[list[ContentDict]] + """The content appended to the current conversation with the model. + + For single-turn queries, this is a single instance. For multi-turn + queries, this is a repeated field that contains conversation history and + latest request. + """ + + turn_complete: Optional[bool] + """If true, indicates that the server content generation should start with + the currently accumulated prompt. Otherwise, the server will await + additional messages before starting generation.""" + + +LiveClientContentOrDict = Union[LiveClientContent, LiveClientContentDict] + + +class ActivityStart(_common.BaseModel): + """Marks the start of user activity. + + This can only be sent if automatic (i.e. server-side) activity detection is + disabled. + """ + + pass + + +class ActivityStartDict(TypedDict, total=False): + """Marks the start of user activity. + + This can only be sent if automatic (i.e. server-side) activity detection is + disabled. + """ + + pass + + +ActivityStartOrDict = Union[ActivityStart, ActivityStartDict] + + +class ActivityEnd(_common.BaseModel): + """Marks the end of user activity. + + This can only be sent if automatic (i.e. server-side) activity detection is + disabled. + """ + + pass + + +class ActivityEndDict(TypedDict, total=False): + """Marks the end of user activity. + + This can only be sent if automatic (i.e. server-side) activity detection is + disabled. + """ + + pass + + +ActivityEndOrDict = Union[ActivityEnd, ActivityEndDict] + + +class LiveClientRealtimeInput(_common.BaseModel): + """User input that is sent in real time. + + This is different from `LiveClientContent` in a few ways: + + - Can be sent continuously without interruption to model generation. + - If there is a need to mix data interleaved across the + `LiveClientContent` and the `LiveClientRealtimeInput`, server attempts to + optimize for best response, but there are no guarantees. + - End of turn is not explicitly specified, but is rather derived from user + activity (for example, end of speech). + - Even before the end of turn, the data is processed incrementally + to optimize for a fast start of the response from the model. + - Is always assumed to be the user's input (cannot be used to populate + conversation history). + """ + + media_chunks: Optional[list[Blob]] = Field( + default=None, description="""Inlined bytes data for media input.""" + ) + audio: Optional[Blob] = Field( + default=None, description="""The realtime audio input stream.""" + ) + audio_stream_end: Optional[bool] = Field( + default=None, + description=""" +Indicates that the audio stream has ended, e.g. because the microphone was +turned off. + +This should only be sent when automatic activity detection is enabled +(which is the default). + +The client can reopen the stream by sending an audio message. +""", + ) + video: Optional[Blob] = Field( + default=None, description="""The realtime video input stream.""" + ) + text: Optional[str] = Field( + default=None, description="""The realtime text input stream.""" + ) + activity_start: Optional[ActivityStart] = Field( + default=None, description="""Marks the start of user activity.""" + ) + activity_end: Optional[ActivityEnd] = Field( + default=None, description="""Marks the end of user activity.""" + ) + + +class LiveClientRealtimeInputDict(TypedDict, total=False): + """User input that is sent in real time. + + This is different from `LiveClientContent` in a few ways: + + - Can be sent continuously without interruption to model generation. + - If there is a need to mix data interleaved across the + `LiveClientContent` and the `LiveClientRealtimeInput`, server attempts to + optimize for best response, but there are no guarantees. + - End of turn is not explicitly specified, but is rather derived from user + activity (for example, end of speech). + - Even before the end of turn, the data is processed incrementally + to optimize for a fast start of the response from the model. + - Is always assumed to be the user's input (cannot be used to populate + conversation history). + """ + + media_chunks: Optional[list[BlobDict]] + """Inlined bytes data for media input.""" + + audio: Optional[BlobDict] + """The realtime audio input stream.""" + + audio_stream_end: Optional[bool] + """ +Indicates that the audio stream has ended, e.g. because the microphone was +turned off. + +This should only be sent when automatic activity detection is enabled +(which is the default). + +The client can reopen the stream by sending an audio message. +""" + + video: Optional[BlobDict] + """The realtime video input stream.""" + + text: Optional[str] + """The realtime text input stream.""" + + activity_start: Optional[ActivityStartDict] + """Marks the start of user activity.""" + + activity_end: Optional[ActivityEndDict] + """Marks the end of user activity.""" + + +LiveClientRealtimeInputOrDict = Union[ + LiveClientRealtimeInput, LiveClientRealtimeInputDict +] + + +class LiveClientToolResponse(_common.BaseModel): + """Client generated response to a `ToolCall` received from the server. + + Individual `FunctionResponse` objects are matched to the respective + `FunctionCall` objects by the `id` field. + + Note that in the unary and server-streaming GenerateContent APIs function + calling happens by exchanging the `Content` parts, while in the bidi + GenerateContent APIs function calling happens over this dedicated set of + messages. + """ + + function_responses: Optional[list[FunctionResponse]] = Field( + default=None, description="""The response to the function calls.""" + ) + + +class LiveClientToolResponseDict(TypedDict, total=False): + """Client generated response to a `ToolCall` received from the server. + + Individual `FunctionResponse` objects are matched to the respective + `FunctionCall` objects by the `id` field. + + Note that in the unary and server-streaming GenerateContent APIs function + calling happens by exchanging the `Content` parts, while in the bidi + GenerateContent APIs function calling happens over this dedicated set of + messages. + """ + + function_responses: Optional[list[FunctionResponseDict]] + """The response to the function calls.""" + + +LiveClientToolResponseOrDict = Union[ + LiveClientToolResponse, LiveClientToolResponseDict +] + + +class LiveClientMessage(_common.BaseModel): + """Messages sent by the client in the API call.""" + + setup: Optional[LiveClientSetup] = Field( + default=None, + description="""Message to be sent by the system when connecting to the API. SDK users should not send this message.""", + ) + client_content: Optional[LiveClientContent] = Field( + default=None, + description="""Incremental update of the current conversation delivered from the client.""", + ) + realtime_input: Optional[LiveClientRealtimeInput] = Field( + default=None, description="""User input that is sent in real time.""" + ) + tool_response: Optional[LiveClientToolResponse] = Field( + default=None, + description="""Response to a `ToolCallMessage` received from the server.""", + ) + + +class LiveClientMessageDict(TypedDict, total=False): + """Messages sent by the client in the API call.""" + + setup: Optional[LiveClientSetupDict] + """Message to be sent by the system when connecting to the API. SDK users should not send this message.""" + + client_content: Optional[LiveClientContentDict] + """Incremental update of the current conversation delivered from the client.""" + + realtime_input: Optional[LiveClientRealtimeInputDict] + """User input that is sent in real time.""" + + tool_response: Optional[LiveClientToolResponseDict] + """Response to a `ToolCallMessage` received from the server.""" + + +LiveClientMessageOrDict = Union[LiveClientMessage, LiveClientMessageDict] + + +class AutomaticActivityDetection(_common.BaseModel): + """Configures automatic detection of activity.""" + + disabled: Optional[bool] = Field( + default=None, + description="""If enabled, detected voice and text input count as activity. If disabled, the client must send activity signals.""", + ) + start_of_speech_sensitivity: Optional[StartSensitivity] = Field( + default=None, + description="""Determines how likely speech is to be detected.""", + ) + end_of_speech_sensitivity: Optional[EndSensitivity] = Field( + default=None, + description="""Determines how likely detected speech is ended.""", + ) + prefix_padding_ms: Optional[int] = Field( + default=None, + description="""The required duration of detected speech before start-of-speech is committed. The lower this value the more sensitive the start-of-speech detection is and the shorter speech can be recognized. However, this also increases the probability of false positives.""", + ) + silence_duration_ms: Optional[int] = Field( + default=None, + description="""The required duration of detected non-speech (e.g. silence) before end-of-speech is committed. The larger this value, the longer speech gaps can be without interrupting the user's activity but this will increase the model's latency.""", + ) + + +class AutomaticActivityDetectionDict(TypedDict, total=False): + """Configures automatic detection of activity.""" + + disabled: Optional[bool] + """If enabled, detected voice and text input count as activity. If disabled, the client must send activity signals.""" + + start_of_speech_sensitivity: Optional[StartSensitivity] + """Determines how likely speech is to be detected.""" + + end_of_speech_sensitivity: Optional[EndSensitivity] + """Determines how likely detected speech is ended.""" + + prefix_padding_ms: Optional[int] + """The required duration of detected speech before start-of-speech is committed. The lower this value the more sensitive the start-of-speech detection is and the shorter speech can be recognized. However, this also increases the probability of false positives.""" + + silence_duration_ms: Optional[int] + """The required duration of detected non-speech (e.g. silence) before end-of-speech is committed. The larger this value, the longer speech gaps can be without interrupting the user's activity but this will increase the model's latency.""" + + +AutomaticActivityDetectionOrDict = Union[ + AutomaticActivityDetection, AutomaticActivityDetectionDict +] + + +class RealtimeInputConfig(_common.BaseModel): + """Marks the end of user activity. + + This can only be sent if automatic (i.e. server-side) activity detection is + disabled. + """ + + automatic_activity_detection: Optional[AutomaticActivityDetection] = Field( + default=None, + description="""If not set, automatic activity detection is enabled by default. If automatic voice detection is disabled, the client must send activity signals.""", + ) + activity_handling: Optional[ActivityHandling] = Field( + default=None, description="""Defines what effect activity has.""" + ) + turn_coverage: Optional[TurnCoverage] = Field( + default=None, + description="""Defines which input is included in the user's turn.""", + ) + + +class RealtimeInputConfigDict(TypedDict, total=False): + """Marks the end of user activity. + + This can only be sent if automatic (i.e. server-side) activity detection is + disabled. + """ + + automatic_activity_detection: Optional[AutomaticActivityDetectionDict] + """If not set, automatic activity detection is enabled by default. If automatic voice detection is disabled, the client must send activity signals.""" + + activity_handling: Optional[ActivityHandling] + """Defines what effect activity has.""" + + turn_coverage: Optional[TurnCoverage] + """Defines which input is included in the user's turn.""" + + +RealtimeInputConfigOrDict = Union[RealtimeInputConfig, RealtimeInputConfigDict] + + +class LiveConnectConfig(_common.BaseModel): + """Session config for the API connection.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + generation_config: Optional[GenerationConfig] = Field( + default=None, + description="""The generation configuration for the session.""", + ) + response_modalities: Optional[list[Modality]] = Field( + default=None, + description="""The requested modalities of the response. Represents the set of + modalities that the model can return. Defaults to AUDIO if not specified. + """, + ) + temperature: Optional[float] = Field( + default=None, + description="""Value that controls the degree of randomness in token selection. + Lower temperatures are good for prompts that require a less open-ended or + creative response, while higher temperatures can lead to more diverse or + creative results. + """, + ) + top_p: Optional[float] = Field( + default=None, + description="""Tokens are selected from the most to least probable until the sum + of their probabilities equals this value. Use a lower value for less + random responses and a higher value for more random responses. + """, + ) + top_k: Optional[float] = Field( + default=None, + description="""For each token selection step, the ``top_k`` tokens with the + highest probabilities are sampled. Then tokens are further filtered based + on ``top_p`` with the final token selected using temperature sampling. Use + a lower number for less random responses and a higher number for more + random responses. + """, + ) + max_output_tokens: Optional[int] = Field( + default=None, + description="""Maximum number of tokens that can be generated in the response. + """, + ) + media_resolution: Optional[MediaResolution] = Field( + default=None, + description="""If specified, the media resolution specified will be used. + """, + ) + seed: Optional[int] = Field( + default=None, + description="""When ``seed`` is fixed to a specific number, the model makes a best + effort to provide the same response for repeated requests. By default, a + random number is used. + """, + ) + speech_config: Optional[SpeechConfig] = Field( + default=None, + description="""The speech generation configuration. + """, + ) + thinking_config: Optional[ThinkingConfig] = Field( + default=None, + description="""Config for thinking features. + An error will be returned if this field is set for models that don't + support thinking. + """, + ) + enable_affective_dialog: Optional[bool] = Field( + default=None, + description="""If enabled, the model will detect emotions and adapt its responses accordingly.""", + ) + system_instruction: Optional[ContentUnion] = Field( + default=None, + description="""The user provided system instructions for the model. + Note: only text should be used in parts and content in each part will be + in a separate paragraph.""", + ) + tools: Optional[ToolListUnion] = Field( + default=None, + description="""A list of `Tools` the model may use to generate the next response. + + A `Tool` is a piece of code that enables the system to interact with + external systems to perform an action, or set of actions, outside of + knowledge and scope of the model.""", + ) + session_resumption: Optional[SessionResumptionConfig] = Field( + default=None, + description="""Configures session resumption mechanism. + +If included the server will send SessionResumptionUpdate messages.""", + ) + input_audio_transcription: Optional[AudioTranscriptionConfig] = Field( + default=None, + description="""The transcription of the input aligns with the input audio language. + """, + ) + output_audio_transcription: Optional[AudioTranscriptionConfig] = Field( + default=None, + description="""The transcription of the output aligns with the language code + specified for the output audio. + """, + ) + realtime_input_config: Optional[RealtimeInputConfig] = Field( + default=None, + description="""Configures the realtime input behavior in BidiGenerateContent.""", + ) + context_window_compression: Optional[ContextWindowCompressionConfig] = Field( + default=None, + description="""Configures context window compression mechanism. + + If included, server will compress context window to fit into given length.""", + ) + proactivity: Optional[ProactivityConfig] = Field( + default=None, + description="""Configures the proactivity of the model. This allows the model to respond proactively to + the input and to ignore irrelevant input.""", + ) + explicit_vad_signal: Optional[bool] = Field( + default=None, + description="""Configures the explicit VAD signal. If enabled, the client will send + vad_signal to indicate the start and end of speech. This allows the server + to process the audio more efficiently.""", + ) + history_config: Optional[HistoryConfig] = Field( + default=None, + description="""Configures the exchange of history between the client and the server.""", + ) + avatar_config: Optional[AvatarConfig] = Field( + default=None, description="""Configures the avatar model behavior.""" + ) + safety_settings: Optional[list[SafetySetting]] = Field( + default=None, + description="""Safety settings in the request to block unsafe content in the + response. + """, + ) + + +class LiveConnectConfigDict(TypedDict, total=False): + """Session config for the API connection.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + generation_config: Optional[GenerationConfigDict] + """The generation configuration for the session.""" + + response_modalities: Optional[list[Modality]] + """The requested modalities of the response. Represents the set of + modalities that the model can return. Defaults to AUDIO if not specified. + """ + + temperature: Optional[float] + """Value that controls the degree of randomness in token selection. + Lower temperatures are good for prompts that require a less open-ended or + creative response, while higher temperatures can lead to more diverse or + creative results. + """ + + top_p: Optional[float] + """Tokens are selected from the most to least probable until the sum + of their probabilities equals this value. Use a lower value for less + random responses and a higher value for more random responses. + """ + + top_k: Optional[float] + """For each token selection step, the ``top_k`` tokens with the + highest probabilities are sampled. Then tokens are further filtered based + on ``top_p`` with the final token selected using temperature sampling. Use + a lower number for less random responses and a higher number for more + random responses. + """ + + max_output_tokens: Optional[int] + """Maximum number of tokens that can be generated in the response. + """ + + media_resolution: Optional[MediaResolution] + """If specified, the media resolution specified will be used. + """ + + seed: Optional[int] + """When ``seed`` is fixed to a specific number, the model makes a best + effort to provide the same response for repeated requests. By default, a + random number is used. + """ + + speech_config: Optional[SpeechConfigDict] + """The speech generation configuration. + """ + + thinking_config: Optional[ThinkingConfigDict] + """Config for thinking features. + An error will be returned if this field is set for models that don't + support thinking. + """ + + enable_affective_dialog: Optional[bool] + """If enabled, the model will detect emotions and adapt its responses accordingly.""" + + system_instruction: Optional[ContentUnionDict] + """The user provided system instructions for the model. + Note: only text should be used in parts and content in each part will be + in a separate paragraph.""" + + tools: Optional[ToolListUnionDict] + """A list of `Tools` the model may use to generate the next response. + + A `Tool` is a piece of code that enables the system to interact with + external systems to perform an action, or set of actions, outside of + knowledge and scope of the model.""" + + session_resumption: Optional[SessionResumptionConfigDict] + """Configures session resumption mechanism. + +If included the server will send SessionResumptionUpdate messages.""" + + input_audio_transcription: Optional[AudioTranscriptionConfigDict] + """The transcription of the input aligns with the input audio language. + """ + + output_audio_transcription: Optional[AudioTranscriptionConfigDict] + """The transcription of the output aligns with the language code + specified for the output audio. + """ + + realtime_input_config: Optional[RealtimeInputConfigDict] + """Configures the realtime input behavior in BidiGenerateContent.""" + + context_window_compression: Optional[ContextWindowCompressionConfigDict] + """Configures context window compression mechanism. + + If included, server will compress context window to fit into given length.""" + + proactivity: Optional[ProactivityConfigDict] + """Configures the proactivity of the model. This allows the model to respond proactively to + the input and to ignore irrelevant input.""" + + explicit_vad_signal: Optional[bool] + """Configures the explicit VAD signal. If enabled, the client will send + vad_signal to indicate the start and end of speech. This allows the server + to process the audio more efficiently.""" + + history_config: Optional[HistoryConfigDict] + """Configures the exchange of history between the client and the server.""" + + avatar_config: Optional[AvatarConfigDict] + """Configures the avatar model behavior.""" + + safety_settings: Optional[list[SafetySettingDict]] + """Safety settings in the request to block unsafe content in the + response. + """ + + +LiveConnectConfigOrDict = Union[LiveConnectConfig, LiveConnectConfigDict] + + +class LiveConnectParameters(_common.BaseModel): + """Parameters for connecting to the live API.""" + + model: Optional[str] = Field( + default=None, + description="""ID of the model to use. For a list of models, see `Google models + `_.""", + ) + config: Optional[LiveConnectConfig] = Field( + default=None, + description="""Optional configuration parameters for the request. + """, + ) + + +class LiveConnectParametersDict(TypedDict, total=False): + """Parameters for connecting to the live API.""" + + model: Optional[str] + """ID of the model to use. For a list of models, see `Google models + `_.""" + + config: Optional[LiveConnectConfigDict] + """Optional configuration parameters for the request. + """ + + +LiveConnectParametersOrDict = Union[ + LiveConnectParameters, LiveConnectParametersDict +] + + +if _is_pillow_image_imported: + BlobImageUnion = Union[PIL_Image, Blob] +else: + BlobImageUnion = Blob # type: ignore[misc] + + +if _is_pillow_image_imported: + BlobImageUnionDict = Union[PIL_Image, Blob, BlobDict] +else: + BlobImageUnionDict = Union[Blob, BlobDict] # type: ignore[misc] + + +class LiveSendRealtimeInputParameters(_common.BaseModel): + """Parameters for sending realtime input to the live API.""" + + media: Optional[BlobImageUnion] = Field( + default=None, description="""Realtime input to send to the session.""" + ) + audio: Optional[Blob] = Field( + default=None, description="""The realtime audio input stream.""" + ) + audio_stream_end: Optional[bool] = Field( + default=None, + description=""" +Indicates that the audio stream has ended, e.g. because the microphone was +turned off. + +This should only be sent when automatic activity detection is enabled +(which is the default). + +The client can reopen the stream by sending an audio message. +""", + ) + video: Optional[BlobImageUnion] = Field( + default=None, description="""The realtime video input stream.""" + ) + text: Optional[str] = Field( + default=None, description="""The realtime text input stream.""" + ) + activity_start: Optional[ActivityStart] = Field( + default=None, description="""Marks the start of user activity.""" + ) + activity_end: Optional[ActivityEnd] = Field( + default=None, description="""Marks the end of user activity.""" + ) + + +class LiveSendRealtimeInputParametersDict(TypedDict, total=False): + """Parameters for sending realtime input to the live API.""" + + media: Optional[BlobImageUnionDict] + """Realtime input to send to the session.""" + + audio: Optional[BlobDict] + """The realtime audio input stream.""" + + audio_stream_end: Optional[bool] + """ +Indicates that the audio stream has ended, e.g. because the microphone was +turned off. + +This should only be sent when automatic activity detection is enabled +(which is the default). + +The client can reopen the stream by sending an audio message. +""" + + video: Optional[BlobImageUnionDict] + """The realtime video input stream.""" + + text: Optional[str] + """The realtime text input stream.""" + + activity_start: Optional[ActivityStartDict] + """Marks the start of user activity.""" + + activity_end: Optional[ActivityEndDict] + """Marks the end of user activity.""" + + +LiveSendRealtimeInputParametersOrDict = Union[ + LiveSendRealtimeInputParameters, LiveSendRealtimeInputParametersDict +] + + +class LiveMusicClientSetup(_common.BaseModel): + """Message to be sent by the system when connecting to the API.""" + + model: Optional[str] = Field( + default=None, + description="""The model's resource name. Format: `models/{model}`.""", + ) + + +class LiveMusicClientSetupDict(TypedDict, total=False): + """Message to be sent by the system when connecting to the API.""" + + model: Optional[str] + """The model's resource name. Format: `models/{model}`.""" + + +LiveMusicClientSetupOrDict = Union[ + LiveMusicClientSetup, LiveMusicClientSetupDict +] + + +class WeightedPrompt(_common.BaseModel): + """Maps a prompt to a relative weight to steer music generation.""" + + text: Optional[str] = Field(default=None, description="""Text prompt.""") + weight: Optional[float] = Field( + default=None, + description="""Weight of the prompt. The weight is used to control the relative + importance of the prompt. Higher weights are more important than lower + weights. + + Weight must not be 0. Weights of all weighted_prompts in this + LiveMusicClientContent message will be normalized.""", + ) + + +class WeightedPromptDict(TypedDict, total=False): + """Maps a prompt to a relative weight to steer music generation.""" + + text: Optional[str] + """Text prompt.""" + + weight: Optional[float] + """Weight of the prompt. The weight is used to control the relative + importance of the prompt. Higher weights are more important than lower + weights. + + Weight must not be 0. Weights of all weighted_prompts in this + LiveMusicClientContent message will be normalized.""" + + +WeightedPromptOrDict = Union[WeightedPrompt, WeightedPromptDict] + + +class LiveMusicClientContent(_common.BaseModel): + """User input to start or steer the music.""" + + weighted_prompts: Optional[list[WeightedPrompt]] = Field( + default=None, description="""Weighted prompts as the model input.""" + ) + + +class LiveMusicClientContentDict(TypedDict, total=False): + """User input to start or steer the music.""" + + weighted_prompts: Optional[list[WeightedPromptDict]] + """Weighted prompts as the model input.""" + + +LiveMusicClientContentOrDict = Union[ + LiveMusicClientContent, LiveMusicClientContentDict +] + + +class LiveMusicGenerationConfig(_common.BaseModel): + """Configuration for music generation.""" + + temperature: Optional[float] = Field( + default=None, + description="""Controls the variance in audio generation. Higher values produce + higher variance. Range is [0.0, 3.0].""", + ) + top_k: Optional[int] = Field( + default=None, + description="""Controls how the model selects tokens for output. Samples the topK + tokens with the highest probabilities. Range is [1, 1000].""", + ) + seed: Optional[int] = Field( + default=None, + description="""Seeds audio generation. If not set, the request uses a randomly + generated seed.""", + ) + guidance: Optional[float] = Field( + default=None, + description="""Controls how closely the model follows prompts. + Higher guidance follows more closely, but will make transitions more + abrupt. Range is [0.0, 6.0].""", + ) + bpm: Optional[int] = Field( + default=None, description="""Beats per minute. Range is [60, 200].""" + ) + density: Optional[float] = Field( + default=None, description="""Density of sounds. Range is [0.0, 1.0].""" + ) + brightness: Optional[float] = Field( + default=None, + description="""Brightness of the music. Range is [0.0, 1.0].""", + ) + scale: Optional[Scale] = Field( + default=None, description="""Scale of the generated music.""" + ) + mute_bass: Optional[bool] = Field( + default=None, + description="""Whether the audio output should contain bass.""", + ) + mute_drums: Optional[bool] = Field( + default=None, + description="""Whether the audio output should contain drums.""", + ) + only_bass_and_drums: Optional[bool] = Field( + default=None, + description="""Whether the audio output should contain only bass and drums.""", + ) + music_generation_mode: Optional[MusicGenerationMode] = Field( + default=None, + description="""The mode of music generation. Default mode is QUALITY.""", + ) + + +class LiveMusicGenerationConfigDict(TypedDict, total=False): + """Configuration for music generation.""" + + temperature: Optional[float] + """Controls the variance in audio generation. Higher values produce + higher variance. Range is [0.0, 3.0].""" + + top_k: Optional[int] + """Controls how the model selects tokens for output. Samples the topK + tokens with the highest probabilities. Range is [1, 1000].""" + + seed: Optional[int] + """Seeds audio generation. If not set, the request uses a randomly + generated seed.""" + + guidance: Optional[float] + """Controls how closely the model follows prompts. + Higher guidance follows more closely, but will make transitions more + abrupt. Range is [0.0, 6.0].""" + + bpm: Optional[int] + """Beats per minute. Range is [60, 200].""" + + density: Optional[float] + """Density of sounds. Range is [0.0, 1.0].""" + + brightness: Optional[float] + """Brightness of the music. Range is [0.0, 1.0].""" + + scale: Optional[Scale] + """Scale of the generated music.""" + + mute_bass: Optional[bool] + """Whether the audio output should contain bass.""" + + mute_drums: Optional[bool] + """Whether the audio output should contain drums.""" + + only_bass_and_drums: Optional[bool] + """Whether the audio output should contain only bass and drums.""" + + music_generation_mode: Optional[MusicGenerationMode] + """The mode of music generation. Default mode is QUALITY.""" + + +LiveMusicGenerationConfigOrDict = Union[ + LiveMusicGenerationConfig, LiveMusicGenerationConfigDict +] + + +class LiveMusicClientMessage(_common.BaseModel): + """Messages sent by the client in the LiveMusicClientMessage call.""" + + setup: Optional[LiveMusicClientSetup] = Field( + default=None, + description="""Message to be sent in the first (and only in the first) `LiveMusicClientMessage`. + Clients should wait for a `LiveMusicSetupComplete` message before + sending any additional messages.""", + ) + client_content: Optional[LiveMusicClientContent] = Field( + default=None, description="""User input to influence music generation.""" + ) + music_generation_config: Optional[LiveMusicGenerationConfig] = Field( + default=None, description="""Configuration for music generation.""" + ) + playback_control: Optional[LiveMusicPlaybackControl] = Field( + default=None, + description="""Playback control signal for the music generation.""", + ) + + +class LiveMusicClientMessageDict(TypedDict, total=False): + """Messages sent by the client in the LiveMusicClientMessage call.""" + + setup: Optional[LiveMusicClientSetupDict] + """Message to be sent in the first (and only in the first) `LiveMusicClientMessage`. + Clients should wait for a `LiveMusicSetupComplete` message before + sending any additional messages.""" + + client_content: Optional[LiveMusicClientContentDict] + """User input to influence music generation.""" + + music_generation_config: Optional[LiveMusicGenerationConfigDict] + """Configuration for music generation.""" + + playback_control: Optional[LiveMusicPlaybackControl] + """Playback control signal for the music generation.""" + + +LiveMusicClientMessageOrDict = Union[ + LiveMusicClientMessage, LiveMusicClientMessageDict +] + + +class LiveMusicServerSetupComplete(_common.BaseModel): + """Sent in response to a `LiveMusicClientSetup` message from the client.""" + + pass + + +class LiveMusicServerSetupCompleteDict(TypedDict, total=False): + """Sent in response to a `LiveMusicClientSetup` message from the client.""" + + pass + + +LiveMusicServerSetupCompleteOrDict = Union[ + LiveMusicServerSetupComplete, LiveMusicServerSetupCompleteDict +] + + +class LiveMusicSourceMetadata(_common.BaseModel): + """Prompts and config used for generating this audio chunk.""" + + client_content: Optional[LiveMusicClientContent] = Field( + default=None, + description="""Weighted prompts for generating this audio chunk.""", + ) + music_generation_config: Optional[LiveMusicGenerationConfig] = Field( + default=None, + description="""Music generation config for generating this audio chunk.""", + ) + + +class LiveMusicSourceMetadataDict(TypedDict, total=False): + """Prompts and config used for generating this audio chunk.""" + + client_content: Optional[LiveMusicClientContentDict] + """Weighted prompts for generating this audio chunk.""" + + music_generation_config: Optional[LiveMusicGenerationConfigDict] + """Music generation config for generating this audio chunk.""" + + +LiveMusicSourceMetadataOrDict = Union[ + LiveMusicSourceMetadata, LiveMusicSourceMetadataDict +] + + +class AudioChunk(_common.BaseModel): + """Representation of an audio chunk.""" + + data: Optional[bytes] = Field( + default=None, description="""Raw bytes of audio data.""" + ) + mime_type: Optional[str] = Field( + default=None, description="""MIME type of the audio chunk.""" + ) + source_metadata: Optional[LiveMusicSourceMetadata] = Field( + default=None, + description="""Prompts and config used for generating this audio chunk.""", + ) + + +class AudioChunkDict(TypedDict, total=False): + """Representation of an audio chunk.""" + + data: Optional[bytes] + """Raw bytes of audio data.""" + + mime_type: Optional[str] + """MIME type of the audio chunk.""" + + source_metadata: Optional[LiveMusicSourceMetadataDict] + """Prompts and config used for generating this audio chunk.""" + + +AudioChunkOrDict = Union[AudioChunk, AudioChunkDict] + + +class LiveMusicServerContent(_common.BaseModel): + """Server update generated by the model in response to client messages. + + Content is generated as quickly as possible, and not in real time. + Clients may choose to buffer and play it out in real time. + """ + + audio_chunks: Optional[list[AudioChunk]] = Field( + default=None, + description="""The audio chunks that the model has generated.""", + ) + + +class LiveMusicServerContentDict(TypedDict, total=False): + """Server update generated by the model in response to client messages. + + Content is generated as quickly as possible, and not in real time. + Clients may choose to buffer and play it out in real time. + """ + + audio_chunks: Optional[list[AudioChunkDict]] + """The audio chunks that the model has generated.""" + + +LiveMusicServerContentOrDict = Union[ + LiveMusicServerContent, LiveMusicServerContentDict +] + + +class LiveMusicFilteredPrompt(_common.BaseModel): + """A prompt that was filtered with the reason.""" + + text: Optional[str] = Field( + default=None, description="""The text prompt that was filtered.""" + ) + filtered_reason: Optional[str] = Field( + default=None, description="""The reason the prompt was filtered.""" + ) + + +class LiveMusicFilteredPromptDict(TypedDict, total=False): + """A prompt that was filtered with the reason.""" + + text: Optional[str] + """The text prompt that was filtered.""" + + filtered_reason: Optional[str] + """The reason the prompt was filtered.""" + + +LiveMusicFilteredPromptOrDict = Union[ + LiveMusicFilteredPrompt, LiveMusicFilteredPromptDict +] + + +class LiveMusicServerMessage(_common.BaseModel): + """Response message for the LiveMusicClientMessage call.""" + + setup_complete: Optional[LiveMusicServerSetupComplete] = Field( + default=None, + description="""Message sent in response to a `LiveMusicClientSetup` message from the client. + Clients should wait for this message before sending any additional messages.""", + ) + server_content: Optional[LiveMusicServerContent] = Field( + default=None, + description="""Content generated by the model in response to client messages.""", + ) + filtered_prompt: Optional[LiveMusicFilteredPrompt] = Field( + default=None, + description="""A prompt that was filtered with the reason.""", + ) + + +class LiveMusicServerMessageDict(TypedDict, total=False): + """Response message for the LiveMusicClientMessage call.""" + + setup_complete: Optional[LiveMusicServerSetupCompleteDict] + """Message sent in response to a `LiveMusicClientSetup` message from the client. + Clients should wait for this message before sending any additional messages.""" + + server_content: Optional[LiveMusicServerContentDict] + """Content generated by the model in response to client messages.""" + + filtered_prompt: Optional[LiveMusicFilteredPromptDict] + """A prompt that was filtered with the reason.""" + + +LiveMusicServerMessageOrDict = Union[ + LiveMusicServerMessage, LiveMusicServerMessageDict +] + + +class LiveMusicConnectParameters(_common.BaseModel): + """Parameters for connecting to the live API.""" + + model: Optional[str] = Field( + default=None, description="""The model's resource name.""" + ) + + +class LiveMusicConnectParametersDict(TypedDict, total=False): + """Parameters for connecting to the live API.""" + + model: Optional[str] + """The model's resource name.""" + + +LiveMusicConnectParametersOrDict = Union[ + LiveMusicConnectParameters, LiveMusicConnectParametersDict +] + + +class LiveMusicSetConfigParameters(_common.BaseModel): + """Parameters for setting config for the live music API.""" + + music_generation_config: Optional[LiveMusicGenerationConfig] = Field( + default=None, description="""Configuration for music generation.""" + ) + + +class LiveMusicSetConfigParametersDict(TypedDict, total=False): + """Parameters for setting config for the live music API.""" + + music_generation_config: Optional[LiveMusicGenerationConfigDict] + """Configuration for music generation.""" + + +LiveMusicSetConfigParametersOrDict = Union[ + LiveMusicSetConfigParameters, LiveMusicSetConfigParametersDict +] + + +class LiveMusicSetWeightedPromptsParameters(_common.BaseModel): + """Parameters for setting weighted prompts for the live music API.""" + + weighted_prompts: Optional[list[WeightedPrompt]] = Field( + default=None, + description="""A map of text prompts to weights to use for the generation request.""", + ) + + +class LiveMusicSetWeightedPromptsParametersDict(TypedDict, total=False): + """Parameters for setting weighted prompts for the live music API.""" + + weighted_prompts: Optional[list[WeightedPromptDict]] + """A map of text prompts to weights to use for the generation request.""" + + +LiveMusicSetWeightedPromptsParametersOrDict = Union[ + LiveMusicSetWeightedPromptsParameters, + LiveMusicSetWeightedPromptsParametersDict, +] + + +class AuthToken(_common.BaseModel): + """Config for auth_tokens.create parameters.""" + + name: Optional[str] = Field( + default=None, description="""The name of the auth token.""" + ) + + +class AuthTokenDict(TypedDict, total=False): + """Config for auth_tokens.create parameters.""" + + name: Optional[str] + """The name of the auth token.""" + + +AuthTokenOrDict = Union[AuthToken, AuthTokenDict] + + +class LiveConnectConstraints(_common.BaseModel): + """Config for LiveConnectConstraints for Auth Token creation.""" + + model: Optional[str] = Field( + default=None, + description="""ID of the model to configure in the ephemeral token for Live API. + For a list of models, see `Gemini models + `.""", + ) + config: Optional[LiveConnectConfig] = Field( + default=None, + description="""Configuration specific to Live API connections created using this token.""", + ) + + +class LiveConnectConstraintsDict(TypedDict, total=False): + """Config for LiveConnectConstraints for Auth Token creation.""" + + model: Optional[str] + """ID of the model to configure in the ephemeral token for Live API. + For a list of models, see `Gemini models + `.""" + + config: Optional[LiveConnectConfigDict] + """Configuration specific to Live API connections created using this token.""" + + +LiveConnectConstraintsOrDict = Union[ + LiveConnectConstraints, LiveConnectConstraintsDict +] + + +class CreateAuthTokenConfig(_common.BaseModel): + """Optional parameters.""" + + http_options: Optional[HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + expire_time: Optional[datetime.datetime] = Field( + default=None, + description="""An optional time after which, when using the resulting token, + messages in Live API sessions will be rejected. (Gemini may + preemptively close the session after this time.) + + If not set then this defaults to 30 minutes in the future. If set, this + value must be less than 20 hours in the future.""", + ) + new_session_expire_time: Optional[datetime.datetime] = Field( + default=None, + description="""The time after which new Live API sessions using the token + resulting from this request will be rejected. + + If not set this defaults to 60 seconds in the future. If set, this value + must be less than 20 hours in the future.""", + ) + uses: Optional[int] = Field( + default=None, + description="""The number of times the token can be used. If this value is zero + then no limit is applied. Default is 1. Resuming a Live API session does + not count as a use.""", + ) + live_connect_constraints: Optional[LiveConnectConstraints] = Field( + default=None, + description="""Configuration specific to Live API connections created using this token.""", + ) + lock_additional_fields: Optional[list[str]] = Field( + default=None, + description="""Additional fields to lock in the effective LiveConnectParameters.""", + ) + + +class CreateAuthTokenConfigDict(TypedDict, total=False): + """Optional parameters.""" + + http_options: Optional[HttpOptionsDict] + """Used to override HTTP request options.""" + + expire_time: Optional[datetime.datetime] + """An optional time after which, when using the resulting token, + messages in Live API sessions will be rejected. (Gemini may + preemptively close the session after this time.) + + If not set then this defaults to 30 minutes in the future. If set, this + value must be less than 20 hours in the future.""" + + new_session_expire_time: Optional[datetime.datetime] + """The time after which new Live API sessions using the token + resulting from this request will be rejected. + + If not set this defaults to 60 seconds in the future. If set, this value + must be less than 20 hours in the future.""" + + uses: Optional[int] + """The number of times the token can be used. If this value is zero + then no limit is applied. Default is 1. Resuming a Live API session does + not count as a use.""" + + live_connect_constraints: Optional[LiveConnectConstraintsDict] + """Configuration specific to Live API connections created using this token.""" + + lock_additional_fields: Optional[list[str]] + """Additional fields to lock in the effective LiveConnectParameters.""" + + +CreateAuthTokenConfigOrDict = Union[ + CreateAuthTokenConfig, CreateAuthTokenConfigDict +] + + +class CreateAuthTokenParameters(_common.BaseModel): + """Config for auth_tokens.create parameters.""" + + config: Optional[CreateAuthTokenConfig] = Field( + default=None, description="""Optional parameters for the request.""" + ) + + +class CreateAuthTokenParametersDict(TypedDict, total=False): + """Config for auth_tokens.create parameters.""" + + config: Optional[CreateAuthTokenConfigDict] + """Optional parameters for the request.""" + + +CreateAuthTokenParametersOrDict = Union[ + CreateAuthTokenParameters, CreateAuthTokenParametersDict +] + + +class CountTokensResult(_common.BaseModel): + """Local tokenizer count tokens result.""" + + total_tokens: Optional[int] = Field( + default=None, description="""The total number of tokens.""" + ) + + +class CountTokensResultDict(TypedDict, total=False): + """Local tokenizer count tokens result.""" + + total_tokens: Optional[int] + """The total number of tokens.""" + + +CountTokensResultOrDict = Union[CountTokensResult, CountTokensResultDict] + + +class ComputeTokensResult(_common.BaseModel): + """Local tokenizer compute tokens result.""" + + tokens_info: Optional[list[TokensInfo]] = Field( + default=None, description="""Lists of tokens info from the input.""" + ) + + +class ComputeTokensResultDict(TypedDict, total=False): + """Local tokenizer compute tokens result.""" + + tokens_info: Optional[list[TokensInfoDict]] + """Lists of tokens info from the input.""" + + +ComputeTokensResultOrDict = Union[ComputeTokensResult, ComputeTokensResultDict] + + +class CreateTuningJobParameters(_common.BaseModel): + """Fine-tuning job creation parameters - optional fields.""" + + base_model: Optional[str] = Field( + default=None, + description="""The base model that is being tuned, e.g., "gemini-2.5-flash".""", + ) + training_dataset: Optional[TuningDataset] = Field( + default=None, + description="""Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file.""", + ) + config: Optional[CreateTuningJobConfig] = Field( + default=None, description="""Configuration for the tuning job.""" + ) + + +class CreateTuningJobParametersDict(TypedDict, total=False): + """Fine-tuning job creation parameters - optional fields.""" + + base_model: Optional[str] + """The base model that is being tuned, e.g., "gemini-2.5-flash".""" + + training_dataset: Optional[TuningDatasetDict] + """Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file.""" + + config: Optional[CreateTuningJobConfigDict] + """Configuration for the tuning job.""" + + +CreateTuningJobParametersOrDict = Union[ + CreateTuningJobParameters, CreateTuningJobParametersDict +] + + +class EmbedContentParameters(_common.BaseModel): + """Parameters for the embed_content method.""" + + model: Optional[str] = Field( + default=None, + description="""ID of the model to use. For a list of models, see `Google models + `_.""", + ) + contents: Optional[ContentListUnion] = Field( + default=None, + description="""The content to embed. Only the `parts.text` fields will be counted. + """, + ) + config: Optional[EmbedContentConfig] = Field( + default=None, + description="""Configuration that contains optional parameters. + """, + ) + + +class EmbedContentParametersDict(TypedDict, total=False): + """Parameters for the embed_content method.""" + + model: Optional[str] + """ID of the model to use. For a list of models, see `Google models + `_.""" + + contents: Optional[ContentListUnionDict] + """The content to embed. Only the `parts.text` fields will be counted. + """ + + config: Optional[EmbedContentConfigDict] + """Configuration that contains optional parameters. + """ + + +EmbedContentParametersOrDict = Union[ + EmbedContentParameters, EmbedContentParametersDict +] + + +class UserContent(Content): + """UserContent facilitates the creation of a Content object with a user role. + + Example usages: + + + - Create a user Content object with a string: + user_content = UserContent("Why is the sky blue?") + - Create a user Content object with a file data Part object: + user_content = UserContent(Part.from_uri(file_uril="gs://bucket/file.txt", + mime_type="text/plain")) + - Create a user Content object with byte data Part object: + user_content = UserContent(Part.from_bytes(data=b"Hello, World!", + mime_type="text/plain")) + + You can create a user Content object using other classmethods in the Part + class as well. + You can also create a user Content using a list of Part objects or strings. + """ + + role: Literal['user'] = Field(default='user', init=False, frozen=True) + parts: list[Part] = Field() + + def __init__( + self, parts: Union['PartUnionDict', list['PartUnionDict'], list['Part']] + ): + from . import _transformers as t + + super().__init__(parts=t.t_parts(parts=parts)) + + +class ModelContent(Content): + """ModelContent facilitates the creation of a Content object with a model role. + + Example usages: + + - Create a model Content object with a string: + model_content = ModelContent("Why is the sky blue?") + - Create a model Content object with a file data Part object: + model_content = ModelContent(Part.from_uri(file_uril="gs://bucket/file.txt", + mime_type="text/plain")) + - Create a model Content object with byte data Part object: + model_content = ModelContent(Part.from_bytes(data=b"Hello, World!", + mime_type="text/plain")) + + You can create a model Content object using other classmethods in the Part + class as well. + You can also create a model Content using a list of Part objects or strings. + """ + + role: Literal['model'] = Field(default='model', init=False, frozen=True) + parts: list[Part] = Field() + + def __init__( + self, parts: Union['PartUnionDict', list['PartUnionDict'], list['Part']] + ): + from . import _transformers as t + + super().__init__(parts=t.t_parts(parts=parts)) + + +class CustomOutputFormatConfig(_common.BaseModel): + """Config for custom output format.""" + + return_raw_output: Optional[bool] = Field( + default=None, description="""Optional. Whether to return raw output.""" + ) + + +class CustomOutputFormatConfigDict(TypedDict, total=False): + """Config for custom output format.""" + + return_raw_output: Optional[bool] + """Optional. Whether to return raw output.""" + + +CustomOutputFormatConfigOrDict = Union[ + CustomOutputFormatConfig, CustomOutputFormatConfigDict +] + + +class BleuSpec(_common.BaseModel): + """Spec for bleu metric.""" + + use_effective_order: Optional[bool] = Field( + default=None, + description="""Optional. Whether to use_effective_order to compute bleu score.""", + ) + + +class BleuSpecDict(TypedDict, total=False): + """Spec for bleu metric.""" + + use_effective_order: Optional[bool] + """Optional. Whether to use_effective_order to compute bleu score.""" + + +BleuSpecOrDict = Union[BleuSpec, BleuSpecDict] + + +class Metric(_common.BaseModel): + """The metric used for evaluation.""" + + name: Optional[str] = Field( + default=None, description="""The name of the metric.""" + ) + custom_function: Optional[Callable[..., Any]] = Field( + default=None, + description="""The custom function that defines the end-to-end logic for metric computation.""", + ) + prompt_template: Optional[str] = Field( + default=None, description="""The prompt template for the metric.""" + ) + judge_model_system_instruction: Optional[str] = Field( + default=None, + description="""The system instruction for the judge model.""", + ) + return_raw_output: Optional[bool] = Field( + default=None, + description="""Whether to return the raw output from the judge model.""", + ) + parse_and_reduce_fn: Optional[Callable[..., Any]] = Field( + default=None, + description="""The parse and reduce function for the judge model.""", + ) + aggregate_summary_fn: Optional[Callable[..., Any]] = Field( + default=None, + description="""The aggregate summary function for the judge model.""", + ) + + # Allow extra fields to support metric-specific config fields. + model_config = ConfigDict(extra='allow') + + _is_predefined: bool = PrivateAttr(default=False) + """A boolean indicating whether the metric is predefined.""" + + _config_source: Optional[str] = PrivateAttr(default=None) + """An optional string indicating the source of the metric configuration.""" + + _version: Optional[str] = PrivateAttr(default=None) + """An optional string indicating the version of the metric.""" + + @model_validator(mode='after') # type: ignore[arg-type] + def validate_name(self) -> 'Metric': + if not self.name: + raise ValueError('Metric name cannot be empty.') + self.name = self.name.lower() + return self + + def to_yaml_file(self, file_path: str, version: Optional[str] = None) -> None: + """Dumps the metric object to a YAML file. + + Args: + file_path: The path to the YAML file. + version: Optional version string to include in the YAML output. + + Raises: + ImportError: If the pyyaml library is not installed. + """ + try: + import yaml + except ImportError: + raise ImportError( + 'YAML serialization requires the pyyaml library. Please install' + " it using 'pip install google-cloud-aiplatform[evaluation]'." + ) + + fields_to_exclude_callables = set() + for field_name, field_info in self.model_fields.items(): + annotation = field_info.annotation + origin = typing.get_origin(annotation) + + is_field_callable_type = False + if annotation is Callable or origin is Callable: # type: ignore[comparison-overlap] + is_field_callable_type = True + elif origin is Union: + args = typing.get_args(annotation) + if any( + arg is Callable or typing.get_origin(arg) is Callable + for arg in args + ): + is_field_callable_type = True + + if is_field_callable_type: + fields_to_exclude_callables.add(field_name) + + data_to_dump = self.model_dump( + exclude_unset=True, + exclude_none=True, + mode='json', + exclude=fields_to_exclude_callables + if fields_to_exclude_callables + else None, + ) + + if version: + data_to_dump['version'] = version + + with open(file_path, 'w', encoding='utf-8') as f: + yaml.dump(data_to_dump, f, sort_keys=False, allow_unicode=True) + + +class MetricDict(TypedDict, total=False): + """The metric used for evaluation.""" + + name: Optional[str] + """The name of the metric.""" + + custom_function: Optional[Callable[..., Any]] + """The custom function that defines the end-to-end logic for metric computation.""" + + prompt_template: Optional[str] + """The prompt template for the metric.""" + + judge_model_system_instruction: Optional[str] + """The system instruction for the judge model.""" + + return_raw_output: Optional[bool] + """Whether to return the raw output from the judge model.""" + + parse_and_reduce_fn: Optional[Callable[..., Any]] + """The parse and reduce function for the judge model.""" + + aggregate_summary_fn: Optional[Callable[..., Any]] + """The aggregate summary function for the judge model.""" + + +MetricOrDict = Union[Metric, MetricDict] + + +class PairwiseMetricSpec(_common.BaseModel): + """Spec for pairwise metric.""" + + metric_prompt_template: Optional[str] = Field( + default=None, + description="""Required. Metric prompt template for pairwise metric.""", + ) + baseline_response_field_name: Optional[str] = Field( + default=None, + description="""Optional. The field name of the baseline response.""", + ) + candidate_response_field_name: Optional[str] = Field( + default=None, + description="""Optional. The field name of the candidate response.""", + ) + custom_output_format_config: Optional[CustomOutputFormatConfig] = Field( + default=None, + description="""Optional. CustomOutputFormatConfig allows customization of metric output. When this config is set, the default output is replaced with the raw output string. If a custom format is chosen, the `pairwise_choice` and `explanation` fields in the corresponding metric result will be empty.""", + ) + system_instruction: Optional[str] = Field( + default=None, + description="""Optional. System instructions for pairwise metric.""", + ) + + +class PairwiseMetricSpecDict(TypedDict, total=False): + """Spec for pairwise metric.""" + + metric_prompt_template: Optional[str] + """Required. Metric prompt template for pairwise metric.""" + + baseline_response_field_name: Optional[str] + """Optional. The field name of the baseline response.""" + + candidate_response_field_name: Optional[str] + """Optional. The field name of the candidate response.""" + + custom_output_format_config: Optional[CustomOutputFormatConfigDict] + """Optional. CustomOutputFormatConfig allows customization of metric output. When this config is set, the default output is replaced with the raw output string. If a custom format is chosen, the `pairwise_choice` and `explanation` fields in the corresponding metric result will be empty.""" + + system_instruction: Optional[str] + """Optional. System instructions for pairwise metric.""" + + +PairwiseMetricSpecOrDict = Union[PairwiseMetricSpec, PairwiseMetricSpecDict] + + +class PointwiseMetricSpec(_common.BaseModel): + """Spec for pointwise metric.""" + + metric_prompt_template: Optional[str] = Field( + default=None, + description="""Required. Metric prompt template for pointwise metric.""", + ) + custom_output_format_config: Optional[CustomOutputFormatConfig] = Field( + default=None, + description="""Optional. CustomOutputFormatConfig allows customization of metric output. By default, metrics return a score and explanation. When this config is set, the default output is replaced with either: - The raw output string. - A parsed output based on a user-defined schema. If a custom format is chosen, the `score` and `explanation` fields in the corresponding metric result will be empty.""", + ) + system_instruction: Optional[str] = Field( + default=None, + description="""Optional. System instructions for pointwise metric.""", + ) + + +class PointwiseMetricSpecDict(TypedDict, total=False): + """Spec for pointwise metric.""" + + metric_prompt_template: Optional[str] + """Required. Metric prompt template for pointwise metric.""" + + custom_output_format_config: Optional[CustomOutputFormatConfigDict] + """Optional. CustomOutputFormatConfig allows customization of metric output. By default, metrics return a score and explanation. When this config is set, the default output is replaced with either: - The raw output string. - A parsed output based on a user-defined schema. If a custom format is chosen, the `score` and `explanation` fields in the corresponding metric result will be empty.""" + + system_instruction: Optional[str] + """Optional. System instructions for pointwise metric.""" + + +PointwiseMetricSpecOrDict = Union[PointwiseMetricSpec, PointwiseMetricSpecDict] + + +class RougeSpec(_common.BaseModel): + """Spec for rouge metric.""" + + rouge_type: Optional[str] = Field( + default=None, + description="""Optional. Supported rouge types are rougen[1-9], rougeL, and rougeLsum.""", + ) + split_summaries: Optional[bool] = Field( + default=None, + description="""Optional. Whether to split summaries while using rougeLsum.""", + ) + use_stemmer: Optional[bool] = Field( + default=None, + description="""Optional. Whether to use stemmer to compute rouge score.""", + ) + + +class RougeSpecDict(TypedDict, total=False): + """Spec for rouge metric.""" + + rouge_type: Optional[str] + """Optional. Supported rouge types are rougen[1-9], rougeL, and rougeLsum.""" + + split_summaries: Optional[bool] + """Optional. Whether to split summaries while using rougeLsum.""" + + use_stemmer: Optional[bool] + """Optional. Whether to use stemmer to compute rouge score.""" + + +RougeSpecOrDict = Union[RougeSpec, RougeSpecDict] + + +class PredefinedMetricSpec(_common.BaseModel): + """Spec for predefined metric.""" + + metric_spec_name: Optional[str] = Field( + default=None, + description="""The name of a pre-defined metric, such as "instruction_following_v1" or + "text_quality_v1".""", + ) + metric_spec_parameters: Optional[dict[str, Any]] = Field( + default=None, + description="""The parameters needed to run the pre-defined metric.""", + ) + + +class PredefinedMetricSpecDict(TypedDict, total=False): + """Spec for predefined metric.""" + + metric_spec_name: Optional[str] + """The name of a pre-defined metric, such as "instruction_following_v1" or + "text_quality_v1".""" + + metric_spec_parameters: Optional[dict[str, Any]] + """The parameters needed to run the pre-defined metric.""" + + +PredefinedMetricSpecOrDict = Union[ + PredefinedMetricSpec, PredefinedMetricSpecDict +] + + +class RubricGenerationSpec(_common.BaseModel): + """Specification for how rubrics should be generated.""" + + prompt_template: Optional[str] = Field( + default=None, + description="""Template for the prompt used to generate rubrics.""", + ) + rubric_content_type: Optional[RubricContentType] = Field( + default=None, + description="""The type of rubric content to be generated.""", + ) + rubric_type_ontology: Optional[list[str]] = Field( + default=None, + description="""An optional, pre-defined list of allowed types for generated rubrics. + If this field is provided, it implies `include_rubric_type` should be true, + and the generated rubric types should be chosen from this ontology.""", + ) + + +class RubricGenerationSpecDict(TypedDict, total=False): + """Specification for how rubrics should be generated.""" + + prompt_template: Optional[str] + """Template for the prompt used to generate rubrics.""" + + rubric_content_type: Optional[RubricContentType] + """The type of rubric content to be generated.""" + + rubric_type_ontology: Optional[list[str]] + """An optional, pre-defined list of allowed types for generated rubrics. + If this field is provided, it implies `include_rubric_type` should be true, + and the generated rubric types should be chosen from this ontology.""" + + +RubricGenerationSpecOrDict = Union[ + RubricGenerationSpec, RubricGenerationSpecDict +] + + +class LLMBasedMetricSpec(_common.BaseModel): + """Specification for an LLM based metric.""" + + metric_prompt_template: Optional[str] = Field( + default=None, + description="""Template for the prompt sent to the judge model.""", + ) + system_instruction: Optional[str] = Field( + default=None, description="""System instruction for the judge model.""" + ) + judge_autorater_config: Optional[AutoraterConfig] = Field( + default=None, + description="""Optional configuration for the judge LLM (Autorater).""", + ) + rubric_group_key: Optional[str] = Field( + default=None, + description="""Use a pre-defined group of rubrics associated with the input. + Refers to a key in the rubric_groups map of EvaluationInstance.""", + ) + predefined_rubric_generation_spec: Optional[PredefinedMetricSpec] = Field( + default=None, + description="""Dynamically generate rubrics using a predefined spec.""", + ) + rubric_generation_spec: Optional[RubricGenerationSpec] = Field( + default=None, + description="""Dynamically generate rubrics using this specification.""", + ) + additional_config: Optional[dict[str, Any]] = Field( + default=None, + description="""Optional. Optional additional configuration for the metric.""", + ) + + +class LLMBasedMetricSpecDict(TypedDict, total=False): + """Specification for an LLM based metric.""" + + metric_prompt_template: Optional[str] + """Template for the prompt sent to the judge model.""" + + system_instruction: Optional[str] + """System instruction for the judge model.""" + + judge_autorater_config: Optional[AutoraterConfigDict] + """Optional configuration for the judge LLM (Autorater).""" + + rubric_group_key: Optional[str] + """Use a pre-defined group of rubrics associated with the input. + Refers to a key in the rubric_groups map of EvaluationInstance.""" + + predefined_rubric_generation_spec: Optional[PredefinedMetricSpecDict] + """Dynamically generate rubrics using a predefined spec.""" + + rubric_generation_spec: Optional[RubricGenerationSpecDict] + """Dynamically generate rubrics using this specification.""" + + additional_config: Optional[dict[str, Any]] + """Optional. Optional additional configuration for the metric.""" + + +LLMBasedMetricSpecOrDict = Union[LLMBasedMetricSpec, LLMBasedMetricSpecDict] + + +class CustomCodeExecutionSpec(_common.BaseModel): + """Specificies a metric that is computed by running user-defined Python functions remotely.""" + + evaluation_function: Optional[str] = Field( + default=None, + description="""A string representing a user-defined function for evaluation. + Expected user to define the following function, e.g.: + def evaluate(instance: dict[str, Any]) -> float: + Please include this function signature in the code snippet. + Instance is the evaluation instance, any fields populated in the instance + are available to the function as instance[field_name].""", + ) + + +class CustomCodeExecutionSpecDict(TypedDict, total=False): + """Specificies a metric that is computed by running user-defined Python functions remotely.""" + + evaluation_function: Optional[str] + """A string representing a user-defined function for evaluation. + Expected user to define the following function, e.g.: + def evaluate(instance: dict[str, Any]) -> float: + Please include this function signature in the code snippet. + Instance is the evaluation instance, any fields populated in the instance + are available to the function as instance[field_name].""" + + +CustomCodeExecutionSpecOrDict = Union[ + CustomCodeExecutionSpec, CustomCodeExecutionSpecDict +] + + +class ComputationBasedMetricSpec(_common.BaseModel): + """Specification for a computation based metric.""" + + type: Optional[ComputationBasedMetricType] = Field( + default=None, description="""The type of the computation based metric.""" + ) + parameters: Optional[dict[str, Any]] = Field( + default=None, + description="""A map of parameters for the metric. ROUGE example: {"rouge_type": "rougeL", "split_summaries": True, "use_stemmer": True}. BLEU example: {"use_effective_order": True}.""", + ) + + +class ComputationBasedMetricSpecDict(TypedDict, total=False): + """Specification for a computation based metric.""" + + type: Optional[ComputationBasedMetricType] + """The type of the computation based metric.""" + + parameters: Optional[dict[str, Any]] + """A map of parameters for the metric. ROUGE example: {"rouge_type": "rougeL", "split_summaries": True, "use_stemmer": True}. BLEU example: {"use_effective_order": True}.""" + + +ComputationBasedMetricSpecOrDict = Union[ + ComputationBasedMetricSpec, ComputationBasedMetricSpecDict +] + + +class UnifiedMetric(_common.BaseModel): + """The unified metric used for evaluation.""" + + bleu_spec: Optional[BleuSpec] = Field( + default=None, description="""The Bleu metric spec.""" + ) + rouge_spec: Optional[RougeSpec] = Field( + default=None, description="""The rouge metric spec.""" + ) + pointwise_metric_spec: Optional[PointwiseMetricSpec] = Field( + default=None, description="""The pointwise metric spec.""" + ) + llm_based_metric_spec: Optional[LLMBasedMetricSpec] = Field( + default=None, description="""The spec for an LLM based metric.""" + ) + custom_code_execution_spec: Optional[CustomCodeExecutionSpec] = Field( + default=None, + description="""The spec for a custom code execution metric.""", + ) + predefined_metric_spec: Optional[PredefinedMetricSpec] = Field( + default=None, description="""The spec for a pre-defined metric.""" + ) + computation_based_metric_spec: Optional[ComputationBasedMetricSpec] = Field( + default=None, description="""The spec for a computation based metric.""" + ) + + +class UnifiedMetricDict(TypedDict, total=False): + """The unified metric used for evaluation.""" + + bleu_spec: Optional[BleuSpecDict] + """The Bleu metric spec.""" + + rouge_spec: Optional[RougeSpecDict] + """The rouge metric spec.""" + + pointwise_metric_spec: Optional[PointwiseMetricSpecDict] + """The pointwise metric spec.""" + + llm_based_metric_spec: Optional[LLMBasedMetricSpecDict] + """The spec for an LLM based metric.""" + + custom_code_execution_spec: Optional[CustomCodeExecutionSpecDict] + """The spec for a custom code execution metric.""" + + predefined_metric_spec: Optional[PredefinedMetricSpecDict] + """The spec for a pre-defined metric.""" + + computation_based_metric_spec: Optional[ComputationBasedMetricSpecDict] + """The spec for a computation based metric.""" + + +UnifiedMetricOrDict = Union[UnifiedMetric, UnifiedMetricDict] + + +class UploadToFileSearchStoreResponse(_common.BaseModel): + """The response when long-running operation for uploading a file to a FileSearchStore complete.""" + + sdk_http_response: Optional[HttpResponse] = Field( + default=None, description="""Used to retain the full HTTP response.""" + ) + parent: Optional[str] = Field( + default=None, + description="""The name of the FileSearchStore containing Documents.""", + ) + document_name: Optional[str] = Field( + default=None, description="""The identifier for the Document imported.""" + ) + + +class UploadToFileSearchStoreResponseDict(TypedDict, total=False): + """The response when long-running operation for uploading a file to a FileSearchStore complete.""" + + sdk_http_response: Optional[HttpResponseDict] + """Used to retain the full HTTP response.""" + + parent: Optional[str] + """The name of the FileSearchStore containing Documents.""" + + document_name: Optional[str] + """The identifier for the Document imported.""" + + +UploadToFileSearchStoreResponseOrDict = Union[ + UploadToFileSearchStoreResponse, UploadToFileSearchStoreResponseDict +] + + +class UploadToFileSearchStoreOperation(_common.BaseModel, Operation): + """Long-running operation for uploading a file to a FileSearchStore.""" + + response: Optional[UploadToFileSearchStoreResponse] = Field( + default=None, + description="""The result of the UploadToFileSearchStore operation, available when the operation is done.""", + ) + + @classmethod + def from_api_response( + cls, api_response: Any, is_vertex_ai: bool = False + ) -> Self: + """Instantiates a UploadToFileSearchStoreOperation from an API response.""" + + response_dict = _UploadToFileSearchStoreOperation_from_mldev(api_response) + return cls._from_response(response=response_dict, kwargs={}) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/genai/version.py b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/version.py new file mode 100644 index 0000000000000000000000000000000000000000..d18bbdc1a4112c3734607e0c29adc2137a8cecb8 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/genai/version.py @@ -0,0 +1,16 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. +# + +__version__ = '1.73.1' # x-release-please-version diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..63f1632862758581cb1a71bc5f9156d6610272f8 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/__init__.py @@ -0,0 +1,13 @@ +# Copyright 2022 Google LLC +# +# Licensed 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. diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/__pycache__/__init__.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..50af396954de8d98353dc5edcc80fdcfee319173 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/__pycache__/__init__.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/__pycache__/iam_policy_pb2.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/__pycache__/iam_policy_pb2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9168afeaafaf9d8859ce8ef9422c2c34de6638dd Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/__pycache__/iam_policy_pb2.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/__pycache__/options_pb2.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/__pycache__/options_pb2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee8063a587e2362ccecacb8ae74772fcfd9d036d Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/__pycache__/options_pb2.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/__pycache__/policy_pb2.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/__pycache__/policy_pb2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51cfd7690fe8cad84c7dd98089044838a273eca3 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/__pycache__/policy_pb2.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/iam_policy.proto b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/iam_policy.proto new file mode 100644 index 0000000000000000000000000000000000000000..a123ab8411f8cb3e3a2bc9f915f1d6cf8063d6d7 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/iam_policy.proto @@ -0,0 +1,157 @@ +// Copyright 2025 Google LLC +// +// Licensed 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. + +syntax = "proto3"; + +package google.iam.v1; + +import "google/api/annotations.proto"; +import "google/api/client.proto"; +import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; +import "google/iam/v1/options.proto"; +import "google/iam/v1/policy.proto"; +import "google/protobuf/field_mask.proto"; + +option csharp_namespace = "Google.Cloud.Iam.V1"; +option go_package = "cloud.google.com/go/iam/apiv1/iampb;iampb"; +option java_multiple_files = true; +option java_outer_classname = "IamPolicyProto"; +option java_package = "com.google.iam.v1"; +option php_namespace = "Google\\Cloud\\Iam\\V1"; + +// API Overview +// +// Manages Identity and Access Management (IAM) policies. +// +// Any implementation of an API that offers access control features +// implements the google.iam.v1.IAMPolicy interface. +// +// ## Data model +// +// Access control is applied when a principal (user or service account), takes +// some action on a resource exposed by a service. Resources, identified by +// URI-like names, are the unit of access control specification. Service +// implementations can choose the granularity of access control and the +// supported permissions for their resources. +// For example one database service may allow access control to be +// specified only at the Table level, whereas another might allow access control +// to also be specified at the Column level. +// +// ## Policy Structure +// +// See google.iam.v1.Policy +// +// This is intentionally not a CRUD style API because access control policies +// are created and deleted implicitly with the resources to which they are +// attached. +service IAMPolicy { + option (google.api.default_host) = "iam-meta-api.googleapis.com"; + + // Sets the access control policy on the specified resource. Replaces any + // existing policy. + // + // Can return `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED` errors. + rpc SetIamPolicy(SetIamPolicyRequest) returns (Policy) { + option (google.api.http) = { + post: "/v1/{resource=**}:setIamPolicy" + body: "*" + }; + } + + // Gets the access control policy for a resource. + // Returns an empty policy if the resource exists and does not have a policy + // set. + rpc GetIamPolicy(GetIamPolicyRequest) returns (Policy) { + option (google.api.http) = { + post: "/v1/{resource=**}:getIamPolicy" + body: "*" + }; + } + + // Returns permissions that a caller has on the specified resource. + // If the resource does not exist, this will return an empty set of + // permissions, not a `NOT_FOUND` error. + // + // Note: This operation is designed to be used for building permission-aware + // UIs and command-line tools, not for authorization checking. This operation + // may "fail open" without warning. + rpc TestIamPermissions(TestIamPermissionsRequest) + returns (TestIamPermissionsResponse) { + option (google.api.http) = { + post: "/v1/{resource=**}:testIamPermissions" + body: "*" + }; + } +} + +// Request message for `SetIamPolicy` method. +message SetIamPolicyRequest { + // REQUIRED: The resource for which the policy is being specified. + // See the operation documentation for the appropriate value for this field. + string resource = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference).type = "*" + ]; + + // REQUIRED: The complete policy to be applied to the `resource`. The size of + // the policy is limited to a few 10s of KB. An empty policy is a + // valid policy but certain Cloud Platform services (such as Projects) + // might reject them. + Policy policy = 2 [(google.api.field_behavior) = REQUIRED]; + + // OPTIONAL: A FieldMask specifying which fields of the policy to modify. Only + // the fields in the mask will be modified. If no mask is provided, the + // following default mask is used: + // + // `paths: "bindings, etag"` + google.protobuf.FieldMask update_mask = 3; +} + +// Request message for `GetIamPolicy` method. +message GetIamPolicyRequest { + // REQUIRED: The resource for which the policy is being requested. + // See the operation documentation for the appropriate value for this field. + string resource = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference).type = "*" + ]; + + // OPTIONAL: A `GetPolicyOptions` object for specifying options to + // `GetIamPolicy`. + GetPolicyOptions options = 2; +} + +// Request message for `TestIamPermissions` method. +message TestIamPermissionsRequest { + // REQUIRED: The resource for which the policy detail is being requested. + // See the operation documentation for the appropriate value for this field. + string resource = 1 [ + (google.api.field_behavior) = REQUIRED, + (google.api.resource_reference).type = "*" + ]; + + // The set of permissions to check for the `resource`. Permissions with + // wildcards (such as '*' or 'storage.*') are not allowed. For more + // information see + // [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions). + repeated string permissions = 2 [(google.api.field_behavior) = REQUIRED]; +} + +// Response message for `TestIamPermissions` method. +message TestIamPermissionsResponse { + // A subset of `TestPermissionsRequest.permissions` that the caller is + // allowed. + repeated string permissions = 1; +} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/iam_policy_pb2.py b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/iam_policy_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..bdd73b609ebcc541b38ce867e3e0d666c9dddfa4 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/iam_policy_pb2.py @@ -0,0 +1,104 @@ +# -*- coding: utf-8 -*- + +# Copyright 2025 Google LLC +# +# Licensed 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. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/iam/v1/iam_policy.proto +# Protobuf Python Version: 4.25.3 +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 +from google.api import client_pb2 as google_dot_api_dot_client__pb2 +from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 +from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 +from google.iam.v1 import options_pb2 as google_dot_iam_dot_v1_dot_options__pb2 +from google.iam.v1 import policy_pb2 as google_dot_iam_dot_v1_dot_policy__pb2 +from google.protobuf import field_mask_pb2 as google_dot_protobuf_dot_field__mask__pb2 + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b'\n\x1egoogle/iam/v1/iam_policy.proto\x12\rgoogle.iam.v1\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a\x1bgoogle/iam/v1/options.proto\x1a\x1agoogle/iam/v1/policy.proto\x1a google/protobuf/field_mask.proto"\x8f\x01\n\x13SetIamPolicyRequest\x12\x1b\n\x08resource\x18\x01 \x01(\tB\t\xe0\x41\x02\xfa\x41\x03\n\x01*\x12*\n\x06policy\x18\x02 \x01(\x0b\x32\x15.google.iam.v1.PolicyB\x03\xe0\x41\x02\x12/\n\x0bupdate_mask\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.FieldMask"d\n\x13GetIamPolicyRequest\x12\x1b\n\x08resource\x18\x01 \x01(\tB\t\xe0\x41\x02\xfa\x41\x03\n\x01*\x12\x30\n\x07options\x18\x02 \x01(\x0b\x32\x1f.google.iam.v1.GetPolicyOptions"R\n\x19TestIamPermissionsRequest\x12\x1b\n\x08resource\x18\x01 \x01(\tB\t\xe0\x41\x02\xfa\x41\x03\n\x01*\x12\x18\n\x0bpermissions\x18\x02 \x03(\tB\x03\xe0\x41\x02"1\n\x1aTestIamPermissionsResponse\x12\x13\n\x0bpermissions\x18\x01 \x03(\t2\xb4\x03\n\tIAMPolicy\x12t\n\x0cSetIamPolicy\x12".google.iam.v1.SetIamPolicyRequest\x1a\x15.google.iam.v1.Policy")\x82\xd3\xe4\x93\x02#"\x1e/v1/{resource=**}:setIamPolicy:\x01*\x12t\n\x0cGetIamPolicy\x12".google.iam.v1.GetIamPolicyRequest\x1a\x15.google.iam.v1.Policy")\x82\xd3\xe4\x93\x02#"\x1e/v1/{resource=**}:getIamPolicy:\x01*\x12\x9a\x01\n\x12TestIamPermissions\x12(.google.iam.v1.TestIamPermissionsRequest\x1a).google.iam.v1.TestIamPermissionsResponse"/\x82\xd3\xe4\x93\x02)"$/v1/{resource=**}:testIamPermissions:\x01*\x1a\x1e\xca\x41\x1biam-meta-api.googleapis.comB|\n\x11\x63om.google.iam.v1B\x0eIamPolicyProtoP\x01Z)cloud.google.com/go/iam/apiv1/iampb;iampb\xaa\x02\x13Google.Cloud.Iam.V1\xca\x02\x13Google\\Cloud\\Iam\\V1b\x06proto3' +) + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages( + DESCRIPTOR, "google.iam.v1.iam_policy_pb2", _globals +) +if _descriptor._USE_C_DESCRIPTORS == False: + _globals["DESCRIPTOR"]._options = None + _globals[ + "DESCRIPTOR" + ]._serialized_options = b"\n\021com.google.iam.v1B\016IamPolicyProtoP\001Z)cloud.google.com/go/iam/apiv1/iampb;iampb\252\002\023Google.Cloud.Iam.V1\312\002\023Google\\Cloud\\Iam\\V1" + _globals["_SETIAMPOLICYREQUEST"].fields_by_name["resource"]._options = None + _globals["_SETIAMPOLICYREQUEST"].fields_by_name[ + "resource" + ]._serialized_options = b"\340A\002\372A\003\n\001*" + _globals["_SETIAMPOLICYREQUEST"].fields_by_name["policy"]._options = None + _globals["_SETIAMPOLICYREQUEST"].fields_by_name[ + "policy" + ]._serialized_options = b"\340A\002" + _globals["_GETIAMPOLICYREQUEST"].fields_by_name["resource"]._options = None + _globals["_GETIAMPOLICYREQUEST"].fields_by_name[ + "resource" + ]._serialized_options = b"\340A\002\372A\003\n\001*" + _globals["_TESTIAMPERMISSIONSREQUEST"].fields_by_name["resource"]._options = None + _globals["_TESTIAMPERMISSIONSREQUEST"].fields_by_name[ + "resource" + ]._serialized_options = b"\340A\002\372A\003\n\001*" + _globals["_TESTIAMPERMISSIONSREQUEST"].fields_by_name["permissions"]._options = None + _globals["_TESTIAMPERMISSIONSREQUEST"].fields_by_name[ + "permissions" + ]._serialized_options = b"\340A\002" + _globals["_IAMPOLICY"]._options = None + _globals["_IAMPOLICY"]._serialized_options = b"\312A\033iam-meta-api.googleapis.com" + _globals["_IAMPOLICY"].methods_by_name["SetIamPolicy"]._options = None + _globals["_IAMPOLICY"].methods_by_name[ + "SetIamPolicy" + ]._serialized_options = ( + b'\202\323\344\223\002#"\036/v1/{resource=**}:setIamPolicy:\001*' + ) + _globals["_IAMPOLICY"].methods_by_name["GetIamPolicy"]._options = None + _globals["_IAMPOLICY"].methods_by_name[ + "GetIamPolicy" + ]._serialized_options = ( + b'\202\323\344\223\002#"\036/v1/{resource=**}:getIamPolicy:\001*' + ) + _globals["_IAMPOLICY"].methods_by_name["TestIamPermissions"]._options = None + _globals["_IAMPOLICY"].methods_by_name[ + "TestIamPermissions" + ]._serialized_options = ( + b'\202\323\344\223\002)"$/v1/{resource=**}:testIamPermissions:\001*' + ) + _globals["_SETIAMPOLICYREQUEST"]._serialized_start = 256 + _globals["_SETIAMPOLICYREQUEST"]._serialized_end = 399 + _globals["_GETIAMPOLICYREQUEST"]._serialized_start = 401 + _globals["_GETIAMPOLICYREQUEST"]._serialized_end = 501 + _globals["_TESTIAMPERMISSIONSREQUEST"]._serialized_start = 503 + _globals["_TESTIAMPERMISSIONSREQUEST"]._serialized_end = 585 + _globals["_TESTIAMPERMISSIONSRESPONSE"]._serialized_start = 587 + _globals["_TESTIAMPERMISSIONSRESPONSE"]._serialized_end = 636 + _globals["_IAMPOLICY"]._serialized_start = 639 + _globals["_IAMPOLICY"]._serialized_end = 1075 +# @@protoc_insertion_point(module_scope) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/iam_policy_pb2.pyi b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/iam_policy_pb2.pyi new file mode 100644 index 0000000000000000000000000000000000000000..26e6b9ab8db53bd249ca4fca2a88c3af75ee009f --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/iam_policy_pb2.pyi @@ -0,0 +1,77 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. + +from typing import ClassVar as _ClassVar +from typing import Iterable as _Iterable +from typing import Mapping as _Mapping +from typing import Optional as _Optional +from typing import Union as _Union + +from google.api import annotations_pb2 as _annotations_pb2 +from google.api import client_pb2 as _client_pb2 +from google.api import field_behavior_pb2 as _field_behavior_pb2 +from google.api import resource_pb2 as _resource_pb2 +from google.iam.v1 import options_pb2 as _options_pb2 +from google.iam.v1 import policy_pb2 as _policy_pb2 +from google.protobuf import descriptor as _descriptor +from google.protobuf import field_mask_pb2 as _field_mask_pb2 +from google.protobuf import message as _message +from google.protobuf.internal import containers as _containers + +DESCRIPTOR: _descriptor.FileDescriptor + +class SetIamPolicyRequest(_message.Message): + __slots__ = ("resource", "policy", "update_mask") + RESOURCE_FIELD_NUMBER: _ClassVar[int] + POLICY_FIELD_NUMBER: _ClassVar[int] + UPDATE_MASK_FIELD_NUMBER: _ClassVar[int] + resource: str + policy: _policy_pb2.Policy + update_mask: _field_mask_pb2.FieldMask + def __init__( + self, + resource: _Optional[str] = ..., + policy: _Optional[_Union[_policy_pb2.Policy, _Mapping]] = ..., + update_mask: _Optional[_Union[_field_mask_pb2.FieldMask, _Mapping]] = ..., + ) -> None: ... + +class GetIamPolicyRequest(_message.Message): + __slots__ = ("resource", "options") + RESOURCE_FIELD_NUMBER: _ClassVar[int] + OPTIONS_FIELD_NUMBER: _ClassVar[int] + resource: str + options: _options_pb2.GetPolicyOptions + def __init__( + self, + resource: _Optional[str] = ..., + options: _Optional[_Union[_options_pb2.GetPolicyOptions, _Mapping]] = ..., + ) -> None: ... + +class TestIamPermissionsRequest(_message.Message): + __slots__ = ("resource", "permissions") + RESOURCE_FIELD_NUMBER: _ClassVar[int] + PERMISSIONS_FIELD_NUMBER: _ClassVar[int] + resource: str + permissions: _containers.RepeatedScalarFieldContainer[str] + def __init__( + self, + resource: _Optional[str] = ..., + permissions: _Optional[_Iterable[str]] = ..., + ) -> None: ... + +class TestIamPermissionsResponse(_message.Message): + __slots__ = ("permissions",) + PERMISSIONS_FIELD_NUMBER: _ClassVar[int] + permissions: _containers.RepeatedScalarFieldContainer[str] + def __init__(self, permissions: _Optional[_Iterable[str]] = ...) -> None: ... diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/iam_policy_pb2_grpc.py b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/iam_policy_pb2_grpc.py new file mode 100644 index 0000000000000000000000000000000000000000..1e881f04fe35d2bf949cec6e63463c067b2d2122 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/iam_policy_pb2_grpc.py @@ -0,0 +1,155 @@ +# Copyright 2022 Google LLC +# +# Licensed 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. + +# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! + + +import grpc + +from google.iam.v1 import iam_policy_pb2 as google_dot_iam_dot_v1_dot_iam__policy__pb2 +from google.iam.v1 import policy_pb2 as google_dot_iam_dot_v1_dot_policy__pb2 + + +class IAMPolicyStub(object): + """## API Overview + + Manages Identity and Access Management (IAM) policies. + + Any implementation of an API that offers access control features + implements the google.iam.v1.IAMPolicy interface. + + ## Data model + + Access control is applied when a principal (user or service account), takes + some action on a resource exposed by a service. Resources, identified by + URI-like names, are the unit of access control specification. Service + implementations can choose the granularity of access control and the + supported permissions for their resources. + For example one database service may allow access control to be + specified only at the Table level, whereas another might allow access control + to also be specified at the Column level. + + ## Policy Structure + + See google.iam.v1.Policy + + This is intentionally not a CRUD style API because access control policies + are created and deleted implicitly with the resources to which they are + attached. + """ + + def __init__(self, channel): + """Constructor. + + Args: + channel: A grpc.Channel. + """ + self.SetIamPolicy = channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=google_dot_iam_dot_v1_dot_policy__pb2.Policy.FromString, + ) + self.GetIamPolicy = channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=google_dot_iam_dot_v1_dot_policy__pb2.Policy.FromString, + ) + self.TestIamPermissions = channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsResponse.FromString, + ) + + +class IAMPolicyServicer(object): + """## API Overview + + Manages Identity and Access Management (IAM) policies. + + Any implementation of an API that offers access control features + implements the google.iam.v1.IAMPolicy interface. + + ## Data model + + Access control is applied when a principal (user or service account), takes + some action on a resource exposed by a service. Resources, identified by + URI-like names, are the unit of access control specification. Service + implementations can choose the granularity of access control and the + supported permissions for their resources. + For example one database service may allow access control to be + specified only at the Table level, whereas another might allow access control + to also be specified at the Column level. + + ## Policy Structure + + See google.iam.v1.Policy + + This is intentionally not a CRUD style API because access control policies + are created and deleted implicitly with the resources to which they are + attached. + """ + + def SetIamPolicy(self, request, context): + """Sets the access control policy on the specified resource. Replaces any + existing policy. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details("Method not implemented!") + raise NotImplementedError("Method not implemented!") + + def GetIamPolicy(self, request, context): + """Gets the access control policy for a resource. + Returns an empty policy if the resource exists and does not have a policy + set. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details("Method not implemented!") + raise NotImplementedError("Method not implemented!") + + def TestIamPermissions(self, request, context): + """Returns permissions that a caller has on the specified resource. + If the resource does not exist, this will return an empty set of + permissions, not a NOT_FOUND error. + + Note: This operation is designed to be used for building permission-aware + UIs and command-line tools, not for authorization checking. This operation + may "fail open" without warning. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details("Method not implemented!") + raise NotImplementedError("Method not implemented!") + + +def add_IAMPolicyServicer_to_server(servicer, server): + rpc_method_handlers = { + "SetIamPolicy": grpc.unary_unary_rpc_method_handler( + servicer.SetIamPolicy, + request_deserializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.SetIamPolicyRequest.FromString, + response_serializer=google_dot_iam_dot_v1_dot_policy__pb2.Policy.SerializeToString, + ), + "GetIamPolicy": grpc.unary_unary_rpc_method_handler( + servicer.GetIamPolicy, + request_deserializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.GetIamPolicyRequest.FromString, + response_serializer=google_dot_iam_dot_v1_dot_policy__pb2.Policy.SerializeToString, + ), + "TestIamPermissions": grpc.unary_unary_rpc_method_handler( + servicer.TestIamPermissions, + request_deserializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsRequest.FromString, + response_serializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsResponse.SerializeToString, + ), + } + generic_handler = grpc.method_handlers_generic_handler( + "google.iam.v1.IAMPolicy", rpc_method_handlers + ) + server.add_generic_rpc_handlers((generic_handler,)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/logging/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/logging/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/logging/audit_data_pb2.py b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/logging/audit_data_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..4ab288ec01a7f820e8bc6ba403972942e83ca6bb --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/logging/audit_data_pb2.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- + +# Copyright 2024 Google LLC +# +# Licensed 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. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/iam/v1/logging/audit_data.proto +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.iam.v1 import policy_pb2 as google_dot_iam_dot_v1_dot_policy__pb2 + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b'\n&google/iam/v1/logging/audit_data.proto\x12\x15google.iam.v1.logging\x1a\x1agoogle/iam/v1/policy.proto"=\n\tAuditData\x12\x30\n\x0cpolicy_delta\x18\x02 \x01(\x0b\x32\x1a.google.iam.v1.PolicyDeltaB\x86\x01\n\x19\x63om.google.iam.v1.loggingB\x0e\x41uditDataProtoP\x01Z9cloud.google.com/go/iam/apiv1/logging/loggingpb;loggingpb\xaa\x02\x1bGoogle.Cloud.Iam.V1.Loggingb\x06proto3' +) + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages( + DESCRIPTOR, "google.iam.v1.logging.audit_data_pb2", _globals +) +if _descriptor._USE_C_DESCRIPTORS == False: + DESCRIPTOR._options = None + DESCRIPTOR._serialized_options = b"\n\031com.google.iam.v1.loggingB\016AuditDataProtoP\001Z9cloud.google.com/go/iam/apiv1/logging/loggingpb;loggingpb\252\002\033Google.Cloud.Iam.V1.Logging" + _globals["_AUDITDATA"]._serialized_start = 93 + _globals["_AUDITDATA"]._serialized_end = 154 +# @@protoc_insertion_point(module_scope) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/options.proto b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/options.proto new file mode 100644 index 0000000000000000000000000000000000000000..5337058794a71fd5ab4751ca7d6a9f682698c91d --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/options.proto @@ -0,0 +1,48 @@ +// Copyright 2025 Google LLC +// +// Licensed 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. + +syntax = "proto3"; + +package google.iam.v1; + +option cc_enable_arenas = true; +option csharp_namespace = "Google.Cloud.Iam.V1"; +option go_package = "cloud.google.com/go/iam/apiv1/iampb;iampb"; +option java_multiple_files = true; +option java_outer_classname = "OptionsProto"; +option java_package = "com.google.iam.v1"; +option php_namespace = "Google\\Cloud\\Iam\\V1"; + +// Encapsulates settings provided to GetIamPolicy. +message GetPolicyOptions { + // Optional. The maximum policy version that will be used to format the + // policy. + // + // Valid values are 0, 1, and 3. Requests specifying an invalid value will be + // rejected. + // + // Requests for policies with any conditional role bindings must specify + // version 3. Policies with no conditional role bindings may specify any valid + // value or leave the field unset. + // + // The policy in the response might use the policy version that you specified, + // or it might use a lower policy version. For example, if you specify version + // 3, but the policy has no conditional role bindings, the response uses + // version 1. + // + // To learn which resources support conditions in their IAM policies, see the + // [IAM + // documentation](https://cloud.google.com/iam/help/conditions/resource-policies). + int32 requested_policy_version = 1; +} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/options_pb2.py b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/options_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..fb8a7f86620bb83819ffb16242eee5ea176d4ed7 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/options_pb2.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- + +# Copyright 2025 Google LLC +# +# Licensed 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. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/iam/v1/options.proto +# Protobuf Python Version: 4.25.3 +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b'\n\x1bgoogle/iam/v1/options.proto\x12\rgoogle.iam.v1"4\n\x10GetPolicyOptions\x12 \n\x18requested_policy_version\x18\x01 \x01(\x05\x42}\n\x11\x63om.google.iam.v1B\x0cOptionsProtoP\x01Z)cloud.google.com/go/iam/apiv1/iampb;iampb\xf8\x01\x01\xaa\x02\x13Google.Cloud.Iam.V1\xca\x02\x13Google\\Cloud\\Iam\\V1b\x06proto3' +) + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages( + DESCRIPTOR, "google.iam.v1.options_pb2", _globals +) +if _descriptor._USE_C_DESCRIPTORS == False: + _globals["DESCRIPTOR"]._options = None + _globals[ + "DESCRIPTOR" + ]._serialized_options = b"\n\021com.google.iam.v1B\014OptionsProtoP\001Z)cloud.google.com/go/iam/apiv1/iampb;iampb\370\001\001\252\002\023Google.Cloud.Iam.V1\312\002\023Google\\Cloud\\Iam\\V1" + _globals["_GETPOLICYOPTIONS"]._serialized_start = 46 + _globals["_GETPOLICYOPTIONS"]._serialized_end = 98 +# @@protoc_insertion_point(module_scope) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/options_pb2.pyi b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/options_pb2.pyi new file mode 100644 index 0000000000000000000000000000000000000000..6c55f20404b4bbdfd853c4d5092f8c51007c999a --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/options_pb2.pyi @@ -0,0 +1,27 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. + +from typing import ClassVar as _ClassVar +from typing import Optional as _Optional + +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message + +DESCRIPTOR: _descriptor.FileDescriptor + +class GetPolicyOptions(_message.Message): + __slots__ = ("requested_policy_version",) + REQUESTED_POLICY_VERSION_FIELD_NUMBER: _ClassVar[int] + requested_policy_version: int + def __init__(self, requested_policy_version: _Optional[int] = ...) -> None: ... diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/options_pb2_grpc.py b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/options_pb2_grpc.py new file mode 100644 index 0000000000000000000000000000000000000000..7ad82ac0608aa95f411ecf4906debf76c80e53f6 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/options_pb2_grpc.py @@ -0,0 +1,15 @@ +# Copyright 2022 Google LLC +# +# Licensed 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. + +# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/policy.proto b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/policy.proto new file mode 100644 index 0000000000000000000000000000000000000000..b5eac03c44272852a3072502e7a912a03c8c6c73 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/policy.proto @@ -0,0 +1,410 @@ +// Copyright 2025 Google LLC +// +// Licensed 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. + +syntax = "proto3"; + +package google.iam.v1; + +import "google/type/expr.proto"; + +option cc_enable_arenas = true; +option csharp_namespace = "Google.Cloud.Iam.V1"; +option go_package = "cloud.google.com/go/iam/apiv1/iampb;iampb"; +option java_multiple_files = true; +option java_outer_classname = "PolicyProto"; +option java_package = "com.google.iam.v1"; +option php_namespace = "Google\\Cloud\\Iam\\V1"; + +// An Identity and Access Management (IAM) policy, which specifies access +// controls for Google Cloud resources. +// +// +// A `Policy` is a collection of `bindings`. A `binding` binds one or more +// `members`, or principals, to a single `role`. Principals can be user +// accounts, service accounts, Google groups, and domains (such as G Suite). A +// `role` is a named list of permissions; each `role` can be an IAM predefined +// role or a user-created custom role. +// +// For some types of Google Cloud resources, a `binding` can also specify a +// `condition`, which is a logical expression that allows access to a resource +// only if the expression evaluates to `true`. A condition can add constraints +// based on attributes of the request, the resource, or both. To learn which +// resources support conditions in their IAM policies, see the +// [IAM +// documentation](https://cloud.google.com/iam/help/conditions/resource-policies). +// +// **JSON example:** +// +// ``` +// { +// "bindings": [ +// { +// "role": "roles/resourcemanager.organizationAdmin", +// "members": [ +// "user:mike@example.com", +// "group:admins@example.com", +// "domain:google.com", +// "serviceAccount:my-project-id@appspot.gserviceaccount.com" +// ] +// }, +// { +// "role": "roles/resourcemanager.organizationViewer", +// "members": [ +// "user:eve@example.com" +// ], +// "condition": { +// "title": "expirable access", +// "description": "Does not grant access after Sep 2020", +// "expression": "request.time < +// timestamp('2020-10-01T00:00:00.000Z')", +// } +// } +// ], +// "etag": "BwWWja0YfJA=", +// "version": 3 +// } +// ``` +// +// **YAML example:** +// +// ``` +// bindings: +// - members: +// - user:mike@example.com +// - group:admins@example.com +// - domain:google.com +// - serviceAccount:my-project-id@appspot.gserviceaccount.com +// role: roles/resourcemanager.organizationAdmin +// - members: +// - user:eve@example.com +// role: roles/resourcemanager.organizationViewer +// condition: +// title: expirable access +// description: Does not grant access after Sep 2020 +// expression: request.time < timestamp('2020-10-01T00:00:00.000Z') +// etag: BwWWja0YfJA= +// version: 3 +// ``` +// +// For a description of IAM and its features, see the +// [IAM documentation](https://cloud.google.com/iam/docs/). +message Policy { + // Specifies the format of the policy. + // + // Valid values are `0`, `1`, and `3`. Requests that specify an invalid value + // are rejected. + // + // Any operation that affects conditional role bindings must specify version + // `3`. This requirement applies to the following operations: + // + // * Getting a policy that includes a conditional role binding + // * Adding a conditional role binding to a policy + // * Changing a conditional role binding in a policy + // * Removing any role binding, with or without a condition, from a policy + // that includes conditions + // + // **Important:** If you use IAM Conditions, you must include the `etag` field + // whenever you call `setIamPolicy`. If you omit this field, then IAM allows + // you to overwrite a version `3` policy with a version `1` policy, and all of + // the conditions in the version `3` policy are lost. + // + // If a policy does not include any conditions, operations on that policy may + // specify any valid version or leave the field unset. + // + // To learn which resources support conditions in their IAM policies, see the + // [IAM + // documentation](https://cloud.google.com/iam/help/conditions/resource-policies). + int32 version = 1; + + // Associates a list of `members`, or principals, with a `role`. Optionally, + // may specify a `condition` that determines how and when the `bindings` are + // applied. Each of the `bindings` must contain at least one principal. + // + // The `bindings` in a `Policy` can refer to up to 1,500 principals; up to 250 + // of these principals can be Google groups. Each occurrence of a principal + // counts towards these limits. For example, if the `bindings` grant 50 + // different roles to `user:alice@example.com`, and not to any other + // principal, then you can add another 1,450 principals to the `bindings` in + // the `Policy`. + repeated Binding bindings = 4; + + // Specifies cloud audit logging configuration for this policy. + repeated AuditConfig audit_configs = 6; + + // `etag` is used for optimistic concurrency control as a way to help + // prevent simultaneous updates of a policy from overwriting each other. + // It is strongly suggested that systems make use of the `etag` in the + // read-modify-write cycle to perform policy updates in order to avoid race + // conditions: An `etag` is returned in the response to `getIamPolicy`, and + // systems are expected to put that etag in the request to `setIamPolicy` to + // ensure that their change will be applied to the same version of the policy. + // + // **Important:** If you use IAM Conditions, you must include the `etag` field + // whenever you call `setIamPolicy`. If you omit this field, then IAM allows + // you to overwrite a version `3` policy with a version `1` policy, and all of + // the conditions in the version `3` policy are lost. + bytes etag = 3; +} + +// Associates `members`, or principals, with a `role`. +message Binding { + // Role that is assigned to the list of `members`, or principals. + // For example, `roles/viewer`, `roles/editor`, or `roles/owner`. + string role = 1; + + // Specifies the principals requesting access for a Google Cloud resource. + // `members` can have the following values: + // + // * `allUsers`: A special identifier that represents anyone who is + // on the internet; with or without a Google account. + // + // * `allAuthenticatedUsers`: A special identifier that represents anyone + // who is authenticated with a Google account or a service account. + // + // * `user:{emailid}`: An email address that represents a specific Google + // account. For example, `alice@example.com` . + // + // + // * `serviceAccount:{emailid}`: An email address that represents a service + // account. For example, `my-other-app@appspot.gserviceaccount.com`. + // + // * `group:{emailid}`: An email address that represents a Google group. + // For example, `admins@example.com`. + // + // * `deleted:user:{emailid}?uid={uniqueid}`: An email address (plus unique + // identifier) representing a user that has been recently deleted. For + // example, `alice@example.com?uid=123456789012345678901`. If the user is + // recovered, this value reverts to `user:{emailid}` and the recovered user + // retains the role in the binding. + // + // * `deleted:serviceAccount:{emailid}?uid={uniqueid}`: An email address (plus + // unique identifier) representing a service account that has been recently + // deleted. For example, + // `my-other-app@appspot.gserviceaccount.com?uid=123456789012345678901`. + // If the service account is undeleted, this value reverts to + // `serviceAccount:{emailid}` and the undeleted service account retains the + // role in the binding. + // + // * `deleted:group:{emailid}?uid={uniqueid}`: An email address (plus unique + // identifier) representing a Google group that has been recently + // deleted. For example, `admins@example.com?uid=123456789012345678901`. If + // the group is recovered, this value reverts to `group:{emailid}` and the + // recovered group retains the role in the binding. + // + // + // * `domain:{domain}`: The G Suite domain (primary) that represents all the + // users of that domain. For example, `google.com` or `example.com`. + // + // + repeated string members = 2; + + // The condition that is associated with this binding. + // + // If the condition evaluates to `true`, then this binding applies to the + // current request. + // + // If the condition evaluates to `false`, then this binding does not apply to + // the current request. However, a different role binding might grant the same + // role to one or more of the principals in this binding. + // + // To learn which resources support conditions in their IAM policies, see the + // [IAM + // documentation](https://cloud.google.com/iam/help/conditions/resource-policies). + google.type.Expr condition = 3; +} + +// Specifies the audit configuration for a service. +// The configuration determines which permission types are logged, and what +// identities, if any, are exempted from logging. +// An AuditConfig must have one or more AuditLogConfigs. +// +// If there are AuditConfigs for both `allServices` and a specific service, +// the union of the two AuditConfigs is used for that service: the log_types +// specified in each AuditConfig are enabled, and the exempted_members in each +// AuditLogConfig are exempted. +// +// Example Policy with multiple AuditConfigs: +// +// { +// "audit_configs": [ +// { +// "service": "allServices", +// "audit_log_configs": [ +// { +// "log_type": "DATA_READ", +// "exempted_members": [ +// "user:jose@example.com" +// ] +// }, +// { +// "log_type": "DATA_WRITE" +// }, +// { +// "log_type": "ADMIN_READ" +// } +// ] +// }, +// { +// "service": "sampleservice.googleapis.com", +// "audit_log_configs": [ +// { +// "log_type": "DATA_READ" +// }, +// { +// "log_type": "DATA_WRITE", +// "exempted_members": [ +// "user:aliya@example.com" +// ] +// } +// ] +// } +// ] +// } +// +// For sampleservice, this policy enables DATA_READ, DATA_WRITE and ADMIN_READ +// logging. It also exempts `jose@example.com` from DATA_READ logging, and +// `aliya@example.com` from DATA_WRITE logging. +message AuditConfig { + // Specifies a service that will be enabled for audit logging. + // For example, `storage.googleapis.com`, `cloudsql.googleapis.com`. + // `allServices` is a special value that covers all services. + string service = 1; + + // The configuration for logging of each type of permission. + repeated AuditLogConfig audit_log_configs = 3; +} + +// Provides the configuration for logging a type of permissions. +// Example: +// +// { +// "audit_log_configs": [ +// { +// "log_type": "DATA_READ", +// "exempted_members": [ +// "user:jose@example.com" +// ] +// }, +// { +// "log_type": "DATA_WRITE" +// } +// ] +// } +// +// This enables 'DATA_READ' and 'DATA_WRITE' logging, while exempting +// jose@example.com from DATA_READ logging. +message AuditLogConfig { + // The list of valid permission types for which logging can be configured. + // Admin writes are always logged, and are not configurable. + enum LogType { + // Default case. Should never be this. + LOG_TYPE_UNSPECIFIED = 0; + + // Admin reads. Example: CloudIAM getIamPolicy + ADMIN_READ = 1; + + // Data writes. Example: CloudSQL Users create + DATA_WRITE = 2; + + // Data reads. Example: CloudSQL Users list + DATA_READ = 3; + } + + // The log type that this config enables. + LogType log_type = 1; + + // Specifies the identities that do not cause logging for this type of + // permission. + // Follows the same format of + // [Binding.members][google.iam.v1.Binding.members]. + repeated string exempted_members = 2; +} + +// The difference delta between two policies. +message PolicyDelta { + // The delta for Bindings between two policies. + repeated BindingDelta binding_deltas = 1; + + // The delta for AuditConfigs between two policies. + repeated AuditConfigDelta audit_config_deltas = 2; +} + +// One delta entry for Binding. Each individual change (only one member in each +// entry) to a binding will be a separate entry. +message BindingDelta { + // The type of action performed on a Binding in a policy. + enum Action { + // Unspecified. + ACTION_UNSPECIFIED = 0; + + // Addition of a Binding. + ADD = 1; + + // Removal of a Binding. + REMOVE = 2; + } + + // The action that was performed on a Binding. + // Required + Action action = 1; + + // Role that is assigned to `members`. + // For example, `roles/viewer`, `roles/editor`, or `roles/owner`. + // Required + string role = 2; + + // A single identity requesting access for a Google Cloud resource. + // Follows the same format of Binding.members. + // Required + string member = 3; + + // The condition that is associated with this binding. + google.type.Expr condition = 4; +} + +// One delta entry for AuditConfig. Each individual change (only one +// exempted_member in each entry) to a AuditConfig will be a separate entry. +message AuditConfigDelta { + // The type of action performed on an audit configuration in a policy. + enum Action { + // Unspecified. + ACTION_UNSPECIFIED = 0; + + // Addition of an audit configuration. + ADD = 1; + + // Removal of an audit configuration. + REMOVE = 2; + } + + // The action that was performed on an audit configuration in a policy. + // Required + Action action = 1; + + // Specifies a service that was configured for Cloud Audit Logging. + // For example, `storage.googleapis.com`, `cloudsql.googleapis.com`. + // `allServices` is a special value that covers all services. + // Required + string service = 2; + + // A single identity that is exempted from "data access" audit + // logging for the `service` specified above. + // Follows the same format of Binding.members. + string exempted_member = 3; + + // Specifies the log_type that was be enabled. ADMIN_ACTIVITY is always + // enabled, and cannot be configured. + // Required + string log_type = 4; +} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/policy_pb2.py b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/policy_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..c07f91e37a1af0a88618bd9574f338821e862e39 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/policy_pb2.py @@ -0,0 +1,68 @@ +# -*- coding: utf-8 -*- + +# Copyright 2025 Google LLC +# +# Licensed 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. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/iam/v1/policy.proto +# Protobuf Python Version: 4.25.3 +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.type import expr_pb2 as google_dot_type_dot_expr__pb2 + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b'\n\x1agoogle/iam/v1/policy.proto\x12\rgoogle.iam.v1\x1a\x16google/type/expr.proto"\x84\x01\n\x06Policy\x12\x0f\n\x07version\x18\x01 \x01(\x05\x12(\n\x08\x62indings\x18\x04 \x03(\x0b\x32\x16.google.iam.v1.Binding\x12\x31\n\raudit_configs\x18\x06 \x03(\x0b\x32\x1a.google.iam.v1.AuditConfig\x12\x0c\n\x04\x65tag\x18\x03 \x01(\x0c"N\n\x07\x42inding\x12\x0c\n\x04role\x18\x01 \x01(\t\x12\x0f\n\x07members\x18\x02 \x03(\t\x12$\n\tcondition\x18\x03 \x01(\x0b\x32\x11.google.type.Expr"X\n\x0b\x41uditConfig\x12\x0f\n\x07service\x18\x01 \x01(\t\x12\x38\n\x11\x61udit_log_configs\x18\x03 \x03(\x0b\x32\x1d.google.iam.v1.AuditLogConfig"\xb7\x01\n\x0e\x41uditLogConfig\x12\x37\n\x08log_type\x18\x01 \x01(\x0e\x32%.google.iam.v1.AuditLogConfig.LogType\x12\x18\n\x10\x65xempted_members\x18\x02 \x03(\t"R\n\x07LogType\x12\x18\n\x14LOG_TYPE_UNSPECIFIED\x10\x00\x12\x0e\n\nADMIN_READ\x10\x01\x12\x0e\n\nDATA_WRITE\x10\x02\x12\r\n\tDATA_READ\x10\x03"\x80\x01\n\x0bPolicyDelta\x12\x33\n\x0e\x62inding_deltas\x18\x01 \x03(\x0b\x32\x1b.google.iam.v1.BindingDelta\x12<\n\x13\x61udit_config_deltas\x18\x02 \x03(\x0b\x32\x1f.google.iam.v1.AuditConfigDelta"\xbd\x01\n\x0c\x42indingDelta\x12\x32\n\x06\x61\x63tion\x18\x01 \x01(\x0e\x32".google.iam.v1.BindingDelta.Action\x12\x0c\n\x04role\x18\x02 \x01(\t\x12\x0e\n\x06member\x18\x03 \x01(\t\x12$\n\tcondition\x18\x04 \x01(\x0b\x32\x11.google.type.Expr"5\n\x06\x41\x63tion\x12\x16\n\x12\x41\x43TION_UNSPECIFIED\x10\x00\x12\x07\n\x03\x41\x44\x44\x10\x01\x12\n\n\x06REMOVE\x10\x02"\xbd\x01\n\x10\x41uditConfigDelta\x12\x36\n\x06\x61\x63tion\x18\x01 \x01(\x0e\x32&.google.iam.v1.AuditConfigDelta.Action\x12\x0f\n\x07service\x18\x02 \x01(\t\x12\x17\n\x0f\x65xempted_member\x18\x03 \x01(\t\x12\x10\n\x08log_type\x18\x04 \x01(\t"5\n\x06\x41\x63tion\x12\x16\n\x12\x41\x43TION_UNSPECIFIED\x10\x00\x12\x07\n\x03\x41\x44\x44\x10\x01\x12\n\n\x06REMOVE\x10\x02\x42|\n\x11\x63om.google.iam.v1B\x0bPolicyProtoP\x01Z)cloud.google.com/go/iam/apiv1/iampb;iampb\xf8\x01\x01\xaa\x02\x13Google.Cloud.Iam.V1\xca\x02\x13Google\\Cloud\\Iam\\V1b\x06proto3' +) + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages( + DESCRIPTOR, "google.iam.v1.policy_pb2", _globals +) +if _descriptor._USE_C_DESCRIPTORS == False: + _globals["DESCRIPTOR"]._options = None + _globals[ + "DESCRIPTOR" + ]._serialized_options = b"\n\021com.google.iam.v1B\013PolicyProtoP\001Z)cloud.google.com/go/iam/apiv1/iampb;iampb\370\001\001\252\002\023Google.Cloud.Iam.V1\312\002\023Google\\Cloud\\Iam\\V1" + _globals["_POLICY"]._serialized_start = 70 + _globals["_POLICY"]._serialized_end = 202 + _globals["_BINDING"]._serialized_start = 204 + _globals["_BINDING"]._serialized_end = 282 + _globals["_AUDITCONFIG"]._serialized_start = 284 + _globals["_AUDITCONFIG"]._serialized_end = 372 + _globals["_AUDITLOGCONFIG"]._serialized_start = 375 + _globals["_AUDITLOGCONFIG"]._serialized_end = 558 + _globals["_AUDITLOGCONFIG_LOGTYPE"]._serialized_start = 476 + _globals["_AUDITLOGCONFIG_LOGTYPE"]._serialized_end = 558 + _globals["_POLICYDELTA"]._serialized_start = 561 + _globals["_POLICYDELTA"]._serialized_end = 689 + _globals["_BINDINGDELTA"]._serialized_start = 692 + _globals["_BINDINGDELTA"]._serialized_end = 881 + _globals["_BINDINGDELTA_ACTION"]._serialized_start = 828 + _globals["_BINDINGDELTA_ACTION"]._serialized_end = 881 + _globals["_AUDITCONFIGDELTA"]._serialized_start = 884 + _globals["_AUDITCONFIGDELTA"]._serialized_end = 1073 + _globals["_AUDITCONFIGDELTA_ACTION"]._serialized_start = 828 + _globals["_AUDITCONFIGDELTA_ACTION"]._serialized_end = 881 +# @@protoc_insertion_point(module_scope) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/policy_pb2.pyi b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/policy_pb2.pyi new file mode 100644 index 0000000000000000000000000000000000000000..f14c5aea37501006fddd277bebad54b8e1cc4dc6 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/policy_pb2.pyi @@ -0,0 +1,163 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. + +from typing import ClassVar as _ClassVar +from typing import Iterable as _Iterable +from typing import Mapping as _Mapping +from typing import Optional as _Optional +from typing import Union as _Union + +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf.internal import containers as _containers +from google.protobuf.internal import enum_type_wrapper as _enum_type_wrapper +from google.type import expr_pb2 as _expr_pb2 + +DESCRIPTOR: _descriptor.FileDescriptor + +class Policy(_message.Message): + __slots__ = ("version", "bindings", "audit_configs", "etag") + VERSION_FIELD_NUMBER: _ClassVar[int] + BINDINGS_FIELD_NUMBER: _ClassVar[int] + AUDIT_CONFIGS_FIELD_NUMBER: _ClassVar[int] + ETAG_FIELD_NUMBER: _ClassVar[int] + version: int + bindings: _containers.RepeatedCompositeFieldContainer[Binding] + audit_configs: _containers.RepeatedCompositeFieldContainer[AuditConfig] + etag: bytes + def __init__( + self, + version: _Optional[int] = ..., + bindings: _Optional[_Iterable[_Union[Binding, _Mapping]]] = ..., + audit_configs: _Optional[_Iterable[_Union[AuditConfig, _Mapping]]] = ..., + etag: _Optional[bytes] = ..., + ) -> None: ... + +class Binding(_message.Message): + __slots__ = ("role", "members", "condition") + ROLE_FIELD_NUMBER: _ClassVar[int] + MEMBERS_FIELD_NUMBER: _ClassVar[int] + CONDITION_FIELD_NUMBER: _ClassVar[int] + role: str + members: _containers.RepeatedScalarFieldContainer[str] + condition: _expr_pb2.Expr + def __init__( + self, + role: _Optional[str] = ..., + members: _Optional[_Iterable[str]] = ..., + condition: _Optional[_Union[_expr_pb2.Expr, _Mapping]] = ..., + ) -> None: ... + +class AuditConfig(_message.Message): + __slots__ = ("service", "audit_log_configs") + SERVICE_FIELD_NUMBER: _ClassVar[int] + AUDIT_LOG_CONFIGS_FIELD_NUMBER: _ClassVar[int] + service: str + audit_log_configs: _containers.RepeatedCompositeFieldContainer[AuditLogConfig] + def __init__( + self, + service: _Optional[str] = ..., + audit_log_configs: _Optional[_Iterable[_Union[AuditLogConfig, _Mapping]]] = ..., + ) -> None: ... + +class AuditLogConfig(_message.Message): + __slots__ = ("log_type", "exempted_members") + class LogType(int, metaclass=_enum_type_wrapper.EnumTypeWrapper): + __slots__ = () + LOG_TYPE_UNSPECIFIED: _ClassVar[AuditLogConfig.LogType] + ADMIN_READ: _ClassVar[AuditLogConfig.LogType] + DATA_WRITE: _ClassVar[AuditLogConfig.LogType] + DATA_READ: _ClassVar[AuditLogConfig.LogType] + + LOG_TYPE_UNSPECIFIED: AuditLogConfig.LogType + ADMIN_READ: AuditLogConfig.LogType + DATA_WRITE: AuditLogConfig.LogType + DATA_READ: AuditLogConfig.LogType + LOG_TYPE_FIELD_NUMBER: _ClassVar[int] + EXEMPTED_MEMBERS_FIELD_NUMBER: _ClassVar[int] + log_type: AuditLogConfig.LogType + exempted_members: _containers.RepeatedScalarFieldContainer[str] + def __init__( + self, + log_type: _Optional[_Union[AuditLogConfig.LogType, str]] = ..., + exempted_members: _Optional[_Iterable[str]] = ..., + ) -> None: ... + +class PolicyDelta(_message.Message): + __slots__ = ("binding_deltas", "audit_config_deltas") + BINDING_DELTAS_FIELD_NUMBER: _ClassVar[int] + AUDIT_CONFIG_DELTAS_FIELD_NUMBER: _ClassVar[int] + binding_deltas: _containers.RepeatedCompositeFieldContainer[BindingDelta] + audit_config_deltas: _containers.RepeatedCompositeFieldContainer[AuditConfigDelta] + def __init__( + self, + binding_deltas: _Optional[_Iterable[_Union[BindingDelta, _Mapping]]] = ..., + audit_config_deltas: _Optional[ + _Iterable[_Union[AuditConfigDelta, _Mapping]] + ] = ..., + ) -> None: ... + +class BindingDelta(_message.Message): + __slots__ = ("action", "role", "member", "condition") + class Action(int, metaclass=_enum_type_wrapper.EnumTypeWrapper): + __slots__ = () + ACTION_UNSPECIFIED: _ClassVar[BindingDelta.Action] + ADD: _ClassVar[BindingDelta.Action] + REMOVE: _ClassVar[BindingDelta.Action] + + ACTION_UNSPECIFIED: BindingDelta.Action + ADD: BindingDelta.Action + REMOVE: BindingDelta.Action + ACTION_FIELD_NUMBER: _ClassVar[int] + ROLE_FIELD_NUMBER: _ClassVar[int] + MEMBER_FIELD_NUMBER: _ClassVar[int] + CONDITION_FIELD_NUMBER: _ClassVar[int] + action: BindingDelta.Action + role: str + member: str + condition: _expr_pb2.Expr + def __init__( + self, + action: _Optional[_Union[BindingDelta.Action, str]] = ..., + role: _Optional[str] = ..., + member: _Optional[str] = ..., + condition: _Optional[_Union[_expr_pb2.Expr, _Mapping]] = ..., + ) -> None: ... + +class AuditConfigDelta(_message.Message): + __slots__ = ("action", "service", "exempted_member", "log_type") + class Action(int, metaclass=_enum_type_wrapper.EnumTypeWrapper): + __slots__ = () + ACTION_UNSPECIFIED: _ClassVar[AuditConfigDelta.Action] + ADD: _ClassVar[AuditConfigDelta.Action] + REMOVE: _ClassVar[AuditConfigDelta.Action] + + ACTION_UNSPECIFIED: AuditConfigDelta.Action + ADD: AuditConfigDelta.Action + REMOVE: AuditConfigDelta.Action + ACTION_FIELD_NUMBER: _ClassVar[int] + SERVICE_FIELD_NUMBER: _ClassVar[int] + EXEMPTED_MEMBER_FIELD_NUMBER: _ClassVar[int] + LOG_TYPE_FIELD_NUMBER: _ClassVar[int] + action: AuditConfigDelta.Action + service: str + exempted_member: str + log_type: str + def __init__( + self, + action: _Optional[_Union[AuditConfigDelta.Action, str]] = ..., + service: _Optional[str] = ..., + exempted_member: _Optional[str] = ..., + log_type: _Optional[str] = ..., + ) -> None: ... diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/policy_pb2_grpc.py b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/policy_pb2_grpc.py new file mode 100644 index 0000000000000000000000000000000000000000..7ad82ac0608aa95f411ecf4906debf76c80e53f6 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/policy_pb2_grpc.py @@ -0,0 +1,15 @@ +# Copyright 2022 Google LLC +# +# Licensed 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. + +# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/resource_policy_member.proto b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/resource_policy_member.proto new file mode 100644 index 0000000000000000000000000000000000000000..16eefacec5bbfd05ca9162d939e23bf8a275ad65 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/resource_policy_member.proto @@ -0,0 +1,50 @@ +// Copyright 2025 Google LLC +// +// Licensed 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. + +syntax = "proto3"; + +package google.iam.v1; + +import "google/api/field_behavior.proto"; + +option csharp_namespace = "Google.Cloud.Iam.V1"; +option go_package = "cloud.google.com/go/iam/apiv1/iampb;iampb"; +option php_namespace = "Google\\Cloud\\Iam\\V1"; +option java_multiple_files = true; +option java_outer_classname = "ResourcePolicyMemberProto"; +option java_package = "com.google.iam.v1"; + +// Output-only policy member strings of a Google Cloud resource's built-in +// identity. +message ResourcePolicyMember { + // IAM policy binding member referring to a Google Cloud resource by + // user-assigned name (https://google.aip.dev/122). If a resource is deleted + // and recreated with the same name, the binding will be applicable to the new + // resource. + // + // Example: + // `principal://parametermanager.googleapis.com/projects/12345/name/locations/us-central1-a/parameters/my-parameter` + string iam_policy_name_principal = 1 + [(google.api.field_behavior) = OUTPUT_ONLY]; + + // IAM policy binding member referring to a Google Cloud resource by + // system-assigned unique identifier (https://google.aip.dev/148#uid). If a + // resource is deleted and recreated with the same name, the binding will not + // be applicable to the new resource + // + // Example: + // `principal://parametermanager.googleapis.com/projects/12345/uid/locations/us-central1-a/parameters/a918fed5` + string iam_policy_uid_principal = 2 + [(google.api.field_behavior) = OUTPUT_ONLY]; +} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/resource_policy_member_pb2.py b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/resource_policy_member_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..6c89871db42b615b7bf8ec8b27d170a4e6b7794c --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/resource_policy_member_pb2.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- + +# Copyright 2025 Google LLC +# +# Licensed 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. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/iam/v1/resource_policy_member.proto +# Protobuf Python Version: 4.25.3 +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b'\n*google/iam/v1/resource_policy_member.proto\x12\rgoogle.iam.v1\x1a\x1fgoogle/api/field_behavior.proto"e\n\x14ResourcePolicyMember\x12&\n\x19iam_policy_name_principal\x18\x01 \x01(\tB\x03\xe0\x41\x03\x12%\n\x18iam_policy_uid_principal\x18\x02 \x01(\tB\x03\xe0\x41\x03\x42\x87\x01\n\x11\x63om.google.iam.v1B\x19ResourcePolicyMemberProtoP\x01Z)cloud.google.com/go/iam/apiv1/iampb;iampb\xaa\x02\x13Google.Cloud.Iam.V1\xca\x02\x13Google\\Cloud\\Iam\\V1b\x06proto3' +) + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages( + DESCRIPTOR, "google.iam.v1.resource_policy_member_pb2", _globals +) +if _descriptor._USE_C_DESCRIPTORS == False: + _globals["DESCRIPTOR"]._options = None + _globals[ + "DESCRIPTOR" + ]._serialized_options = b"\n\021com.google.iam.v1B\031ResourcePolicyMemberProtoP\001Z)cloud.google.com/go/iam/apiv1/iampb;iampb\252\002\023Google.Cloud.Iam.V1\312\002\023Google\\Cloud\\Iam\\V1" + _globals["_RESOURCEPOLICYMEMBER"].fields_by_name[ + "iam_policy_name_principal" + ]._options = None + _globals["_RESOURCEPOLICYMEMBER"].fields_by_name[ + "iam_policy_name_principal" + ]._serialized_options = b"\340A\003" + _globals["_RESOURCEPOLICYMEMBER"].fields_by_name[ + "iam_policy_uid_principal" + ]._options = None + _globals["_RESOURCEPOLICYMEMBER"].fields_by_name[ + "iam_policy_uid_principal" + ]._serialized_options = b"\340A\003" + _globals["_RESOURCEPOLICYMEMBER"]._serialized_start = 94 + _globals["_RESOURCEPOLICYMEMBER"]._serialized_end = 195 +# @@protoc_insertion_point(module_scope) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/resource_policy_member_pb2.pyi b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/resource_policy_member_pb2.pyi new file mode 100644 index 0000000000000000000000000000000000000000..f3b4fdc63dc37cfdd905b1e95dc718355246d583 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/iam/v1/resource_policy_member_pb2.pyi @@ -0,0 +1,34 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. + +from typing import ClassVar as _ClassVar +from typing import Optional as _Optional + +from google.api import field_behavior_pb2 as _field_behavior_pb2 +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message + +DESCRIPTOR: _descriptor.FileDescriptor + +class ResourcePolicyMember(_message.Message): + __slots__ = ("iam_policy_name_principal", "iam_policy_uid_principal") + IAM_POLICY_NAME_PRINCIPAL_FIELD_NUMBER: _ClassVar[int] + IAM_POLICY_UID_PRINCIPAL_FIELD_NUMBER: _ClassVar[int] + iam_policy_name_principal: str + iam_policy_uid_principal: str + def __init__( + self, + iam_policy_name_principal: _Optional[str] = ..., + iam_policy_uid_principal: _Optional[str] = ..., + ) -> None: ... diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/logging/type/http_request.proto b/loan-advisor-agent/.venv/Lib/site-packages/google/logging/type/http_request.proto new file mode 100644 index 0000000000000000000000000000000000000000..b31522b69c7c292d855bb806cc80aa7b1b57362b --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/logging/type/http_request.proto @@ -0,0 +1,95 @@ +// Copyright 2025 Google LLC +// +// Licensed 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. + +syntax = "proto3"; + +package google.logging.type; + +import "google/protobuf/duration.proto"; + +option csharp_namespace = "Google.Cloud.Logging.Type"; +option go_package = "google.golang.org/genproto/googleapis/logging/type;ltype"; +option java_multiple_files = true; +option java_outer_classname = "HttpRequestProto"; +option java_package = "com.google.logging.type"; +option php_namespace = "Google\\Cloud\\Logging\\Type"; +option ruby_package = "Google::Cloud::Logging::Type"; + +// A common proto for logging HTTP requests. Only contains semantics +// defined by the HTTP specification. Product-specific logging +// information MUST be defined in a separate message. +message HttpRequest { + // The request method. Examples: `"GET"`, `"HEAD"`, `"PUT"`, `"POST"`. + string request_method = 1; + + // The scheme (http, https), the host name, the path and the query + // portion of the URL that was requested. + // Example: `"http://example.com/some/info?color=red"`. + string request_url = 2; + + // The size of the HTTP request message in bytes, including the request + // headers and the request body. + int64 request_size = 3; + + // The response code indicating the status of response. + // Examples: 200, 404. + int32 status = 4; + + // The size of the HTTP response message sent back to the client, in bytes, + // including the response headers and the response body. + int64 response_size = 5; + + // The user agent sent by the client. Example: + // `"Mozilla/4.0 (compatible; MSIE 6.0; Windows 98; Q312461; .NET + // CLR 1.0.3705)"`. + string user_agent = 6; + + // The IP address (IPv4 or IPv6) of the client that issued the HTTP + // request. This field can include port information. Examples: + // `"192.168.1.1"`, `"10.0.0.1:80"`, `"FE80::0202:B3FF:FE1E:8329"`. + string remote_ip = 7; + + // The IP address (IPv4 or IPv6) of the origin server that the request was + // sent to. This field can include port information. Examples: + // `"192.168.1.1"`, `"10.0.0.1:80"`, `"FE80::0202:B3FF:FE1E:8329"`. + string server_ip = 13; + + // The referer URL of the request, as defined in + // [HTTP/1.1 Header Field + // Definitions](https://datatracker.ietf.org/doc/html/rfc2616#section-14.36). + string referer = 8; + + // The request processing latency on the server, from the time the request was + // received until the response was sent. + google.protobuf.Duration latency = 14; + + // Whether or not a cache lookup was attempted. + bool cache_lookup = 11; + + // Whether or not an entity was served from cache + // (with or without validation). + bool cache_hit = 9; + + // Whether or not the response was validated with the origin server before + // being served from cache. This field is only meaningful if `cache_hit` is + // True. + bool cache_validated_with_origin_server = 10; + + // The number of HTTP response bytes inserted into cache. Set only when a + // cache fill was attempted. + int64 cache_fill_bytes = 12; + + // Protocol used for the request. Examples: "HTTP/1.1", "HTTP/2", "websocket" + string protocol = 15; +} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/logging/type/http_request_pb2.py b/loan-advisor-agent/.venv/Lib/site-packages/google/logging/type/http_request_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..521a91f1e9afff03f6097be8f2ed8c80ee2daea9 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/logging/type/http_request_pb2.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- + +# Copyright 2025 Google LLC +# +# Licensed 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. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/logging/type/http_request.proto +# Protobuf Python Version: 4.25.3 +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.protobuf import duration_pb2 as google_dot_protobuf_dot_duration__pb2 + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b'\n&google/logging/type/http_request.proto\x12\x13google.logging.type\x1a\x1egoogle/protobuf/duration.proto"\xef\x02\n\x0bHttpRequest\x12\x16\n\x0erequest_method\x18\x01 \x01(\t\x12\x13\n\x0brequest_url\x18\x02 \x01(\t\x12\x14\n\x0crequest_size\x18\x03 \x01(\x03\x12\x0e\n\x06status\x18\x04 \x01(\x05\x12\x15\n\rresponse_size\x18\x05 \x01(\x03\x12\x12\n\nuser_agent\x18\x06 \x01(\t\x12\x11\n\tremote_ip\x18\x07 \x01(\t\x12\x11\n\tserver_ip\x18\r \x01(\t\x12\x0f\n\x07referer\x18\x08 \x01(\t\x12*\n\x07latency\x18\x0e \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x14\n\x0c\x63\x61\x63he_lookup\x18\x0b \x01(\x08\x12\x11\n\tcache_hit\x18\t \x01(\x08\x12*\n"cache_validated_with_origin_server\x18\n \x01(\x08\x12\x18\n\x10\x63\x61\x63he_fill_bytes\x18\x0c \x01(\x03\x12\x10\n\x08protocol\x18\x0f \x01(\tB\xbe\x01\n\x17\x63om.google.logging.typeB\x10HttpRequestProtoP\x01Z8google.golang.org/genproto/googleapis/logging/type;ltype\xaa\x02\x19Google.Cloud.Logging.Type\xca\x02\x19Google\\Cloud\\Logging\\Type\xea\x02\x1cGoogle::Cloud::Logging::Typeb\x06proto3' +) + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages( + DESCRIPTOR, "google.logging.type.http_request_pb2", _globals +) +if _descriptor._USE_C_DESCRIPTORS == False: + _globals["DESCRIPTOR"]._options = None + _globals[ + "DESCRIPTOR" + ]._serialized_options = b"\n\027com.google.logging.typeB\020HttpRequestProtoP\001Z8google.golang.org/genproto/googleapis/logging/type;ltype\252\002\031Google.Cloud.Logging.Type\312\002\031Google\\Cloud\\Logging\\Type\352\002\034Google::Cloud::Logging::Type" + _globals["_HTTPREQUEST"]._serialized_start = 96 + _globals["_HTTPREQUEST"]._serialized_end = 463 +# @@protoc_insertion_point(module_scope) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/logging/type/http_request_pb2.pyi b/loan-advisor-agent/.venv/Lib/site-packages/google/logging/type/http_request_pb2.pyi new file mode 100644 index 0000000000000000000000000000000000000000..b808ded1359f6c9b5722ef553a923efa59761ef5 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/logging/type/http_request_pb2.pyi @@ -0,0 +1,91 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. + +from typing import ClassVar as _ClassVar +from typing import Mapping as _Mapping +from typing import Optional as _Optional +from typing import Union as _Union + +from google.protobuf import descriptor as _descriptor +from google.protobuf import duration_pb2 as _duration_pb2 +from google.protobuf import message as _message + +DESCRIPTOR: _descriptor.FileDescriptor + +class HttpRequest(_message.Message): + __slots__ = ( + "request_method", + "request_url", + "request_size", + "status", + "response_size", + "user_agent", + "remote_ip", + "server_ip", + "referer", + "latency", + "cache_lookup", + "cache_hit", + "cache_validated_with_origin_server", + "cache_fill_bytes", + "protocol", + ) + REQUEST_METHOD_FIELD_NUMBER: _ClassVar[int] + REQUEST_URL_FIELD_NUMBER: _ClassVar[int] + REQUEST_SIZE_FIELD_NUMBER: _ClassVar[int] + STATUS_FIELD_NUMBER: _ClassVar[int] + RESPONSE_SIZE_FIELD_NUMBER: _ClassVar[int] + USER_AGENT_FIELD_NUMBER: _ClassVar[int] + REMOTE_IP_FIELD_NUMBER: _ClassVar[int] + SERVER_IP_FIELD_NUMBER: _ClassVar[int] + REFERER_FIELD_NUMBER: _ClassVar[int] + LATENCY_FIELD_NUMBER: _ClassVar[int] + CACHE_LOOKUP_FIELD_NUMBER: _ClassVar[int] + CACHE_HIT_FIELD_NUMBER: _ClassVar[int] + CACHE_VALIDATED_WITH_ORIGIN_SERVER_FIELD_NUMBER: _ClassVar[int] + CACHE_FILL_BYTES_FIELD_NUMBER: _ClassVar[int] + PROTOCOL_FIELD_NUMBER: _ClassVar[int] + request_method: str + request_url: str + request_size: int + status: int + response_size: int + user_agent: str + remote_ip: str + server_ip: str + referer: str + latency: _duration_pb2.Duration + cache_lookup: bool + cache_hit: bool + cache_validated_with_origin_server: bool + cache_fill_bytes: int + protocol: str + def __init__( + self, + request_method: _Optional[str] = ..., + request_url: _Optional[str] = ..., + request_size: _Optional[int] = ..., + status: _Optional[int] = ..., + response_size: _Optional[int] = ..., + user_agent: _Optional[str] = ..., + remote_ip: _Optional[str] = ..., + server_ip: _Optional[str] = ..., + referer: _Optional[str] = ..., + latency: _Optional[_Union[_duration_pb2.Duration, _Mapping]] = ..., + cache_lookup: bool = ..., + cache_hit: bool = ..., + cache_validated_with_origin_server: bool = ..., + cache_fill_bytes: _Optional[int] = ..., + protocol: _Optional[str] = ..., + ) -> None: ... diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/logging/type/log_severity.proto b/loan-advisor-agent/.venv/Lib/site-packages/google/logging/type/log_severity.proto new file mode 100644 index 0000000000000000000000000000000000000000..406b8173a3aa056d8dab749db0ae731811d681c1 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/logging/type/log_severity.proto @@ -0,0 +1,71 @@ +// Copyright 2025 Google LLC +// +// Licensed 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. + +syntax = "proto3"; + +package google.logging.type; + +option csharp_namespace = "Google.Cloud.Logging.Type"; +option go_package = "google.golang.org/genproto/googleapis/logging/type;ltype"; +option java_multiple_files = true; +option java_outer_classname = "LogSeverityProto"; +option java_package = "com.google.logging.type"; +option objc_class_prefix = "GLOG"; +option php_namespace = "Google\\Cloud\\Logging\\Type"; +option ruby_package = "Google::Cloud::Logging::Type"; + +// The severity of the event described in a log entry, expressed as one of the +// standard severity levels listed below. For your reference, the levels are +// assigned the listed numeric values. The effect of using numeric values other +// than those listed is undefined. +// +// You can filter for log entries by severity. For example, the following +// filter expression will match log entries with severities `INFO`, `NOTICE`, +// and `WARNING`: +// +// severity > DEBUG AND severity <= WARNING +// +// If you are writing log entries, you should map other severity encodings to +// one of these standard levels. For example, you might map all of Java's FINE, +// FINER, and FINEST levels to `LogSeverity.DEBUG`. You can preserve the +// original severity level in the log entry payload if you wish. +enum LogSeverity { + // (0) The log entry has no assigned severity level. + DEFAULT = 0; + + // (100) Debug or trace information. + DEBUG = 100; + + // (200) Routine information, such as ongoing status or performance. + INFO = 200; + + // (300) Normal but significant events, such as start up, shut down, or + // a configuration change. + NOTICE = 300; + + // (400) Warning events might cause problems. + WARNING = 400; + + // (500) Error events are likely to cause problems. + ERROR = 500; + + // (600) Critical events cause more severe problems or outages. + CRITICAL = 600; + + // (700) A person must take an action immediately. + ALERT = 700; + + // (800) One or more systems are unusable. + EMERGENCY = 800; +} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/logging/type/log_severity_pb2.py b/loan-advisor-agent/.venv/Lib/site-packages/google/logging/type/log_severity_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..67958a4084ca9206c55e8b62efb78ef4b22e33be --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/logging/type/log_severity_pb2.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- + +# Copyright 2025 Google LLC +# +# Licensed 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. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/logging/type/log_severity.proto +# Protobuf Python Version: 4.25.3 +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b"\n&google/logging/type/log_severity.proto\x12\x13google.logging.type*\x82\x01\n\x0bLogSeverity\x12\x0b\n\x07\x44\x45\x46\x41ULT\x10\x00\x12\t\n\x05\x44\x45\x42UG\x10\x64\x12\t\n\x04INFO\x10\xc8\x01\x12\x0b\n\x06NOTICE\x10\xac\x02\x12\x0c\n\x07WARNING\x10\x90\x03\x12\n\n\x05\x45RROR\x10\xf4\x03\x12\r\n\x08\x43RITICAL\x10\xd8\x04\x12\n\n\x05\x41LERT\x10\xbc\x05\x12\x0e\n\tEMERGENCY\x10\xa0\x06\x42\xc5\x01\n\x17\x63om.google.logging.typeB\x10LogSeverityProtoP\x01Z8google.golang.org/genproto/googleapis/logging/type;ltype\xa2\x02\x04GLOG\xaa\x02\x19Google.Cloud.Logging.Type\xca\x02\x19Google\\Cloud\\Logging\\Type\xea\x02\x1cGoogle::Cloud::Logging::Typeb\x06proto3" +) + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages( + DESCRIPTOR, "google.logging.type.log_severity_pb2", _globals +) +if _descriptor._USE_C_DESCRIPTORS == False: + _globals["DESCRIPTOR"]._options = None + _globals[ + "DESCRIPTOR" + ]._serialized_options = b"\n\027com.google.logging.typeB\020LogSeverityProtoP\001Z8google.golang.org/genproto/googleapis/logging/type;ltype\242\002\004GLOG\252\002\031Google.Cloud.Logging.Type\312\002\031Google\\Cloud\\Logging\\Type\352\002\034Google::Cloud::Logging::Type" + _globals["_LOGSEVERITY"]._serialized_start = 64 + _globals["_LOGSEVERITY"]._serialized_end = 194 +# @@protoc_insertion_point(module_scope) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/logging/type/log_severity_pb2.pyi b/loan-advisor-agent/.venv/Lib/site-packages/google/logging/type/log_severity_pb2.pyi new file mode 100644 index 0000000000000000000000000000000000000000..eeafb8ed88df6bb1c6012341973a172fc2d90165 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/logging/type/log_severity_pb2.pyi @@ -0,0 +1,42 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. + +from typing import ClassVar as _ClassVar + +from google.protobuf import descriptor as _descriptor +from google.protobuf.internal import enum_type_wrapper as _enum_type_wrapper + +DESCRIPTOR: _descriptor.FileDescriptor + +class LogSeverity(int, metaclass=_enum_type_wrapper.EnumTypeWrapper): + __slots__ = () + DEFAULT: _ClassVar[LogSeverity] + DEBUG: _ClassVar[LogSeverity] + INFO: _ClassVar[LogSeverity] + NOTICE: _ClassVar[LogSeverity] + WARNING: _ClassVar[LogSeverity] + ERROR: _ClassVar[LogSeverity] + CRITICAL: _ClassVar[LogSeverity] + ALERT: _ClassVar[LogSeverity] + EMERGENCY: _ClassVar[LogSeverity] + +DEFAULT: LogSeverity +DEBUG: LogSeverity +INFO: LogSeverity +NOTICE: LogSeverity +WARNING: LogSeverity +ERROR: LogSeverity +CRITICAL: LogSeverity +ALERT: LogSeverity +EMERGENCY: LogSeverity diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/longrunning/__pycache__/operations_grpc_pb2.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/longrunning/__pycache__/operations_grpc_pb2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..50b0e33e2ce36ae62b51dc6049c80fdd23514609 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/longrunning/__pycache__/operations_grpc_pb2.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/longrunning/__pycache__/operations_pb2.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/longrunning/__pycache__/operations_pb2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d06cd6acbe8b7416a3f447bea31826852be6974b Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/longrunning/__pycache__/operations_pb2.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/longrunning/__pycache__/operations_pb2_grpc.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/longrunning/__pycache__/operations_pb2_grpc.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..09fe348f36f300f688f61b9cf28b9b596e8c9e7a Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/longrunning/__pycache__/operations_pb2_grpc.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/longrunning/__pycache__/operations_proto_pb2.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/longrunning/__pycache__/operations_proto_pb2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca2816e2304057f6af2a72e15e6a3340b4452f12 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/longrunning/__pycache__/operations_proto_pb2.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/longrunning/operations_grpc.py b/loan-advisor-agent/.venv/Lib/site-packages/google/longrunning/operations_grpc.py new file mode 100644 index 0000000000000000000000000000000000000000..0545e8c9dd75e55fb13067fd80bcf9508eab1a7d --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/longrunning/operations_grpc.py @@ -0,0 +1,20 @@ +# Copyright 2020 Google LLC +# +# Licensed 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 +# +# https://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. + +# This module is provided for backwards compatibility with +# googleapis-common-protos <= 1.5.0, where this was the import path. + +from __future__ import absolute_import + +from google.longrunning.operations_grpc_pb2 import * # noqa: F401, F403 diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/longrunning/operations_grpc_pb2.py b/loan-advisor-agent/.venv/Lib/site-packages/google/longrunning/operations_grpc_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..d03fe28e4428915072aaa71025f95e78e649869b --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/longrunning/operations_grpc_pb2.py @@ -0,0 +1,16 @@ +# This module is provided for backwards compatibility with +# googleapis-common-protos <= 1.52.0, where this import path contained +# all of the message and gRPC definitions. + +from google.longrunning.operations_pb2_grpc import * +from google.longrunning.operations_proto_pb2 import * +from google.longrunning.operations_proto_pb2 import ( + _CANCELOPERATIONREQUEST, + _DELETEOPERATIONREQUEST, + _GETOPERATIONREQUEST, + _LISTOPERATIONSREQUEST, + _LISTOPERATIONSRESPONSE, + _OPERATION, + _OPERATIONINFO, + _OPERATIONS, +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/longrunning/operations_pb2.py b/loan-advisor-agent/.venv/Lib/site-packages/google/longrunning/operations_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..928c33600ecfad420552e3df74e1001fc6c4a3b8 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/longrunning/operations_pb2.py @@ -0,0 +1,45 @@ +# Copyright 2016 Google Inc. All Rights Reserved. +# +# Licensed 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. + +"""Safe implementation of long-running operations with and without gRPC. + +Multiplexes between versions of long-running operations with and without gRPC. +The former is preferred, but not possible in all environments (such as Google +AppEngine Standard). +""" + +try: + from google.longrunning.operations_grpc_pb2 import * + from google.longrunning.operations_grpc_pb2 import ( + _CANCELOPERATIONREQUEST, + _DELETEOPERATIONREQUEST, + _GETOPERATIONREQUEST, + _LISTOPERATIONSREQUEST, + _LISTOPERATIONSRESPONSE, + _OPERATION, + _OPERATIONINFO, + _OPERATIONS, + ) +except ImportError: + from google.longrunning.operations_proto_pb2 import * + from google.longrunning.operations_proto_pb2 import ( + _CANCELOPERATIONREQUEST, + _DELETEOPERATIONREQUEST, + _GETOPERATIONREQUEST, + _LISTOPERATIONSREQUEST, + _LISTOPERATIONSRESPONSE, + _OPERATION, + _OPERATIONINFO, + _OPERATIONS, + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/longrunning/operations_pb2_grpc.py b/loan-advisor-agent/.venv/Lib/site-packages/google/longrunning/operations_pb2_grpc.py new file mode 100644 index 0000000000000000000000000000000000000000..6bf00bd4dc9d2f54793b8df0e997e52ec2e63d94 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/longrunning/operations_pb2_grpc.py @@ -0,0 +1,341 @@ +# Copyright 2020 Google LLC +# +# Licensed 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. + +# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! + +"""Client and server classes corresponding to protobuf-defined services.""" + +import grpc +from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 + +from google.longrunning import ( + operations_proto_pb2 as google_dot_longrunning_dot_operations__pb2, +) + + +class OperationsStub(object): + """Manages long-running operations with an API service. + + When an API method normally takes long time to complete, it can be designed + to return [Operation][google.longrunning.Operation] to the client, and the client can use this + interface to receive the real response asynchronously by polling the + operation resource, or pass the operation resource to another API (such as + Google Cloud Pub/Sub API) to receive the response. Any API service that + returns long-running operations should implement the `Operations` interface + so developers can have a consistent client experience. + """ + + def __init__(self, channel): + """Constructor. + + Args: + channel: A grpc.Channel. + """ + self.ListOperations = channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=google_dot_longrunning_dot_operations__pb2.ListOperationsRequest.SerializeToString, + response_deserializer=google_dot_longrunning_dot_operations__pb2.ListOperationsResponse.FromString, + ) + self.GetOperation = channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=google_dot_longrunning_dot_operations__pb2.GetOperationRequest.SerializeToString, + response_deserializer=google_dot_longrunning_dot_operations__pb2.Operation.FromString, + ) + self.DeleteOperation = channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=google_dot_longrunning_dot_operations__pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, + ) + self.CancelOperation = channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=google_dot_longrunning_dot_operations__pb2.CancelOperationRequest.SerializeToString, + response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, + ) + self.WaitOperation = channel.unary_unary( + "/google.longrunning.Operations/WaitOperation", + request_serializer=google_dot_longrunning_dot_operations__pb2.WaitOperationRequest.SerializeToString, + response_deserializer=google_dot_longrunning_dot_operations__pb2.Operation.FromString, + ) + + +class OperationsServicer(object): + """Manages long-running operations with an API service. + + When an API method normally takes long time to complete, it can be designed + to return [Operation][google.longrunning.Operation] to the client, and the client can use this + interface to receive the real response asynchronously by polling the + operation resource, or pass the operation resource to another API (such as + Google Cloud Pub/Sub API) to receive the response. Any API service that + returns long-running operations should implement the `Operations` interface + so developers can have a consistent client experience. + """ + + def ListOperations(self, request, context): + """Lists operations that match the specified filter in the request. If the + server doesn't support this method, it returns `UNIMPLEMENTED`. + + NOTE: the `name` binding allows API services to override the binding + to use different resource name schemes, such as `users/*/operations`. To + override the binding, API services can add a binding such as + `"/v1/{name=users/*}/operations"` to their service configuration. + For backwards compatibility, the default name includes the operations + collection id, however overriding users must ensure the name binding + is the parent resource, without the operations collection id. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details("Method not implemented!") + raise NotImplementedError("Method not implemented!") + + def GetOperation(self, request, context): + """Gets the latest state of a long-running operation. Clients can use this + method to poll the operation result at intervals as recommended by the API + service. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details("Method not implemented!") + raise NotImplementedError("Method not implemented!") + + def DeleteOperation(self, request, context): + """Deletes a long-running operation. This method indicates that the client is + no longer interested in the operation result. It does not cancel the + operation. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details("Method not implemented!") + raise NotImplementedError("Method not implemented!") + + def CancelOperation(self, request, context): + """Starts asynchronous cancellation on a long-running operation. The server + makes a best effort to cancel the operation, but success is not + guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. Clients can use + [Operations.GetOperation][google.longrunning.Operations.GetOperation] or + other methods to check whether the cancellation succeeded or whether the + operation completed despite cancellation. On successful cancellation, + the operation is not deleted; instead, it becomes an operation with + an [Operation.error][google.longrunning.Operation.error] value with a [google.rpc.Status.code][google.rpc.Status.code] of 1, + corresponding to `Code.CANCELLED`. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details("Method not implemented!") + raise NotImplementedError("Method not implemented!") + + def WaitOperation(self, request, context): + """Waits until the specified long-running operation is done or reaches at most + a specified timeout, returning the latest state. If the operation is + already done, the latest state is immediately returned. If the timeout + specified is greater than the default HTTP/RPC timeout, the HTTP/RPC + timeout is used. If the server does not support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + Note that this method is on a best-effort basis. It may return the latest + state before the specified timeout (including immediately), meaning even an + immediate response is no guarantee that the operation is done. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details("Method not implemented!") + raise NotImplementedError("Method not implemented!") + + +def add_OperationsServicer_to_server(servicer, server): + rpc_method_handlers = { + "ListOperations": grpc.unary_unary_rpc_method_handler( + servicer.ListOperations, + request_deserializer=google_dot_longrunning_dot_operations__pb2.ListOperationsRequest.FromString, + response_serializer=google_dot_longrunning_dot_operations__pb2.ListOperationsResponse.SerializeToString, + ), + "GetOperation": grpc.unary_unary_rpc_method_handler( + servicer.GetOperation, + request_deserializer=google_dot_longrunning_dot_operations__pb2.GetOperationRequest.FromString, + response_serializer=google_dot_longrunning_dot_operations__pb2.Operation.SerializeToString, + ), + "DeleteOperation": grpc.unary_unary_rpc_method_handler( + servicer.DeleteOperation, + request_deserializer=google_dot_longrunning_dot_operations__pb2.DeleteOperationRequest.FromString, + response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, + ), + "CancelOperation": grpc.unary_unary_rpc_method_handler( + servicer.CancelOperation, + request_deserializer=google_dot_longrunning_dot_operations__pb2.CancelOperationRequest.FromString, + response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, + ), + "WaitOperation": grpc.unary_unary_rpc_method_handler( + servicer.WaitOperation, + request_deserializer=google_dot_longrunning_dot_operations__pb2.WaitOperationRequest.FromString, + response_serializer=google_dot_longrunning_dot_operations__pb2.Operation.SerializeToString, + ), + } + generic_handler = grpc.method_handlers_generic_handler( + "google.longrunning.Operations", rpc_method_handlers + ) + server.add_generic_rpc_handlers((generic_handler,)) + + +# This class is part of an EXPERIMENTAL API. +class Operations(object): + """Manages long-running operations with an API service. + + When an API method normally takes long time to complete, it can be designed + to return [Operation][google.longrunning.Operation] to the client, and the client can use this + interface to receive the real response asynchronously by polling the + operation resource, or pass the operation resource to another API (such as + Google Cloud Pub/Sub API) to receive the response. Any API service that + returns long-running operations should implement the `Operations` interface + so developers can have a consistent client experience. + """ + + @staticmethod + def ListOperations( + request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None, + ): + return grpc.experimental.unary_unary( + request, + target, + "/google.longrunning.Operations/ListOperations", + google_dot_longrunning_dot_operations__pb2.ListOperationsRequest.SerializeToString, + google_dot_longrunning_dot_operations__pb2.ListOperationsResponse.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, + ) + + @staticmethod + def GetOperation( + request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None, + ): + return grpc.experimental.unary_unary( + request, + target, + "/google.longrunning.Operations/GetOperation", + google_dot_longrunning_dot_operations__pb2.GetOperationRequest.SerializeToString, + google_dot_longrunning_dot_operations__pb2.Operation.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, + ) + + @staticmethod + def DeleteOperation( + request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None, + ): + return grpc.experimental.unary_unary( + request, + target, + "/google.longrunning.Operations/DeleteOperation", + google_dot_longrunning_dot_operations__pb2.DeleteOperationRequest.SerializeToString, + google_dot_protobuf_dot_empty__pb2.Empty.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, + ) + + @staticmethod + def CancelOperation( + request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None, + ): + return grpc.experimental.unary_unary( + request, + target, + "/google.longrunning.Operations/CancelOperation", + google_dot_longrunning_dot_operations__pb2.CancelOperationRequest.SerializeToString, + google_dot_protobuf_dot_empty__pb2.Empty.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, + ) + + @staticmethod + def WaitOperation( + request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None, + ): + return grpc.experimental.unary_unary( + request, + target, + "/google.longrunning.Operations/WaitOperation", + google_dot_longrunning_dot_operations__pb2.WaitOperationRequest.SerializeToString, + google_dot_longrunning_dot_operations__pb2.Operation.FromString, + options, + channel_credentials, + insecure, + call_credentials, + compression, + wait_for_ready, + timeout, + metadata, + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/longrunning/operations_proto.proto b/loan-advisor-agent/.venv/Lib/site-packages/google/longrunning/operations_proto.proto new file mode 100644 index 0000000000000000000000000000000000000000..e0206a906103d4673c6a5af22e5539cf3687b736 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/longrunning/operations_proto.proto @@ -0,0 +1,246 @@ +// Copyright 2025 Google LLC +// +// Licensed 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. + +syntax = "proto3"; + +package google.longrunning; + +import "google/api/annotations.proto"; +import "google/api/client.proto"; +import "google/protobuf/any.proto"; +import "google/protobuf/descriptor.proto"; +import "google/protobuf/duration.proto"; +import "google/protobuf/empty.proto"; +import "google/rpc/status.proto"; + +option cc_enable_arenas = true; +option csharp_namespace = "Google.LongRunning"; +option go_package = "cloud.google.com/go/longrunning/autogen/longrunningpb;longrunningpb"; +option java_multiple_files = true; +option java_outer_classname = "OperationsProto"; +option java_package = "com.google.longrunning"; +option objc_class_prefix = "GLRUN"; +option php_namespace = "Google\\LongRunning"; + +extend google.protobuf.MethodOptions { + // Additional information regarding long-running operations. + // In particular, this specifies the types that are returned from + // long-running operations. + // + // Required for methods that return `google.longrunning.Operation`; invalid + // otherwise. + google.longrunning.OperationInfo operation_info = 1049; +} + +// Manages long-running operations with an API service. +// +// When an API method normally takes long time to complete, it can be designed +// to return [Operation][google.longrunning.Operation] to the client, and the +// client can use this interface to receive the real response asynchronously by +// polling the operation resource, or pass the operation resource to another API +// (such as Pub/Sub API) to receive the response. Any API service that returns +// long-running operations should implement the `Operations` interface so +// developers can have a consistent client experience. +service Operations { + option (google.api.default_host) = "longrunning.googleapis.com"; + + // Lists operations that match the specified filter in the request. If the + // server doesn't support this method, it returns `UNIMPLEMENTED`. + rpc ListOperations(ListOperationsRequest) returns (ListOperationsResponse) { + option (google.api.http) = { + get: "/v1/{name=operations}" + }; + option (google.api.method_signature) = "name,filter"; + } + + // Gets the latest state of a long-running operation. Clients can use this + // method to poll the operation result at intervals as recommended by the API + // service. + rpc GetOperation(GetOperationRequest) returns (Operation) { + option (google.api.http) = { + get: "/v1/{name=operations/**}" + }; + option (google.api.method_signature) = "name"; + } + + // Deletes a long-running operation. This method indicates that the client is + // no longer interested in the operation result. It does not cancel the + // operation. If the server doesn't support this method, it returns + // `google.rpc.Code.UNIMPLEMENTED`. + rpc DeleteOperation(DeleteOperationRequest) returns (google.protobuf.Empty) { + option (google.api.http) = { + delete: "/v1/{name=operations/**}" + }; + option (google.api.method_signature) = "name"; + } + + // Starts asynchronous cancellation on a long-running operation. The server + // makes a best effort to cancel the operation, but success is not + // guaranteed. If the server doesn't support this method, it returns + // `google.rpc.Code.UNIMPLEMENTED`. Clients can use + // [Operations.GetOperation][google.longrunning.Operations.GetOperation] or + // other methods to check whether the cancellation succeeded or whether the + // operation completed despite cancellation. On successful cancellation, + // the operation is not deleted; instead, it becomes an operation with + // an [Operation.error][google.longrunning.Operation.error] value with a + // [google.rpc.Status.code][google.rpc.Status.code] of `1`, corresponding to + // `Code.CANCELLED`. + rpc CancelOperation(CancelOperationRequest) returns (google.protobuf.Empty) { + option (google.api.http) = { + post: "/v1/{name=operations/**}:cancel" + body: "*" + }; + option (google.api.method_signature) = "name"; + } + + // Waits until the specified long-running operation is done or reaches at most + // a specified timeout, returning the latest state. If the operation is + // already done, the latest state is immediately returned. If the timeout + // specified is greater than the default HTTP/RPC timeout, the HTTP/RPC + // timeout is used. If the server does not support this method, it returns + // `google.rpc.Code.UNIMPLEMENTED`. + // Note that this method is on a best-effort basis. It may return the latest + // state before the specified timeout (including immediately), meaning even an + // immediate response is no guarantee that the operation is done. + rpc WaitOperation(WaitOperationRequest) returns (Operation) {} +} + +// This resource represents a long-running operation that is the result of a +// network API call. +message Operation { + // The server-assigned name, which is only unique within the same service that + // originally returns it. If you use the default HTTP mapping, the + // `name` should be a resource name ending with `operations/{unique_id}`. + string name = 1; + + // Service-specific metadata associated with the operation. It typically + // contains progress information and common metadata such as create time. + // Some services might not provide such metadata. Any method that returns a + // long-running operation should document the metadata type, if any. + google.protobuf.Any metadata = 2; + + // If the value is `false`, it means the operation is still in progress. + // If `true`, the operation is completed, and either `error` or `response` is + // available. + bool done = 3; + + // The operation result, which can be either an `error` or a valid `response`. + // If `done` == `false`, neither `error` nor `response` is set. + // If `done` == `true`, exactly one of `error` or `response` can be set. + // Some services might not provide the result. + oneof result { + // The error result of the operation in case of failure or cancellation. + google.rpc.Status error = 4; + + // The normal, successful response of the operation. If the original + // method returns no data on success, such as `Delete`, the response is + // `google.protobuf.Empty`. If the original method is standard + // `Get`/`Create`/`Update`, the response should be the resource. For other + // methods, the response should have the type `XxxResponse`, where `Xxx` + // is the original method name. For example, if the original method name + // is `TakeSnapshot()`, the inferred response type is + // `TakeSnapshotResponse`. + google.protobuf.Any response = 5; + } +} + +// The request message for +// [Operations.GetOperation][google.longrunning.Operations.GetOperation]. +message GetOperationRequest { + // The name of the operation resource. + string name = 1; +} + +// The request message for +// [Operations.ListOperations][google.longrunning.Operations.ListOperations]. +message ListOperationsRequest { + // The name of the operation's parent resource. + string name = 4; + + // The standard list filter. + string filter = 1; + + // The standard list page size. + int32 page_size = 2; + + // The standard list page token. + string page_token = 3; +} + +// The response message for +// [Operations.ListOperations][google.longrunning.Operations.ListOperations]. +message ListOperationsResponse { + // A list of operations that matches the specified filter in the request. + repeated Operation operations = 1; + + // The standard List next-page token. + string next_page_token = 2; +} + +// The request message for +// [Operations.CancelOperation][google.longrunning.Operations.CancelOperation]. +message CancelOperationRequest { + // The name of the operation resource to be cancelled. + string name = 1; +} + +// The request message for +// [Operations.DeleteOperation][google.longrunning.Operations.DeleteOperation]. +message DeleteOperationRequest { + // The name of the operation resource to be deleted. + string name = 1; +} + +// The request message for +// [Operations.WaitOperation][google.longrunning.Operations.WaitOperation]. +message WaitOperationRequest { + // The name of the operation resource to wait on. + string name = 1; + + // The maximum duration to wait before timing out. If left blank, the wait + // will be at most the time permitted by the underlying HTTP/RPC protocol. + // If RPC context deadline is also specified, the shorter one will be used. + google.protobuf.Duration timeout = 2; +} + +// A message representing the message types used by a long-running operation. +// +// Example: +// +// rpc Export(ExportRequest) returns (google.longrunning.Operation) { +// option (google.longrunning.operation_info) = { +// response_type: "ExportResponse" +// metadata_type: "ExportMetadata" +// }; +// } +message OperationInfo { + // Required. The message name of the primary return type for this + // long-running operation. + // This type will be used to deserialize the LRO's response. + // + // If the response is in a different package from the rpc, a fully-qualified + // message name must be used (e.g. `google.protobuf.Struct`). + // + // Note: Altering this value constitutes a breaking change. + string response_type = 1; + + // Required. The message name of the metadata type for this long-running + // operation. + // + // If the response is in a different package from the rpc, a fully-qualified + // message name must be used (e.g. `google.protobuf.Struct`). + // + // Note: Altering this value constitutes a breaking change. + string metadata_type = 2; +} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/longrunning/operations_proto.py b/loan-advisor-agent/.venv/Lib/site-packages/google/longrunning/operations_proto.py new file mode 100644 index 0000000000000000000000000000000000000000..35d1facade44a2dc67eb8b9e57ec51f971480e46 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/longrunning/operations_proto.py @@ -0,0 +1,6 @@ +# This module is provided for backwards compatibility with +# googleapis-common-protos <= 1.5.0, where this was the import path. + +from __future__ import absolute_import + +from google.longrunning.operations_proto_pb2 import * # noqa: F401, F403 diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/longrunning/operations_proto_pb2.py b/loan-advisor-agent/.venv/Lib/site-packages/google/longrunning/operations_proto_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..3ec02b13d89fa30119bf74bba566d6b4d824a913 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/longrunning/operations_proto_pb2.py @@ -0,0 +1,99 @@ +# -*- coding: utf-8 -*- + +# Copyright 2025 Google LLC +# +# Licensed 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. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/longrunning/operations.proto +# Protobuf Python Version: 4.25.3 +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.protobuf import any_pb2 as google_dot_protobuf_dot_any__pb2 +from google.protobuf import descriptor_pb2 as google_dot_protobuf_dot_descriptor__pb2 +from google.protobuf import duration_pb2 as google_dot_protobuf_dot_duration__pb2 +from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 + +from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 +from google.api import client_pb2 as google_dot_api_dot_client__pb2 +from google.rpc import status_pb2 as google_dot_rpc_dot_status__pb2 + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b'\n#google/longrunning/operations.proto\x12\x12google.longrunning\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x19google/protobuf/any.proto\x1a google/protobuf/descriptor.proto\x1a\x1egoogle/protobuf/duration.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a\x17google/rpc/status.proto"\xa8\x01\n\tOperation\x12\x0c\n\x04name\x18\x01 \x01(\t\x12&\n\x08metadata\x18\x02 \x01(\x0b\x32\x14.google.protobuf.Any\x12\x0c\n\x04\x64one\x18\x03 \x01(\x08\x12#\n\x05\x65rror\x18\x04 \x01(\x0b\x32\x12.google.rpc.StatusH\x00\x12(\n\x08response\x18\x05 \x01(\x0b\x32\x14.google.protobuf.AnyH\x00\x42\x08\n\x06result"#\n\x13GetOperationRequest\x12\x0c\n\x04name\x18\x01 \x01(\t"\\\n\x15ListOperationsRequest\x12\x0c\n\x04name\x18\x04 \x01(\t\x12\x0e\n\x06\x66ilter\x18\x01 \x01(\t\x12\x11\n\tpage_size\x18\x02 \x01(\x05\x12\x12\n\npage_token\x18\x03 \x01(\t"d\n\x16ListOperationsResponse\x12\x31\n\noperations\x18\x01 \x03(\x0b\x32\x1d.google.longrunning.Operation\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t"&\n\x16\x43\x61ncelOperationRequest\x12\x0c\n\x04name\x18\x01 \x01(\t"&\n\x16\x44\x65leteOperationRequest\x12\x0c\n\x04name\x18\x01 \x01(\t"P\n\x14WaitOperationRequest\x12\x0c\n\x04name\x18\x01 \x01(\t\x12*\n\x07timeout\x18\x02 \x01(\x0b\x32\x19.google.protobuf.Duration"=\n\rOperationInfo\x12\x15\n\rresponse_type\x18\x01 \x01(\t\x12\x15\n\rmetadata_type\x18\x02 \x01(\t2\xaa\x05\n\nOperations\x12\x94\x01\n\x0eListOperations\x12).google.longrunning.ListOperationsRequest\x1a*.google.longrunning.ListOperationsResponse"+\xda\x41\x0bname,filter\x82\xd3\xe4\x93\x02\x17\x12\x15/v1/{name=operations}\x12\x7f\n\x0cGetOperation\x12\'.google.longrunning.GetOperationRequest\x1a\x1d.google.longrunning.Operation"\'\xda\x41\x04name\x82\xd3\xe4\x93\x02\x1a\x12\x18/v1/{name=operations/**}\x12~\n\x0f\x44\x65leteOperation\x12*.google.longrunning.DeleteOperationRequest\x1a\x16.google.protobuf.Empty"\'\xda\x41\x04name\x82\xd3\xe4\x93\x02\x1a*\x18/v1/{name=operations/**}\x12\x88\x01\n\x0f\x43\x61ncelOperation\x12*.google.longrunning.CancelOperationRequest\x1a\x16.google.protobuf.Empty"1\xda\x41\x04name\x82\xd3\xe4\x93\x02$"\x1f/v1/{name=operations/**}:cancel:\x01*\x12Z\n\rWaitOperation\x12(.google.longrunning.WaitOperationRequest\x1a\x1d.google.longrunning.Operation"\x00\x1a\x1d\xca\x41\x1alongrunning.googleapis.com:Z\n\x0eoperation_info\x12\x1e.google.protobuf.MethodOptions\x18\x99\x08 \x01(\x0b\x32!.google.longrunning.OperationInfoB\xa5\x01\n\x16\x63om.google.longrunningB\x0fOperationsProtoP\x01ZCcloud.google.com/go/longrunning/autogen/longrunningpb;longrunningpb\xf8\x01\x01\xa2\x02\x05GLRUN\xaa\x02\x12Google.LongRunning\xca\x02\x12Google\\LongRunningb\x06proto3' +) + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages( + DESCRIPTOR, "google.longrunning.operations_pb2", _globals +) +if _descriptor._USE_C_DESCRIPTORS == False: + _globals["DESCRIPTOR"]._options = None + _globals[ + "DESCRIPTOR" + ]._serialized_options = b"\n\026com.google.longrunningB\017OperationsProtoP\001ZCcloud.google.com/go/longrunning/autogen/longrunningpb;longrunningpb\370\001\001\242\002\005GLRUN\252\002\022Google.LongRunning\312\002\022Google\\LongRunning" + _globals["_OPERATIONS"]._options = None + _globals["_OPERATIONS"]._serialized_options = b"\312A\032longrunning.googleapis.com" + _globals["_OPERATIONS"].methods_by_name["ListOperations"]._options = None + _globals["_OPERATIONS"].methods_by_name[ + "ListOperations" + ]._serialized_options = ( + b"\332A\013name,filter\202\323\344\223\002\027\022\025/v1/{name=operations}" + ) + _globals["_OPERATIONS"].methods_by_name["GetOperation"]._options = None + _globals["_OPERATIONS"].methods_by_name[ + "GetOperation" + ]._serialized_options = ( + b"\332A\004name\202\323\344\223\002\032\022\030/v1/{name=operations/**}" + ) + _globals["_OPERATIONS"].methods_by_name["DeleteOperation"]._options = None + _globals["_OPERATIONS"].methods_by_name[ + "DeleteOperation" + ]._serialized_options = ( + b"\332A\004name\202\323\344\223\002\032*\030/v1/{name=operations/**}" + ) + _globals["_OPERATIONS"].methods_by_name["CancelOperation"]._options = None + _globals["_OPERATIONS"].methods_by_name[ + "CancelOperation" + ]._serialized_options = ( + b'\332A\004name\202\323\344\223\002$"\037/v1/{name=operations/**}:cancel:\001*' + ) + _globals["_OPERATION"]._serialized_start = 262 + _globals["_OPERATION"]._serialized_end = 430 + _globals["_GETOPERATIONREQUEST"]._serialized_start = 432 + _globals["_GETOPERATIONREQUEST"]._serialized_end = 467 + _globals["_LISTOPERATIONSREQUEST"]._serialized_start = 469 + _globals["_LISTOPERATIONSREQUEST"]._serialized_end = 561 + _globals["_LISTOPERATIONSRESPONSE"]._serialized_start = 563 + _globals["_LISTOPERATIONSRESPONSE"]._serialized_end = 663 + _globals["_CANCELOPERATIONREQUEST"]._serialized_start = 665 + _globals["_CANCELOPERATIONREQUEST"]._serialized_end = 703 + _globals["_DELETEOPERATIONREQUEST"]._serialized_start = 705 + _globals["_DELETEOPERATIONREQUEST"]._serialized_end = 743 + _globals["_WAITOPERATIONREQUEST"]._serialized_start = 745 + _globals["_WAITOPERATIONREQUEST"]._serialized_end = 825 + _globals["_OPERATIONINFO"]._serialized_start = 827 + _globals["_OPERATIONINFO"]._serialized_end = 888 + _globals["_OPERATIONS"]._serialized_start = 891 + _globals["_OPERATIONS"]._serialized_end = 1573 +# @@protoc_insertion_point(module_scope) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/longrunning/operations_proto_pb2.pyi b/loan-advisor-agent/.venv/Lib/site-packages/google/longrunning/operations_proto_pb2.pyi new file mode 100644 index 0000000000000000000000000000000000000000..a0d45c540fa9f3474655fdb00108dd23241d35a1 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/longrunning/operations_proto_pb2.pyi @@ -0,0 +1,126 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. + +from typing import ClassVar as _ClassVar +from typing import Iterable as _Iterable +from typing import Mapping as _Mapping +from typing import Optional as _Optional +from typing import Union as _Union + +from google.protobuf import any_pb2 as _any_pb2 +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pb2 as _descriptor_pb2 +from google.protobuf import duration_pb2 as _duration_pb2 +from google.protobuf import empty_pb2 as _empty_pb2 +from google.protobuf import message as _message +from google.protobuf.internal import containers as _containers + +from google.api import annotations_pb2 as _annotations_pb2 +from google.api import client_pb2 as _client_pb2 +from google.rpc import status_pb2 as _status_pb2 + +DESCRIPTOR: _descriptor.FileDescriptor +OPERATION_INFO_FIELD_NUMBER: _ClassVar[int] +operation_info: _descriptor.FieldDescriptor + +class Operation(_message.Message): + __slots__ = ("name", "metadata", "done", "error", "response") + NAME_FIELD_NUMBER: _ClassVar[int] + METADATA_FIELD_NUMBER: _ClassVar[int] + DONE_FIELD_NUMBER: _ClassVar[int] + ERROR_FIELD_NUMBER: _ClassVar[int] + RESPONSE_FIELD_NUMBER: _ClassVar[int] + name: str + metadata: _any_pb2.Any + done: bool + error: _status_pb2.Status + response: _any_pb2.Any + def __init__( + self, + name: _Optional[str] = ..., + metadata: _Optional[_Union[_any_pb2.Any, _Mapping]] = ..., + done: bool = ..., + error: _Optional[_Union[_status_pb2.Status, _Mapping]] = ..., + response: _Optional[_Union[_any_pb2.Any, _Mapping]] = ..., + ) -> None: ... + +class GetOperationRequest(_message.Message): + __slots__ = ("name",) + NAME_FIELD_NUMBER: _ClassVar[int] + name: str + def __init__(self, name: _Optional[str] = ...) -> None: ... + +class ListOperationsRequest(_message.Message): + __slots__ = ("name", "filter", "page_size", "page_token") + NAME_FIELD_NUMBER: _ClassVar[int] + FILTER_FIELD_NUMBER: _ClassVar[int] + PAGE_SIZE_FIELD_NUMBER: _ClassVar[int] + PAGE_TOKEN_FIELD_NUMBER: _ClassVar[int] + name: str + filter: str + page_size: int + page_token: str + def __init__( + self, + name: _Optional[str] = ..., + filter: _Optional[str] = ..., + page_size: _Optional[int] = ..., + page_token: _Optional[str] = ..., + ) -> None: ... + +class ListOperationsResponse(_message.Message): + __slots__ = ("operations", "next_page_token") + OPERATIONS_FIELD_NUMBER: _ClassVar[int] + NEXT_PAGE_TOKEN_FIELD_NUMBER: _ClassVar[int] + operations: _containers.RepeatedCompositeFieldContainer[Operation] + next_page_token: str + def __init__( + self, + operations: _Optional[_Iterable[_Union[Operation, _Mapping]]] = ..., + next_page_token: _Optional[str] = ..., + ) -> None: ... + +class CancelOperationRequest(_message.Message): + __slots__ = ("name",) + NAME_FIELD_NUMBER: _ClassVar[int] + name: str + def __init__(self, name: _Optional[str] = ...) -> None: ... + +class DeleteOperationRequest(_message.Message): + __slots__ = ("name",) + NAME_FIELD_NUMBER: _ClassVar[int] + name: str + def __init__(self, name: _Optional[str] = ...) -> None: ... + +class WaitOperationRequest(_message.Message): + __slots__ = ("name", "timeout") + NAME_FIELD_NUMBER: _ClassVar[int] + TIMEOUT_FIELD_NUMBER: _ClassVar[int] + name: str + timeout: _duration_pb2.Duration + def __init__( + self, + name: _Optional[str] = ..., + timeout: _Optional[_Union[_duration_pb2.Duration, _Mapping]] = ..., + ) -> None: ... + +class OperationInfo(_message.Message): + __slots__ = ("response_type", "metadata_type") + RESPONSE_TYPE_FIELD_NUMBER: _ClassVar[int] + METADATA_TYPE_FIELD_NUMBER: _ClassVar[int] + response_type: str + metadata_type: str + def __init__( + self, response_type: _Optional[str] = ..., metadata_type: _Optional[str] = ... + ) -> None: ... diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..56c2e629a1918988653bd15133888ac7525e01f9 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/__init__.py @@ -0,0 +1,40 @@ +# Copyright 2016 Google LLC +# +# Licensed 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. + +"""Google OAuth 2.0 Library for Python.""" + +import sys +import warnings + + +class Python37DeprecationWarning(DeprecationWarning): # pragma: NO COVER + """ + Deprecation warning raised when Python 3.7 runtime is detected. + Python 3.7 support will be dropped after January 1, 2024. + """ + + pass + + +# Raise warnings for deprecated versions +eol_message = ( + "You are using a Python version {} past its end of life. Google will update " + "google-auth with critical bug fixes on a best-effort basis, but not " + "with any other fixes or features. Please upgrade your Python version, " + "and then update google-auth." +) +if sys.version_info.major == 3 and sys.version_info.minor == 8: # pragma: NO COVER + warnings.warn(eol_message.format("3.8"), FutureWarning) +elif sys.version_info.major == 3 and sys.version_info.minor == 9: # pragma: NO COVER + warnings.warn(eol_message.format("3.9"), FutureWarning) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/__pycache__/__init__.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..086292918923ed65100337d7d96a7d7996c46c56 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/__pycache__/__init__.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/__pycache__/_client.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/__pycache__/_client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da1e7354aa70b2f279d194b88c8c76f077efed92 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/__pycache__/_client.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/__pycache__/challenges.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/__pycache__/challenges.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a7a30b7ffa47b1ebc41b83dbd19ae7c9d7f901cc Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/__pycache__/challenges.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/__pycache__/credentials.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/__pycache__/credentials.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5fd73b0efb7b7cd12fbd7c6c0d1f0230fa7d279b Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/__pycache__/credentials.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/__pycache__/reauth.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/__pycache__/reauth.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3c210157b3e4b59a066ff424c8326b631180b2d9 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/__pycache__/reauth.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/__pycache__/service_account.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/__pycache__/service_account.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d91598c554a0446c4e7b10eb005ee9dac42c7d5f Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/__pycache__/service_account.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/__pycache__/webauthn_handler.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/__pycache__/webauthn_handler.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a7fbd58432495ecb687f9e7855e18cf49b49a61 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/__pycache__/webauthn_handler.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/__pycache__/webauthn_handler_factory.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/__pycache__/webauthn_handler_factory.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df160e54c44d949f2e505cc5610ec7b421ebb51e Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/__pycache__/webauthn_handler_factory.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/__pycache__/webauthn_types.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/__pycache__/webauthn_types.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d9e31075ff7f6cc3692ea7fb56cf8178dbe1a1a Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/__pycache__/webauthn_types.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/_client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/_client.py new file mode 100644 index 0000000000000000000000000000000000000000..d4db420070ef931fbc7cb9bbaa854fa5a39e3ea9 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/_client.py @@ -0,0 +1,631 @@ +# Copyright 2016 Google LLC +# +# Licensed 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. + +"""OAuth 2.0 client. + +This is a client for interacting with an OAuth 2.0 authorization server's +token endpoint. + +For more information about the token endpoint, see +`Section 3.1 of rfc6749`_ + +.. _Section 3.1 of rfc6749: https://tools.ietf.org/html/rfc6749#section-3.2 +""" + +import datetime +import http.client as http_client +import json +import urllib + +from google.auth import _exponential_backoff +from google.auth import _helpers +from google.auth import credentials +from google.auth import exceptions +from google.auth import jwt +from google.auth import metrics +from google.auth import transport + +_URLENCODED_CONTENT_TYPE = "application/x-www-form-urlencoded" +_JSON_CONTENT_TYPE = "application/json" +_JWT_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer" +_REFRESH_GRANT_TYPE = "refresh_token" + + +def _handle_error_response(response_data, retryable_error): + """Translates an error response into an exception. + + Args: + response_data (Mapping | str): The decoded response data. + retryable_error Optional[bool]: A boolean indicating if an error is retryable. + Defaults to False. + + Raises: + google.auth.exceptions.RefreshError: The errors contained in response_data. + """ + + retryable_error = retryable_error if retryable_error else False + + if isinstance(response_data, str): + raise exceptions.RefreshError(response_data, retryable=retryable_error) + try: + error_details = "{}: {}".format( + response_data["error"], response_data.get("error_description") + ) + # If no details could be extracted, use the response data. + except (KeyError, ValueError): + error_details = json.dumps(response_data) + + raise exceptions.RefreshError( + error_details, response_data, retryable=retryable_error + ) + + +def _can_retry(status_code, response_data): + """Checks if a request can be retried by inspecting the status code + and response body of the request. + + Args: + status_code (int): The response status code. + response_data (Mapping | str): The decoded response data. + + Returns: + bool: True if the response is retryable. False otherwise. + """ + if status_code in transport.DEFAULT_RETRYABLE_STATUS_CODES: + return True + + try: + # For a failed response, response_body could be a string + error_desc = response_data.get("error_description") or "" + error_code = response_data.get("error") or "" + + if not isinstance(error_code, str) or not isinstance(error_desc, str): + return False + + # Per Oauth 2.0 RFC https://www.rfc-editor.org/rfc/rfc6749.html#section-4.1.2.1 + # This is needed because a redirect will not return a 500 status code. + retryable_error_descriptions = { + "internal_failure", + "server_error", + "temporarily_unavailable", + } + + if any(e in retryable_error_descriptions for e in (error_code, error_desc)): + return True + + except AttributeError: + pass + + return False + + +def _parse_expiry(response_data): + """Parses the expiry field from a response into a datetime. + + Args: + response_data (Mapping): The JSON-parsed response data. + + Returns: + Optional[datetime]: The expiration or ``None`` if no expiration was + specified. + """ + expires_in = response_data.get("expires_in", None) + + if expires_in is not None: + # Some services do not respect the OAUTH2.0 RFC and send expires_in as a + # JSON String. + if isinstance(expires_in, str): + expires_in = int(expires_in) + + return _helpers.utcnow() + datetime.timedelta(seconds=expires_in) + else: + return None + + +def _token_endpoint_request_no_throw( + request, + token_uri, + body, + access_token=None, + use_json=False, + can_retry=True, + headers=None, + **kwargs +): + """Makes a request to the OAuth 2.0 authorization server's token endpoint. + This function doesn't throw on response errors. + + Args: + request (google.auth.transport.Request): A callable used to make + HTTP requests. + token_uri (str): The OAuth 2.0 authorizations server's token endpoint + URI. + body (Mapping[str, str]): The parameters to send in the request body. + access_token (Optional(str)): The access token needed to make the request. + use_json (Optional(bool)): Use urlencoded format or json format for the + content type. The default value is False. + can_retry (bool): Enable or disable request retry behavior. + headers (Optional[Mapping[str, str]]): The headers for the request. + kwargs: Additional arguments passed on to the request method. The + kwargs will be passed to `requests.request` method, see: + https://docs.python-requests.org/en/latest/api/#requests.request. + For example, you can use `cert=("cert_pem_path", "key_pem_path")` + to set up client side SSL certificate, and use + `verify="ca_bundle_path"` to set up the CA certificates for sever + side SSL certificate verification. + + Returns: + Tuple(bool, Mapping[str, str], Optional[bool]): A boolean indicating + if the request is successful, a mapping for the JSON-decoded response + data and in the case of an error a boolean indicating if the error + is retryable. + """ + if use_json: + headers_to_use = {"Content-Type": _JSON_CONTENT_TYPE} + body = json.dumps(body).encode("utf-8") + else: + headers_to_use = {"Content-Type": _URLENCODED_CONTENT_TYPE} + body = urllib.parse.urlencode(body).encode("utf-8") + + if access_token: + headers_to_use["Authorization"] = "Bearer {}".format(access_token) + + if headers: + headers_to_use.update(headers) + + response_data = {} + retryable_error = False + + retries = _exponential_backoff.ExponentialBackoff() + for _ in retries: + response = request( + method="POST", url=token_uri, headers=headers_to_use, body=body, **kwargs + ) + response_body = ( + response.data.decode("utf-8") + if hasattr(response.data, "decode") + else response.data + ) + + try: + # response_body should be a JSON + response_data = json.loads(response_body) + except ValueError: + response_data = response_body + + if response.status == http_client.OK: + return True, response_data, None + + retryable_error = _can_retry( + status_code=response.status, response_data=response_data + ) + + if not can_retry or not retryable_error: + return False, response_data, retryable_error + + return False, response_data, retryable_error + + +def _token_endpoint_request( + request, + token_uri, + body, + access_token=None, + use_json=False, + can_retry=True, + headers=None, + **kwargs +): + """Makes a request to the OAuth 2.0 authorization server's token endpoint. + + Args: + request (google.auth.transport.Request): A callable used to make + HTTP requests. + token_uri (str): The OAuth 2.0 authorizations server's token endpoint + URI. + body (Mapping[str, str]): The parameters to send in the request body. + access_token (Optional(str)): The access token needed to make the request. + use_json (Optional(bool)): Use urlencoded format or json format for the + content type. The default value is False. + can_retry (bool): Enable or disable request retry behavior. + headers (Optional[Mapping[str, str]]): The headers for the request. + kwargs: Additional arguments passed on to the request method. The + kwargs will be passed to `requests.request` method, see: + https://docs.python-requests.org/en/latest/api/#requests.request. + For example, you can use `cert=("cert_pem_path", "key_pem_path")` + to set up client side SSL certificate, and use + `verify="ca_bundle_path"` to set up the CA certificates for sever + side SSL certificate verification. + + Returns: + Mapping[str, str]: The JSON-decoded response data. + + Raises: + google.auth.exceptions.RefreshError: If the token endpoint returned + an error. + """ + + ( + response_status_ok, + response_data, + retryable_error, + ) = _token_endpoint_request_no_throw( + request, + token_uri, + body, + access_token=access_token, + use_json=use_json, + can_retry=can_retry, + headers=headers, + **kwargs + ) + if not response_status_ok: + _handle_error_response(response_data, retryable_error) + return response_data + + +def jwt_grant(request, token_uri, assertion, can_retry=True): + """Implements the JWT Profile for OAuth 2.0 Authorization Grants. + + For more details, see `rfc7523 section 4`_. + + Args: + request (google.auth.transport.Request): A callable used to make + HTTP requests. + token_uri (str): The OAuth 2.0 authorizations server's token endpoint + URI. + assertion (str): The OAuth 2.0 assertion. + can_retry (bool): Enable or disable request retry behavior. + + Returns: + Tuple[str, Optional[datetime], Mapping[str, str]]: The access token, + expiration, and additional data returned by the token endpoint. + + Raises: + google.auth.exceptions.RefreshError: If the token endpoint returned + an error. + + .. _rfc7523 section 4: https://tools.ietf.org/html/rfc7523#section-4 + """ + body = {"assertion": assertion, "grant_type": _JWT_GRANT_TYPE} + + response_data = _token_endpoint_request( + request, + token_uri, + body, + can_retry=can_retry, + headers={ + metrics.API_CLIENT_HEADER: metrics.token_request_access_token_sa_assertion() + }, + ) + + try: + access_token = response_data["access_token"] + except KeyError as caught_exc: + new_exc = exceptions.RefreshError( + "No access token in response.", response_data, retryable=False + ) + raise new_exc from caught_exc + + expiry = _parse_expiry(response_data) + + return access_token, expiry, response_data + + +def call_iam_generate_id_token_endpoint( + request, + iam_id_token_endpoint, + signer_email, + audience, + access_token, + universe_domain=credentials.DEFAULT_UNIVERSE_DOMAIN, +): + """Call iam.generateIdToken endpoint to get ID token. + + Args: + request (google.auth.transport.Request): A callable used to make + HTTP requests. + iam_id_token_endpoint (str): The IAM ID token endpoint to use. + signer_email (str): The signer email used to form the IAM + generateIdToken endpoint. + audience (str): The audience for the ID token. + access_token (str): The access token used to call the IAM endpoint. + universe_domain (str): The universe domain for the request. The + default is ``googleapis.com``. + + Returns: + Tuple[str, datetime]: The ID token and expiration. + """ + body = {"audience": audience, "includeEmail": "true", "useEmailAzp": "true"} + + response_data = _token_endpoint_request( + request, + iam_id_token_endpoint.replace( + credentials.DEFAULT_UNIVERSE_DOMAIN, universe_domain + ).format(signer_email), + body, + access_token=access_token, + use_json=True, + ) + + try: + id_token = response_data["token"] + except KeyError as caught_exc: + new_exc = exceptions.RefreshError( + "No ID token in response.", response_data, retryable=False + ) + raise new_exc from caught_exc + + payload = jwt.decode(id_token, verify=False) + expiry = _helpers.utcfromtimestamp(payload["exp"]) + + return id_token, expiry + + +def id_token_jwt_grant(request, token_uri, assertion, can_retry=True): + """Implements the JWT Profile for OAuth 2.0 Authorization Grants, but + requests an OpenID Connect ID Token instead of an access token. + + This is a variant on the standard JWT Profile that is currently unique + to Google. This was added for the benefit of authenticating to services + that require ID Tokens instead of access tokens or JWT bearer tokens. + + Args: + request (google.auth.transport.Request): A callable used to make + HTTP requests. + token_uri (str): The OAuth 2.0 authorization server's token endpoint + URI. + assertion (str): JWT token signed by a service account. The token's + payload must include a ``target_audience`` claim. + can_retry (bool): Enable or disable request retry behavior. + + Returns: + Tuple[str, Optional[datetime], Mapping[str, str]]: + The (encoded) Open ID Connect ID Token, expiration, and additional + data returned by the endpoint. + + Raises: + google.auth.exceptions.RefreshError: If the token endpoint returned + an error. + """ + body = {"assertion": assertion, "grant_type": _JWT_GRANT_TYPE} + + response_data = _token_endpoint_request( + request, + token_uri, + body, + can_retry=can_retry, + headers={ + metrics.API_CLIENT_HEADER: metrics.token_request_id_token_sa_assertion() + }, + ) + + try: + id_token = response_data["id_token"] + except KeyError as caught_exc: + new_exc = exceptions.RefreshError( + "No ID token in response.", response_data, retryable=False + ) + raise new_exc from caught_exc + + payload = jwt.decode(id_token, verify=False) + expiry = _helpers.utcfromtimestamp(payload["exp"]) + + return id_token, expiry, response_data + + +def _handle_refresh_grant_response(response_data, refresh_token): + """Extract tokens from refresh grant response. + + Args: + response_data (Mapping[str, str]): Refresh grant response data. + refresh_token (str): Current refresh token. + + Returns: + Tuple[str, str, Optional[datetime], Mapping[str, str]]: The access token, + refresh token, expiration, and additional data returned by the token + endpoint. If response_data doesn't have refresh token, then the current + refresh token will be returned. + + Raises: + google.auth.exceptions.RefreshError: If the token endpoint returned + an error. + """ + try: + access_token = response_data["access_token"] + except KeyError as caught_exc: + new_exc = exceptions.RefreshError( + "No access token in response.", response_data, retryable=False + ) + raise new_exc from caught_exc + + refresh_token = response_data.get("refresh_token", refresh_token) + expiry = _parse_expiry(response_data) + + return access_token, refresh_token, expiry, response_data + + +def refresh_grant( + request, + token_uri, + refresh_token, + client_id, + client_secret, + scopes=None, + rapt_token=None, + can_retry=True, +): + """Implements the OAuth 2.0 refresh token grant. + + For more details, see `rfc678 section 6`_. + + Args: + request (google.auth.transport.Request): A callable used to make + HTTP requests. + token_uri (str): The OAuth 2.0 authorizations server's token endpoint + URI. + refresh_token (str): The refresh token to use to get a new access + token. + client_id (str): The OAuth 2.0 application's client ID. + client_secret (str): The Oauth 2.0 appliaction's client secret. + scopes (Optional(Sequence[str])): Scopes to request. If present, all + scopes must be authorized for the refresh token. Useful if refresh + token has a wild card scope (e.g. + 'https://www.googleapis.com/auth/any-api'). + rapt_token (Optional(str)): The reauth Proof Token. + can_retry (bool): Enable or disable request retry behavior. + + Returns: + Tuple[str, str, Optional[datetime], Mapping[str, str]]: The access + token, new or current refresh token, expiration, and additional data + returned by the token endpoint. + + Raises: + google.auth.exceptions.RefreshError: If the token endpoint returned + an error. + + .. _rfc6748 section 6: https://tools.ietf.org/html/rfc6749#section-6 + """ + body = { + "grant_type": _REFRESH_GRANT_TYPE, + "client_id": client_id, + "client_secret": client_secret, + "refresh_token": refresh_token, + } + if scopes: + body["scope"] = " ".join(scopes) + if rapt_token: + body["rapt"] = rapt_token + + response_data = _token_endpoint_request( + request, token_uri, body, can_retry=can_retry + ) + return _handle_refresh_grant_response(response_data, refresh_token) + + +def _lookup_trust_boundary(request, url, headers=None): + """Implements the global lookup of a credential trust boundary. + For the lookup, we send a request to the global lookup endpoint and then + parse the response. Service account credentials, workload identity + pools and workforce pools implementation may have trust boundaries configured. + Args: + request (google.auth.transport.Request): A callable used to make + HTTP requests. + url (str): The trust boundary lookup url. + headers (Optional[Mapping[str, str]]): The headers for the request. + Returns: + Mapping[str,list|str]: A dictionary containing + "locations" as a list of allowed locations as strings and + "encodedLocations" as a hex string. + e.g: + { + "locations": [ + "us-central1", "us-east1", "europe-west1", "asia-east1" + ], + "encodedLocations": "0xA30" + } + If the credential is not set up with explicit trust boundaries, a trust boundary + of "all" will be returned as a default response. + { + "locations": [], + "encodedLocations": "0x0" + } + Raises: + exceptions.RefreshError: If the response status code is not 200. + exceptions.MalformedError: If the response is not in a valid format. + """ + + response_data = _lookup_trust_boundary_request(request, url, headers=headers) + # In case of no-op response, the "locations" list may or may not be present as an empty list. + if "encodedLocations" not in response_data: + raise exceptions.MalformedError( + "Invalid trust boundary info: {}".format(response_data) + ) + return response_data + + +def _lookup_trust_boundary_request(request, url, can_retry=True, headers=None): + """Makes a request to the trust boundary lookup endpoint. + + Args: + request (google.auth.transport.Request): A callable used to make + HTTP requests. + url (str): The trust boundary lookup url. + can_retry (bool): Enable or disable request retry behavior. Defaults to true. + headers (Optional[Mapping[str, str]]): The headers for the request. + + Returns: + Mapping[str, str]: The JSON-decoded response data. + + Raises: + google.auth.exceptions.RefreshError: If the token endpoint returned + an error. + """ + ( + response_status_ok, + response_data, + retryable_error, + ) = _lookup_trust_boundary_request_no_throw(request, url, can_retry, headers) + if not response_status_ok: + _handle_error_response(response_data, retryable_error) + return response_data + + +def _lookup_trust_boundary_request_no_throw(request, url, can_retry=True, headers=None): + """Makes a request to the trust boundary lookup endpoint. This + function doesn't throw on response errors. + + Args: + request (google.auth.transport.Request): A callable used to make + HTTP requests. + url (str): The trust boundary lookup url. + can_retry (bool): Enable or disable request retry behavior. Defaults to true. + headers (Optional[Mapping[str, str]]): The headers for the request. + + Returns: + Tuple(bool, Mapping[str, str], Optional[bool]): A boolean indicating + if the request is successful, a mapping for the JSON-decoded response + data and in the case of an error a boolean indicating if the error + is retryable. + """ + + response_data = {} + retryable_error = False + + retries = _exponential_backoff.ExponentialBackoff() + for _ in retries: + response = request(method="GET", url=url, headers=headers) + response_body = ( + response.data.decode("utf-8") + if hasattr(response.data, "decode") + else response.data + ) + + try: + # response_body should be a JSON + response_data = json.loads(response_body) + except ValueError: + response_data = response_body + + if response.status == http_client.OK: + return True, response_data, None + + retryable_error = _can_retry( + status_code=response.status, response_data=response_data + ) + + if not can_retry or not retryable_error: + return False, response_data, retryable_error + + return False, response_data, retryable_error diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/_client_async.py b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/_client_async.py new file mode 100644 index 0000000000000000000000000000000000000000..a6201fbdcb94f1f7f5a6155b278c64577110ca77 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/_client_async.py @@ -0,0 +1,290 @@ +# Copyright 2020 Google LLC +# +# Licensed 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. + +"""OAuth 2.0 async client. + +This is a client for interacting with an OAuth 2.0 authorization server's +token endpoint. + +For more information about the token endpoint, see +`Section 3.1 of rfc6749`_ + +.. _Section 3.1 of rfc6749: https://tools.ietf.org/html/rfc6749#section-3.2 +""" + +import http.client as http_client +import json +import urllib + +from google.auth import _exponential_backoff +from google.auth import _helpers +from google.auth import exceptions +from google.auth import jwt +from google.oauth2 import _client as client + + +async def _token_endpoint_request_no_throw( + request, token_uri, body, access_token=None, use_json=False, can_retry=True +): + """Makes a request to the OAuth 2.0 authorization server's token endpoint. + This function doesn't throw on response errors. + + Args: + request (google.auth.transport.Request): A callable used to make + HTTP requests. + token_uri (str): The OAuth 2.0 authorizations server's token endpoint + URI. + body (Mapping[str, str]): The parameters to send in the request body. + access_token (Optional(str)): The access token needed to make the request. + use_json (Optional(bool)): Use urlencoded format or json format for the + content type. The default value is False. + can_retry (bool): Enable or disable request retry behavior. + + Returns: + Tuple(bool, Mapping[str, str], Optional[bool]): A boolean indicating + if the request is successful, a mapping for the JSON-decoded response + data and in the case of an error a boolean indicating if the error + is retryable. + """ + if use_json: + headers = {"Content-Type": client._JSON_CONTENT_TYPE} + body = json.dumps(body).encode("utf-8") + else: + headers = {"Content-Type": client._URLENCODED_CONTENT_TYPE} + body = urllib.parse.urlencode(body).encode("utf-8") + + if access_token: + headers["Authorization"] = "Bearer {}".format(access_token) + + response_data = {} + retryable_error = False + + retries = _exponential_backoff.ExponentialBackoff() + for _ in retries: + response = await request( + method="POST", url=token_uri, headers=headers, body=body + ) + + # Using data.read() resulted in zlib decompression errors. This may require future investigation. + response_body1 = await response.content() + + response_body = ( + response_body1.decode("utf-8") + if hasattr(response_body1, "decode") + else response_body1 + ) + + try: + response_data = json.loads(response_body) + except ValueError: + response_data = response_body + + if response.status == http_client.OK: + return True, response_data, None + + retryable_error = client._can_retry( + status_code=response.status, response_data=response_data + ) + + if not can_retry or not retryable_error: + return False, response_data, retryable_error + + return False, response_data, retryable_error + + +async def _token_endpoint_request( + request, token_uri, body, access_token=None, use_json=False, can_retry=True +): + """Makes a request to the OAuth 2.0 authorization server's token endpoint. + + Args: + request (google.auth.transport.Request): A callable used to make + HTTP requests. + token_uri (str): The OAuth 2.0 authorizations server's token endpoint + URI. + body (Mapping[str, str]): The parameters to send in the request body. + access_token (Optional(str)): The access token needed to make the request. + use_json (Optional(bool)): Use urlencoded format or json format for the + content type. The default value is False. + can_retry (bool): Enable or disable request retry behavior. + + Returns: + Mapping[str, str]: The JSON-decoded response data. + + Raises: + google.auth.exceptions.RefreshError: If the token endpoint returned + an error. + """ + + ( + response_status_ok, + response_data, + retryable_error, + ) = await _token_endpoint_request_no_throw( + request, + token_uri, + body, + access_token=access_token, + use_json=use_json, + can_retry=can_retry, + ) + if not response_status_ok: + client._handle_error_response(response_data, retryable_error) + return response_data + + +async def jwt_grant(request, token_uri, assertion, can_retry=True): + """Implements the JWT Profile for OAuth 2.0 Authorization Grants. + + For more details, see `rfc7523 section 4`_. + + Args: + request (google.auth.transport.Request): A callable used to make + HTTP requests. + token_uri (str): The OAuth 2.0 authorizations server's token endpoint + URI. + assertion (str): The OAuth 2.0 assertion. + can_retry (bool): Enable or disable request retry behavior. + + Returns: + Tuple[str, Optional[datetime], Mapping[str, str]]: The access token, + expiration, and additional data returned by the token endpoint. + + Raises: + google.auth.exceptions.RefreshError: If the token endpoint returned + an error. + + .. _rfc7523 section 4: https://tools.ietf.org/html/rfc7523#section-4 + """ + body = {"assertion": assertion, "grant_type": client._JWT_GRANT_TYPE} + + response_data = await _token_endpoint_request( + request, token_uri, body, can_retry=can_retry + ) + + try: + access_token = response_data["access_token"] + except KeyError as caught_exc: + new_exc = exceptions.RefreshError( + "No access token in response.", response_data, retryable=False + ) + raise new_exc from caught_exc + + expiry = client._parse_expiry(response_data) + + return access_token, expiry, response_data + + +async def id_token_jwt_grant(request, token_uri, assertion, can_retry=True): + """Implements the JWT Profile for OAuth 2.0 Authorization Grants, but + requests an OpenID Connect ID Token instead of an access token. + + This is a variant on the standard JWT Profile that is currently unique + to Google. This was added for the benefit of authenticating to services + that require ID Tokens instead of access tokens or JWT bearer tokens. + + Args: + request (google.auth.transport.Request): A callable used to make + HTTP requests. + token_uri (str): The OAuth 2.0 authorization server's token endpoint + URI. + assertion (str): JWT token signed by a service account. The token's + payload must include a ``target_audience`` claim. + can_retry (bool): Enable or disable request retry behavior. + + Returns: + Tuple[str, Optional[datetime], Mapping[str, str]]: + The (encoded) Open ID Connect ID Token, expiration, and additional + data returned by the endpoint. + + Raises: + google.auth.exceptions.RefreshError: If the token endpoint returned + an error. + """ + body = {"assertion": assertion, "grant_type": client._JWT_GRANT_TYPE} + + response_data = await _token_endpoint_request( + request, token_uri, body, can_retry=can_retry + ) + + try: + id_token = response_data["id_token"] + except KeyError as caught_exc: + new_exc = exceptions.RefreshError( + "No ID token in response.", response_data, retryable=False + ) + raise new_exc from caught_exc + + payload = jwt.decode(id_token, verify=False) + expiry = _helpers.utcfromtimestamp(payload["exp"]) + + return id_token, expiry, response_data + + +async def refresh_grant( + request, + token_uri, + refresh_token, + client_id, + client_secret, + scopes=None, + rapt_token=None, + can_retry=True, +): + """Implements the OAuth 2.0 refresh token grant. + + For more details, see `rfc678 section 6`_. + + Args: + request (google.auth.transport.Request): A callable used to make + HTTP requests. + token_uri (str): The OAuth 2.0 authorizations server's token endpoint + URI. + refresh_token (str): The refresh token to use to get a new access + token. + client_id (str): The OAuth 2.0 application's client ID. + client_secret (str): The Oauth 2.0 appliaction's client secret. + scopes (Optional(Sequence[str])): Scopes to request. If present, all + scopes must be authorized for the refresh token. Useful if refresh + token has a wild card scope (e.g. + 'https://www.googleapis.com/auth/any-api'). + rapt_token (Optional(str)): The reauth Proof Token. + can_retry (bool): Enable or disable request retry behavior. + + Returns: + Tuple[str, Optional[str], Optional[datetime], Mapping[str, str]]: The + access token, new or current refresh token, expiration, and additional data + returned by the token endpoint. + + Raises: + google.auth.exceptions.RefreshError: If the token endpoint returned + an error. + + .. _rfc6748 section 6: https://tools.ietf.org/html/rfc6749#section-6 + """ + body = { + "grant_type": client._REFRESH_GRANT_TYPE, + "client_id": client_id, + "client_secret": client_secret, + "refresh_token": refresh_token, + } + if scopes: + body["scope"] = " ".join(scopes) + if rapt_token: + body["rapt"] = rapt_token + + response_data = await _token_endpoint_request( + request, token_uri, body, can_retry=can_retry + ) + return client._handle_refresh_grant_response(response_data, refresh_token) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/_credentials_async.py b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/_credentials_async.py new file mode 100644 index 0000000000000000000000000000000000000000..b5561aae02293b3ab7f3180803b07993331ab149 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/_credentials_async.py @@ -0,0 +1,118 @@ +# Copyright 2020 Google LLC +# +# Licensed 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. + +"""OAuth 2.0 Async Credentials. + +This module provides credentials based on OAuth 2.0 access and refresh tokens. +These credentials usually access resources on behalf of a user (resource +owner). + +Specifically, this is intended to use access tokens acquired using the +`Authorization Code grant`_ and can refresh those tokens using a +optional `refresh token`_. + +Obtaining the initial access and refresh token is outside of the scope of this +module. Consult `rfc6749 section 4.1`_ for complete details on the +Authorization Code grant flow. + +.. _Authorization Code grant: https://tools.ietf.org/html/rfc6749#section-1.3.1 +.. _refresh token: https://tools.ietf.org/html/rfc6749#section-6 +.. _rfc6749 section 4.1: https://tools.ietf.org/html/rfc6749#section-4.1 +""" + +from google.auth import _credentials_async as credentials +from google.auth import _helpers +from google.auth import exceptions +from google.oauth2 import _reauth_async as reauth +from google.oauth2 import credentials as oauth2_credentials + + +class Credentials(oauth2_credentials.Credentials): + """Credentials using OAuth 2.0 access and refresh tokens. + + The credentials are considered immutable. If you want to modify the + quota project, use :meth:`with_quota_project` or :: + + credentials = credentials.with_quota_project('myproject-123) + """ + + @_helpers.copy_docstring(credentials.Credentials) + async def refresh(self, request): + if ( + self._refresh_token is None + or self._token_uri is None + or self._client_id is None + or self._client_secret is None + ): + raise exceptions.RefreshError( + "The credentials do not contain the necessary fields need to " + "refresh the access token. You must specify refresh_token, " + "token_uri, client_id, and client_secret." + ) + + ( + access_token, + refresh_token, + expiry, + grant_response, + rapt_token, + ) = await reauth.refresh_grant( + request, + self._token_uri, + self._refresh_token, + self._client_id, + self._client_secret, + scopes=self._scopes, + rapt_token=self._rapt_token, + enable_reauth_refresh=self._enable_reauth_refresh, + ) + + self.token = access_token + self.expiry = expiry + self._refresh_token = refresh_token + self._id_token = grant_response.get("id_token") + self._rapt_token = rapt_token + + if self._scopes and "scope" in grant_response: + requested_scopes = frozenset(self._scopes) + granted_scopes = frozenset(grant_response["scope"].split()) + scopes_requested_but_not_granted = requested_scopes - granted_scopes + if scopes_requested_but_not_granted: + raise exceptions.RefreshError( + "Not all requested scopes were granted by the " + "authorization server, missing scopes {}.".format( + ", ".join(scopes_requested_but_not_granted) + ) + ) + + @_helpers.copy_docstring(credentials.Credentials) + async def before_request(self, request, method, url, headers): + if not self.valid: + await self.refresh(request) + self.apply(headers) + + +class UserAccessTokenCredentials(oauth2_credentials.UserAccessTokenCredentials): + """Access token credentials for user account. + + Obtain the access token for a given user account or the current active + user account with the ``gcloud auth print-access-token`` command. + + Args: + account (Optional[str]): Account to get the access token for. If not + specified, the current active account will be used. + quota_project_id (Optional[str]): The project ID used for quota + and billing. + + """ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/_id_token_async.py b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/_id_token_async.py new file mode 100644 index 0000000000000000000000000000000000000000..a7f77a1c785b831c92aaaf78fffa22fb73969c0a --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/_id_token_async.py @@ -0,0 +1,287 @@ +# Copyright 2020 Google LLC +# +# Licensed 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. + +"""Google ID Token helpers. + +Provides support for verifying `OpenID Connect ID Tokens`_, especially ones +generated by Google infrastructure. + +To parse and verify an ID Token issued by Google's OAuth 2.0 authorization +server use :func:`verify_oauth2_token`. To verify an ID Token issued by +Firebase, use :func:`verify_firebase_token`. + +A general purpose ID Token verifier is available as :func:`verify_token`. + +Example:: + + from google.oauth2 import _id_token_async + from google.auth.transport import aiohttp_requests + + request = aiohttp_requests.Request() + + id_info = await _id_token_async.verify_oauth2_token( + token, request, 'my-client-id.example.com') + + if id_info['iss'] != 'https://accounts.google.com': + raise ValueError('Wrong issuer.') + + userid = id_info['sub'] + +By default, this will re-fetch certificates for each verification. Because +Google's public keys are only changed infrequently (on the order of once per +day), you may wish to take advantage of caching to reduce latency and the +potential for network errors. This can be accomplished using an external +library like `CacheControl`_ to create a cache-aware +:class:`google.auth.transport.Request`:: + + import cachecontrol + import google.auth.transport.requests + import requests + + session = requests.session() + cached_session = cachecontrol.CacheControl(session) + request = google.auth.transport.requests.Request(session=cached_session) + +.. _OpenID Connect ID Token: + http://openid.net/specs/openid-connect-core-1_0.html#IDToken +.. _CacheControl: https://cachecontrol.readthedocs.io +""" + +import http.client as http_client +import json +import os + +from google.auth import environment_vars +from google.auth import exceptions +from google.auth import jwt +from google.auth.transport import requests +from google.oauth2 import id_token as sync_id_token + + +async def _fetch_certs(request, certs_url): + """Fetches certificates. + + Google-style cerificate endpoints return JSON in the format of + ``{'key id': 'x509 certificate'}``. + + Args: + request (google.auth.transport.Request): The object used to make + HTTP requests. This must be an aiohttp request. + certs_url (str): The certificate endpoint URL. + + Returns: + Mapping[str, str]: A mapping of public key ID to x.509 certificate + data. + """ + response = await request(certs_url, method="GET") + + if response.status != http_client.OK: + raise exceptions.TransportError( + "Could not fetch certificates at {}".format(certs_url) + ) + + data = await response.content() + + return json.loads(data) + + +async def verify_token( + id_token, + request, + audience=None, + certs_url=sync_id_token._GOOGLE_OAUTH2_CERTS_URL, + clock_skew_in_seconds=0, +): + """Verifies an ID token and returns the decoded token. + + Args: + id_token (Union[str, bytes]): The encoded token. + request (google.auth.transport.Request): The object used to make + HTTP requests. This must be an aiohttp request. + audience (str): The audience that this token is intended for. If None + then the audience is not verified. + certs_url (str): The URL that specifies the certificates to use to + verify the token. This URL should return JSON in the format of + ``{'key id': 'x509 certificate'}``. + clock_skew_in_seconds (int): The clock skew used for `iat` and `exp` + validation. + + Returns: + Mapping[str, Any]: The decoded token. + """ + certs = await _fetch_certs(request, certs_url) + + return jwt.decode( + id_token, + certs=certs, + audience=audience, + clock_skew_in_seconds=clock_skew_in_seconds, + ) + + +async def verify_oauth2_token( + id_token, request, audience=None, clock_skew_in_seconds=0 +): + """Verifies an ID Token issued by Google's OAuth 2.0 authorization server. + + Args: + id_token (Union[str, bytes]): The encoded token. + request (google.auth.transport.Request): The object used to make + HTTP requests. This must be an aiohttp request. + audience (str): The audience that this token is intended for. This is + typically your application's OAuth 2.0 client ID. If None then the + audience is not verified. + clock_skew_in_seconds (int): The clock skew used for `iat` and `exp` + validation. + + Returns: + Mapping[str, Any]: The decoded token. + + Raises: + exceptions.GoogleAuthError: If the issuer is invalid. + """ + idinfo = await verify_token( + id_token, + request, + audience=audience, + certs_url=sync_id_token._GOOGLE_OAUTH2_CERTS_URL, + clock_skew_in_seconds=clock_skew_in_seconds, + ) + + if idinfo["iss"] not in sync_id_token._GOOGLE_ISSUERS: + raise exceptions.GoogleAuthError( + "Wrong issuer. 'iss' should be one of the following: {}".format( + sync_id_token._GOOGLE_ISSUERS + ) + ) + + return idinfo + + +async def verify_firebase_token( + id_token, request, audience=None, clock_skew_in_seconds=0 +): + """Verifies an ID Token issued by Firebase Authentication. + + Args: + id_token (Union[str, bytes]): The encoded token. + request (google.auth.transport.Request): The object used to make + HTTP requests. This must be an aiohttp request. + audience (str): The audience that this token is intended for. This is + typically your Firebase application ID. If None then the audience + is not verified. + clock_skew_in_seconds (int): The clock skew used for `iat` and `exp` + validation. + + Returns: + Mapping[str, Any]: The decoded token. + """ + return await verify_token( + id_token, + request, + audience=audience, + certs_url=sync_id_token._GOOGLE_APIS_CERTS_URL, + clock_skew_in_seconds=clock_skew_in_seconds, + ) + + +async def fetch_id_token(request, audience): + """Fetch the ID Token from the current environment. + + This function acquires ID token from the environment in the following order. + See https://google.aip.dev/auth/4110. + + 1. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set + to the path of a valid service account JSON file, then ID token is + acquired using this service account credentials. + 2. If the application is running in Compute Engine, App Engine or Cloud Run, + then the ID token are obtained from the metadata server. + 3. If metadata server doesn't exist and no valid service account credentials + are found, :class:`~google.auth.exceptions.DefaultCredentialsError` will + be raised. + + Example:: + + import google.oauth2._id_token_async + import google.auth.transport.aiohttp_requests + + request = google.auth.transport.aiohttp_requests.Request() + target_audience = "https://pubsub.googleapis.com" + + id_token = await google.oauth2._id_token_async.fetch_id_token(request, target_audience) + + Args: + request (google.auth.transport.aiohttp_requests.Request): A callable used to make + HTTP requests. + audience (str): The audience that this ID token is intended for. + + Returns: + str: The ID token. + + Raises: + ~google.auth.exceptions.DefaultCredentialsError: + If metadata server doesn't exist and no valid service account + credentials are found. + """ + # 1. Try to get credentials from the GOOGLE_APPLICATION_CREDENTIALS environment + # variable. + credentials_filename = os.environ.get(environment_vars.CREDENTIALS) + if credentials_filename: + if not ( + os.path.exists(credentials_filename) + and os.path.isfile(credentials_filename) + ): + raise exceptions.DefaultCredentialsError( + "GOOGLE_APPLICATION_CREDENTIALS path is either not found or invalid." + ) + + try: + with open(credentials_filename, "r") as f: + from google.oauth2 import _service_account_async as service_account + + info = json.load(f) + if info.get("type") == "service_account": + credentials = ( + service_account.IDTokenCredentials.from_service_account_info( + info, target_audience=audience + ) + ) + await credentials.refresh(request) + return credentials.token + except ValueError as caught_exc: + new_exc = exceptions.DefaultCredentialsError( + "GOOGLE_APPLICATION_CREDENTIALS is not valid service account credentials.", + caught_exc, + ) + raise new_exc from caught_exc + + # 2. Try to fetch ID token from metada server if it exists. The code works + # for GAE and Cloud Run metadata server as well. + try: + from google.auth import compute_engine + from google.auth.compute_engine import _metadata + + request_new = requests.Request() + if _metadata.ping(request_new): + credentials = compute_engine.IDTokenCredentials( + request_new, audience, use_metadata_identity_endpoint=True + ) + credentials.refresh(request_new) + return credentials.token + except (ImportError, exceptions.TransportError): + pass + + raise exceptions.DefaultCredentialsError( + "Neither metadata server or valid service account credentials are found." + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/_reauth_async.py b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/_reauth_async.py new file mode 100644 index 0000000000000000000000000000000000000000..eeb8e9fb02739b0b24a9ee4f7c6e311a0fdab239 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/_reauth_async.py @@ -0,0 +1,330 @@ +# Copyright 2021 Google LLC +# +# Licensed 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. + +"""A module that provides functions for handling rapt authentication. + +Reauth is a process of obtaining additional authentication (such as password, +security token, etc.) while refreshing OAuth 2.0 credentials for a user. + +Credentials that use the Reauth flow must have the reauth scope, +``https://www.googleapis.com/auth/accounts.reauth``. + +This module provides a high-level function for executing the Reauth process, +:func:`refresh_grant`, and lower-level helpers for doing the individual +steps of the reauth process. + +Those steps are: + +1. Obtaining a list of challenges from the reauth server. +2. Running through each challenge and sending the result back to the reauth + server. +3. Refreshing the access token using the returned rapt token. +""" + +import sys + +from google.auth import exceptions +from google.oauth2 import _client +from google.oauth2 import _client_async +from google.oauth2 import challenges +from google.oauth2 import reauth + + +async def _get_challenges( + request, supported_challenge_types, access_token, requested_scopes=None +): + """Does initial request to reauth API to get the challenges. + + Args: + request (google.auth.transport.Request): A callable used to make + HTTP requests. This must be an aiohttp request. + supported_challenge_types (Sequence[str]): list of challenge names + supported by the manager. + access_token (str): Access token with reauth scopes. + requested_scopes (Optional(Sequence[str])): Authorized scopes for the credentials. + + Returns: + dict: The response from the reauth API. + """ + body = {"supportedChallengeTypes": supported_challenge_types} + if requested_scopes: + body["oauthScopesForDomainPolicyLookup"] = requested_scopes + + return await _client_async._token_endpoint_request( + request, + reauth._REAUTH_API + ":start", + body, + access_token=access_token, + use_json=True, + ) + + +async def _send_challenge_result( + request, session_id, challenge_id, client_input, access_token +): + """Attempt to refresh access token by sending next challenge result. + + Args: + request (google.auth.transport.Request): A callable used to make + HTTP requests. This must be an aiohttp request. + session_id (str): session id returned by the initial reauth call. + challenge_id (str): challenge id returned by the initial reauth call. + client_input: dict with a challenge-specific client input. For example: + ``{'credential': password}`` for password challenge. + access_token (str): Access token with reauth scopes. + + Returns: + dict: The response from the reauth API. + """ + body = { + "sessionId": session_id, + "challengeId": challenge_id, + "action": "RESPOND", + "proposalResponse": client_input, + } + + return await _client_async._token_endpoint_request( + request, + reauth._REAUTH_API + "/{}:continue".format(session_id), + body, + access_token=access_token, + use_json=True, + ) + + +async def _run_next_challenge(msg, request, access_token): + """Get the next challenge from msg and run it. + + Args: + msg (dict): Reauth API response body (either from the initial request to + https://reauth.googleapis.com/v2/sessions:start or from sending the + previous challenge response to + https://reauth.googleapis.com/v2/sessions/id:continue) + request (google.auth.transport.Request): A callable used to make + HTTP requests. This must be an aiohttp request. + access_token (str): reauth access token + + Returns: + dict: The response from the reauth API. + + Raises: + google.auth.exceptions.ReauthError: if reauth failed. + """ + for challenge in msg["challenges"]: + if challenge["status"] != "READY": + # Skip non-activated challenges. + continue + c = challenges.AVAILABLE_CHALLENGES.get(challenge["challengeType"], None) + if not c: + raise exceptions.ReauthFailError( + "Unsupported challenge type {0}. Supported types: {1}".format( + challenge["challengeType"], + ",".join(list(challenges.AVAILABLE_CHALLENGES.keys())), + ) + ) + if not c.is_locally_eligible: + raise exceptions.ReauthFailError( + "Challenge {0} is not locally eligible".format( + challenge["challengeType"] + ) + ) + client_input = c.obtain_challenge_input(challenge) + if not client_input: + return None + return await _send_challenge_result( + request, + msg["sessionId"], + challenge["challengeId"], + client_input, + access_token, + ) + return None + + +async def _obtain_rapt(request, access_token, requested_scopes): + """Given an http request method and reauth access token, get rapt token. + + Args: + request (google.auth.transport.Request): A callable used to make + HTTP requests. This must be an aiohttp request. + access_token (str): reauth access token + requested_scopes (Sequence[str]): scopes required by the client application + + Returns: + str: The rapt token. + + Raises: + google.auth.exceptions.ReauthError: if reauth failed + """ + msg = await _get_challenges( + request, + list(challenges.AVAILABLE_CHALLENGES.keys()), + access_token, + requested_scopes, + ) + + if msg["status"] == reauth._AUTHENTICATED: + return msg["encodedProofOfReauthToken"] + + for _ in range(0, reauth.RUN_CHALLENGE_RETRY_LIMIT): + if not ( + msg["status"] == reauth._CHALLENGE_REQUIRED + or msg["status"] == reauth._CHALLENGE_PENDING + ): + raise exceptions.ReauthFailError( + "Reauthentication challenge failed due to API error: {}".format( + msg["status"] + ) + ) + + if not reauth.is_interactive(): + raise exceptions.ReauthFailError( + "Reauthentication challenge could not be answered because you are not" + " in an interactive session." + ) + + msg = await _run_next_challenge(msg, request, access_token) + + if msg["status"] == reauth._AUTHENTICATED: + return msg["encodedProofOfReauthToken"] + + # If we got here it means we didn't get authenticated. + raise exceptions.ReauthFailError("Failed to obtain rapt token.") + + +async def get_rapt_token( + request, client_id, client_secret, refresh_token, token_uri, scopes=None +): + """Given an http request method and refresh_token, get rapt token. + + Args: + request (google.auth.transport.Request): A callable used to make + HTTP requests. This must be an aiohttp request. + client_id (str): client id to get access token for reauth scope. + client_secret (str): client secret for the client_id + refresh_token (str): refresh token to refresh access token + token_uri (str): uri to refresh access token + scopes (Optional(Sequence[str])): scopes required by the client application + + Returns: + str: The rapt token. + Raises: + google.auth.exceptions.RefreshError: If reauth failed. + """ + sys.stderr.write("Reauthentication required.\n") + + # Get access token for reauth. + access_token, _, _, _ = await _client_async.refresh_grant( + request=request, + client_id=client_id, + client_secret=client_secret, + refresh_token=refresh_token, + token_uri=token_uri, + scopes=[reauth._REAUTH_SCOPE], + ) + + # Get rapt token from reauth API. + rapt_token = await _obtain_rapt(request, access_token, requested_scopes=scopes) + + return rapt_token + + +async def refresh_grant( + request, + token_uri, + refresh_token, + client_id, + client_secret, + scopes=None, + rapt_token=None, + enable_reauth_refresh=False, +): + """Implements the reauthentication flow. + + Args: + request (google.auth.transport.Request): A callable used to make + HTTP requests. This must be an aiohttp request. + token_uri (str): The OAuth 2.0 authorizations server's token endpoint + URI. + refresh_token (str): The refresh token to use to get a new access + token. + client_id (str): The OAuth 2.0 application's client ID. + client_secret (str): The Oauth 2.0 appliaction's client secret. + scopes (Optional(Sequence[str])): Scopes to request. If present, all + scopes must be authorized for the refresh token. Useful if refresh + token has a wild card scope (e.g. + 'https://www.googleapis.com/auth/any-api'). + rapt_token (Optional(str)): The rapt token for reauth. + enable_reauth_refresh (Optional[bool]): Whether reauth refresh flow + should be used. The default value is False. This option is for + gcloud only, other users should use the default value. + + Returns: + Tuple[str, Optional[str], Optional[datetime], Mapping[str, str], str]: The + access token, new refresh token, expiration, the additional data + returned by the token endpoint, and the rapt token. + + Raises: + google.auth.exceptions.RefreshError: If the token endpoint returned + an error. + """ + body = { + "grant_type": _client._REFRESH_GRANT_TYPE, + "client_id": client_id, + "client_secret": client_secret, + "refresh_token": refresh_token, + } + if scopes: + body["scope"] = " ".join(scopes) + if rapt_token: + body["rapt"] = rapt_token + + ( + response_status_ok, + response_data, + retryable_error, + ) = await _client_async._token_endpoint_request_no_throw(request, token_uri, body) + if ( + not response_status_ok + and response_data.get("error") == reauth._REAUTH_NEEDED_ERROR + and ( + response_data.get("error_subtype") + == reauth._REAUTH_NEEDED_ERROR_INVALID_RAPT + or response_data.get("error_subtype") + == reauth._REAUTH_NEEDED_ERROR_RAPT_REQUIRED + ) + ): + if not enable_reauth_refresh: + raise exceptions.RefreshError( + "Reauthentication is needed. Please run `gcloud auth application-default login` to reauthenticate." + ) + + rapt_token = await get_rapt_token( + request, client_id, client_secret, refresh_token, token_uri, scopes=scopes + ) + body["rapt"] = rapt_token + ( + response_status_ok, + response_data, + retryable_error, + ) = await _client_async._token_endpoint_request_no_throw( + request, token_uri, body + ) + + if not response_status_ok: + _client._handle_error_response(response_data, retryable_error) + refresh_response = _client._handle_refresh_grant_response( + response_data, refresh_token + ) + return refresh_response + (rapt_token,) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/_service_account_async.py b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/_service_account_async.py new file mode 100644 index 0000000000000000000000000000000000000000..cfd315a7ff1f5ece44f808945c47bc929ad07c9e --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/_service_account_async.py @@ -0,0 +1,132 @@ +# Copyright 2020 Google LLC +# +# Licensed 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. + +"""Service Accounts: JSON Web Token (JWT) Profile for OAuth 2.0 + +NOTE: This file adds asynchronous refresh methods to both credentials +classes, and therefore async/await syntax is required when calling this +method when using service account credentials with asynchronous functionality. +Otherwise, all other methods are inherited from the regular service account +credentials file google.oauth2.service_account + +""" + +from google.auth import _credentials_async as credentials_async +from google.auth import _helpers +from google.oauth2 import _client_async +from google.oauth2 import service_account + + +class Credentials( + service_account.Credentials, credentials_async.Scoped, credentials_async.Credentials +): + """Service account credentials + + Usually, you'll create these credentials with one of the helper + constructors. To create credentials using a Google service account + private key JSON file:: + + credentials = _service_account_async.Credentials.from_service_account_file( + 'service-account.json') + + Or if you already have the service account file loaded:: + + service_account_info = json.load(open('service_account.json')) + credentials = _service_account_async.Credentials.from_service_account_info( + service_account_info) + + Both helper methods pass on arguments to the constructor, so you can + specify additional scopes and a subject if necessary:: + + credentials = _service_account_async.Credentials.from_service_account_file( + 'service-account.json', + scopes=['email'], + subject='user@example.com') + + The credentials are considered immutable. If you want to modify the scopes + or the subject used for delegation, use :meth:`with_scopes` or + :meth:`with_subject`:: + + scoped_credentials = credentials.with_scopes(['email']) + delegated_credentials = credentials.with_subject(subject) + + To add a quota project, use :meth:`with_quota_project`:: + + credentials = credentials.with_quota_project('myproject-123') + """ + + @_helpers.copy_docstring(credentials_async.Credentials) + async def refresh(self, request): + assertion = self._make_authorization_grant_assertion() + access_token, expiry, _ = await _client_async.jwt_grant( + request, self._token_uri, assertion + ) + self.token = access_token + self.expiry = expiry + + +class IDTokenCredentials( + service_account.IDTokenCredentials, + credentials_async.Signing, + credentials_async.Credentials, +): + """Open ID Connect ID Token-based service account credentials. + + These credentials are largely similar to :class:`.Credentials`, but instead + of using an OAuth 2.0 Access Token as the bearer token, they use an Open + ID Connect ID Token as the bearer token. These credentials are useful when + communicating to services that require ID Tokens and can not accept access + tokens. + + Usually, you'll create these credentials with one of the helper + constructors. To create credentials using a Google service account + private key JSON file:: + + credentials = ( + _service_account_async.IDTokenCredentials.from_service_account_file( + 'service-account.json')) + + Or if you already have the service account file loaded:: + + service_account_info = json.load(open('service_account.json')) + credentials = ( + _service_account_async.IDTokenCredentials.from_service_account_info( + service_account_info)) + + Both helper methods pass on arguments to the constructor, so you can + specify additional scopes and a subject if necessary:: + + credentials = ( + _service_account_async.IDTokenCredentials.from_service_account_file( + 'service-account.json', + scopes=['email'], + subject='user@example.com')) + + The credentials are considered immutable. If you want to modify the scopes + or the subject used for delegation, use :meth:`with_scopes` or + :meth:`with_subject`:: + + scoped_credentials = credentials.with_scopes(['email']) + delegated_credentials = credentials.with_subject(subject) + + """ + + @_helpers.copy_docstring(credentials_async.Credentials) + async def refresh(self, request): + assertion = self._make_authorization_grant_assertion() + access_token, expiry, _ = await _client_async.id_token_jwt_grant( + request, self._token_uri, assertion + ) + self.token = access_token + self.expiry = expiry diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/challenges.py b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/challenges.py new file mode 100644 index 0000000000000000000000000000000000000000..59a2f9be4f43b1db5685f49bea265361c72cb532 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/challenges.py @@ -0,0 +1,281 @@ +# Copyright 2021 Google LLC +# +# Licensed 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. + +""" Challenges for reauthentication. +""" + +import abc +import base64 +import getpass +import sys + +from google.auth import _helpers +from google.auth import exceptions +from google.oauth2 import webauthn_handler_factory +from google.oauth2.webauthn_types import ( + AuthenticationExtensionsClientInputs, + GetRequest, + PublicKeyCredentialDescriptor, +) + + +REAUTH_ORIGIN = "https://accounts.google.com" +SAML_CHALLENGE_MESSAGE = ( + "Please run `gcloud auth login` to complete reauthentication with SAML." +) +WEBAUTHN_TIMEOUT_MS = 120000 # Two minute timeout + + +def get_user_password(text): + """Get password from user. + + Override this function with a different logic if you are using this library + outside a CLI. + + Args: + text (str): message for the password prompt. + + Returns: + str: password string. + """ + return getpass.getpass(text) + + +class ReauthChallenge(metaclass=abc.ABCMeta): + """Base class for reauth challenges.""" + + @property + @abc.abstractmethod + def name(self): # pragma: NO COVER + """Returns the name of the challenge.""" + raise NotImplementedError("name property must be implemented") + + @property + @abc.abstractmethod + def is_locally_eligible(self): # pragma: NO COVER + """Returns true if a challenge is supported locally on this machine.""" + raise NotImplementedError("is_locally_eligible property must be implemented") + + @abc.abstractmethod + def obtain_challenge_input(self, metadata): # pragma: NO COVER + """Performs logic required to obtain credentials and returns it. + + Args: + metadata (Mapping): challenge metadata returned in the 'challenges' field in + the initial reauth request. Includes the 'challengeType' field + and other challenge-specific fields. + + Returns: + response that will be send to the reauth service as the content of + the 'proposalResponse' field in the request body. Usually a dict + with the keys specific to the challenge. For example, + ``{'credential': password}`` for password challenge. + """ + raise NotImplementedError("obtain_challenge_input method must be implemented") + + +class PasswordChallenge(ReauthChallenge): + """Challenge that asks for user's password.""" + + @property + def name(self): + return "PASSWORD" + + @property + def is_locally_eligible(self): + return True + + @_helpers.copy_docstring(ReauthChallenge) + def obtain_challenge_input(self, unused_metadata): + passwd = get_user_password("Please enter your password:") + if not passwd: + passwd = " " # avoid the server crashing in case of no password :D + return {"credential": passwd} + + +class SecurityKeyChallenge(ReauthChallenge): + """Challenge that asks for user's security key touch.""" + + @property + def name(self): + return "SECURITY_KEY" + + @property + def is_locally_eligible(self): + return True + + @_helpers.copy_docstring(ReauthChallenge) + def obtain_challenge_input(self, metadata): + # Check if there is an available Webauthn Handler, if not use pyu2f + try: + factory = webauthn_handler_factory.WebauthnHandlerFactory() + webauthn_handler = factory.get_handler() + if webauthn_handler is not None: + sys.stderr.write("Please insert and touch your security key\n") + return self._obtain_challenge_input_webauthn(metadata, webauthn_handler) + except Exception: + # Attempt pyu2f if exception in webauthn flow + pass + + try: + import pyu2f.convenience.authenticator # type: ignore + import pyu2f.errors # type: ignore + import pyu2f.model # type: ignore + except ImportError: + raise exceptions.ReauthFailError( + "pyu2f dependency is required to use Security key reauth feature. " + "It can be installed via `pip install pyu2f` or `pip install google-auth[reauth]`." + ) + sk = metadata["securityKey"] + challenges = sk["challenges"] + # Read both 'applicationId' and 'relyingPartyId', if they are the same, use + # applicationId, if they are different, use relyingPartyId first and retry + # with applicationId + application_id = sk["applicationId"] + relying_party_id = sk["relyingPartyId"] + + if application_id != relying_party_id: + application_parameters = [relying_party_id, application_id] + else: + application_parameters = [application_id] + + challenge_data = [] + for c in challenges: + kh = c["keyHandle"].encode("ascii") + key = pyu2f.model.RegisteredKey(bytearray(base64.urlsafe_b64decode(kh))) + challenge = c["challenge"].encode("ascii") + challenge = base64.urlsafe_b64decode(challenge) + challenge_data.append({"key": key, "challenge": challenge}) + + # Track number of tries to suppress error message until all application_parameters + # are tried. + tries = 0 + for app_id in application_parameters: + try: + tries += 1 + api = pyu2f.convenience.authenticator.CreateCompositeAuthenticator( + REAUTH_ORIGIN + ) + response = api.Authenticate( + app_id, challenge_data, print_callback=sys.stderr.write + ) + return {"securityKey": response} + except pyu2f.errors.U2FError as e: + if e.code == pyu2f.errors.U2FError.DEVICE_INELIGIBLE: + # Only show error if all app_ids have been tried + if tries == len(application_parameters): + sys.stderr.write("Ineligible security key.\n") + return None + continue + if e.code == pyu2f.errors.U2FError.TIMEOUT: + sys.stderr.write( + "Timed out while waiting for security key touch.\n" + ) + else: + raise e + except pyu2f.errors.PluginError as e: + sys.stderr.write("Plugin error: {}.\n".format(e)) + continue + except pyu2f.errors.NoDeviceFoundError: + sys.stderr.write("No security key found.\n") + return None + + def _obtain_challenge_input_webauthn(self, metadata, webauthn_handler): + sk = metadata.get("securityKey") + if sk is None: + raise exceptions.InvalidValue("securityKey is None") + challenges = sk.get("challenges") + application_id = sk.get("applicationId") + relying_party_id = sk.get("relyingPartyId") + if challenges is None or len(challenges) < 1: + raise exceptions.InvalidValue("challenges is None or empty") + if application_id is None: + raise exceptions.InvalidValue("application_id is None") + if relying_party_id is None: + raise exceptions.InvalidValue("relying_party_id is None") + + allow_credentials = [] + for challenge in challenges: + kh = challenge.get("keyHandle") + if kh is None: + raise exceptions.InvalidValue("keyHandle is None") + key_handle = self._unpadded_urlsafe_b64recode(kh) + allow_credentials.append(PublicKeyCredentialDescriptor(id=key_handle)) + + extension = AuthenticationExtensionsClientInputs(appid=application_id) + + challenge = challenges[0].get("challenge") + if challenge is None: + raise exceptions.InvalidValue("challenge is None") + + get_request = GetRequest( + origin=REAUTH_ORIGIN, + rpid=relying_party_id, + challenge=self._unpadded_urlsafe_b64recode(challenge), + timeout_ms=WEBAUTHN_TIMEOUT_MS, + allow_credentials=allow_credentials, + user_verification="preferred", + extensions=extension, + ) + + try: + get_response = webauthn_handler.get(get_request) + except Exception as e: + sys.stderr.write("Webauthn Error: {}.\n".format(e)) + raise e + + response = { + "clientData": get_response.response.client_data_json, + "authenticatorData": get_response.response.authenticator_data, + "signatureData": get_response.response.signature, + "applicationId": application_id, + "keyHandle": get_response.id, + "securityKeyReplyType": 2, + } + return {"securityKey": response} + + def _unpadded_urlsafe_b64recode(self, s): + """Converts standard b64 encoded string to url safe b64 encoded string + with no padding.""" + b = base64.urlsafe_b64decode(s) + return base64.urlsafe_b64encode(b).decode().rstrip("=") + + +class SamlChallenge(ReauthChallenge): + """Challenge that asks the users to browse to their ID Providers. + + Currently SAML challenge is not supported. When obtaining the challenge + input, exception will be raised to instruct the users to run + `gcloud auth login` for reauthentication. + """ + + @property + def name(self): + return "SAML" + + @property + def is_locally_eligible(self): + return True + + def obtain_challenge_input(self, metadata): + # Magic Arch has not fully supported returning a proper dedirect URL + # for programmatic SAML users today. So we error our here and request + # users to use gcloud to complete a login. + raise exceptions.ReauthSamlChallengeFailError(SAML_CHALLENGE_MESSAGE) + + +AVAILABLE_CHALLENGES = { + challenge.name: challenge + for challenge in [SecurityKeyChallenge(), PasswordChallenge(), SamlChallenge()] +} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/credentials.py b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/credentials.py new file mode 100644 index 0000000000000000000000000000000000000000..ae60223b455ea8ab53090491b2ff633612e0c562 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/credentials.py @@ -0,0 +1,617 @@ +# Copyright 2016 Google LLC +# +# Licensed 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. + +"""OAuth 2.0 Credentials. + +This module provides credentials based on OAuth 2.0 access and refresh tokens. +These credentials usually access resources on behalf of a user (resource +owner). + +Specifically, this is intended to use access tokens acquired using the +`Authorization Code grant`_ and can refresh those tokens using a +optional `refresh token`_. + +Obtaining the initial access and refresh token is outside of the scope of this +module. Consult `rfc6749 section 4.1`_ for complete details on the +Authorization Code grant flow. + +.. _Authorization Code grant: https://tools.ietf.org/html/rfc6749#section-1.3.1 +.. _refresh token: https://tools.ietf.org/html/rfc6749#section-6 +.. _rfc6749 section 4.1: https://tools.ietf.org/html/rfc6749#section-4.1 +""" + +from datetime import datetime +import io +import json +import logging +import warnings + +from google.auth import _cloud_sdk +from google.auth import _helpers +from google.auth import credentials +from google.auth import exceptions +from google.auth import metrics +from google.oauth2 import reauth + +_LOGGER = logging.getLogger(__name__) + + +# The Google OAuth 2.0 token endpoint. Used for authorized user credentials. +_GOOGLE_OAUTH2_TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token" + +# The Google OAuth 2.0 token info endpoint. Used for getting token info JSON from access tokens. +_GOOGLE_OAUTH2_TOKEN_INFO_ENDPOINT = "https://oauth2.googleapis.com/tokeninfo" + + +class Credentials(credentials.ReadOnlyScoped, credentials.CredentialsWithQuotaProject): + """Credentials using OAuth 2.0 access and refresh tokens. + + The credentials are considered immutable except the tokens and the token + expiry, which are updated after refresh. If you want to modify the quota + project, use :meth:`with_quota_project` or :: + + credentials = credentials.with_quota_project('myproject-123') + + Reauth is disabled by default. To enable reauth, set the + `enable_reauth_refresh` parameter to True in the constructor. Note that + reauth feature is intended for gcloud to use only. + If reauth is enabled, `pyu2f` dependency has to be installed in order to use security + key reauth feature. Dependency can be installed via `pip install pyu2f` or `pip install + google-auth[reauth]`. + """ + + def __init__( + self, + token, + refresh_token=None, + id_token=None, + token_uri=None, + client_id=None, + client_secret=None, + scopes=None, + default_scopes=None, + quota_project_id=None, + expiry=None, + rapt_token=None, + refresh_handler=None, + enable_reauth_refresh=False, + granted_scopes=None, + trust_boundary=None, + universe_domain=credentials.DEFAULT_UNIVERSE_DOMAIN, + account=None, + ): + """ + Args: + token (Optional(str)): The OAuth 2.0 access token. Can be None + if refresh information is provided. + refresh_token (str): The OAuth 2.0 refresh token. If specified, + credentials can be refreshed. + id_token (str): The Open ID Connect ID Token. + token_uri (str): The OAuth 2.0 authorization server's token + endpoint URI. Must be specified for refresh, can be left as + None if the token can not be refreshed. + client_id (str): The OAuth 2.0 client ID. Must be specified for + refresh, can be left as None if the token can not be refreshed. + client_secret(str): The OAuth 2.0 client secret. Must be specified + for refresh, can be left as None if the token can not be + refreshed. + scopes (Sequence[str]): The scopes used to obtain authorization. + This parameter is used by :meth:`has_scopes`. OAuth 2.0 + credentials can not request additional scopes after + authorization. The scopes must be derivable from the refresh + token if refresh information is provided (e.g. The refresh + token scopes are a superset of this or contain a wild card + scope like 'https://www.googleapis.com/auth/any-api'). + default_scopes (Sequence[str]): Default scopes passed by a + Google client library. Use 'scopes' for user-defined scopes. + quota_project_id (Optional[str]): The project ID used for quota and billing. + This project may be different from the project used to + create the credentials. + rapt_token (Optional[str]): The reauth Proof Token. + refresh_handler (Optional[Callable[[google.auth.transport.Request, Sequence[str]], [str, datetime]]]): + A callable which takes in the HTTP request callable and the list of + OAuth scopes and when called returns an access token string for the + requested scopes and its expiry datetime. This is useful when no + refresh tokens are provided and tokens are obtained by calling + some external process on demand. It is particularly useful for + retrieving downscoped tokens from a token broker. + enable_reauth_refresh (Optional[bool]): Whether reauth refresh flow + should be used. This flag is for gcloud to use only. + granted_scopes (Optional[Sequence[str]]): The scopes that were consented/granted by the user. + This could be different from the requested scopes and it could be empty if granted + and requested scopes were same. + trust_boundary (str): String representation of trust boundary meta. + universe_domain (Optional[str]): The universe domain. The default + universe domain is googleapis.com. + account (Optional[str]): The account associated with the credential. + """ + super(Credentials, self).__init__() + self.token = token + self.expiry = expiry + self._refresh_token = refresh_token + self._id_token = id_token + if scopes is not None and isinstance(scopes, set): + self._scopes = list(scopes) + else: + self._scopes = scopes + self._default_scopes = default_scopes + self._granted_scopes = granted_scopes + self._token_uri = token_uri + self._client_id = client_id + self._client_secret = client_secret + self._quota_project_id = quota_project_id + self._rapt_token = rapt_token + self.refresh_handler = refresh_handler + self._enable_reauth_refresh = enable_reauth_refresh + self._trust_boundary = trust_boundary + self._universe_domain = universe_domain or credentials.DEFAULT_UNIVERSE_DOMAIN + self._account = account or "" + self._cred_file_path = None + + def __getstate__(self): + """A __getstate__ method must exist for the __setstate__ to be called + This is identical to the default implementation. + See https://docs.python.org/3.7/library/pickle.html#object.__setstate__ + """ + state_dict = self.__dict__.copy() + # Remove _refresh_handler function as there are limitations pickling and + # unpickling certain callables (lambda, functools.partial instances) + # because they need to be importable. + # Instead, the refresh_handler setter should be used to repopulate this. + if "_refresh_handler" in state_dict: + del state_dict["_refresh_handler"] + + if "_refresh_worker" in state_dict: + del state_dict["_refresh_worker"] + return state_dict + + def __setstate__(self, d): + """Credentials pickled with older versions of the class do not have + all the attributes.""" + self.token = d.get("token") + self.expiry = d.get("expiry") + self._refresh_token = d.get("_refresh_token") + self._id_token = d.get("_id_token") + self._scopes = d.get("_scopes") + self._default_scopes = d.get("_default_scopes") + self._granted_scopes = d.get("_granted_scopes") + self._token_uri = d.get("_token_uri") + self._client_id = d.get("_client_id") + self._client_secret = d.get("_client_secret") + self._quota_project_id = d.get("_quota_project_id") + self._rapt_token = d.get("_rapt_token") + self._enable_reauth_refresh = d.get("_enable_reauth_refresh") + self._trust_boundary = d.get("_trust_boundary") + self._universe_domain = ( + d.get("_universe_domain") or credentials.DEFAULT_UNIVERSE_DOMAIN + ) + self._cred_file_path = d.get("_cred_file_path") + # The refresh_handler setter should be used to repopulate this. + self._refresh_handler = None + self._refresh_worker = None + self._use_non_blocking_refresh = d.get("_use_non_blocking_refresh", False) + self._account = d.get("_account", "") + + @property + def refresh_token(self): + """Optional[str]: The OAuth 2.0 refresh token.""" + return self._refresh_token + + @property + def scopes(self): + """Optional[Sequence[str]]: The OAuth 2.0 permission scopes.""" + return self._scopes + + @property + def granted_scopes(self): + """Optional[Sequence[str]]: The OAuth 2.0 permission scopes that were granted by the user.""" + return self._granted_scopes + + @property + def token_uri(self): + """Optional[str]: The OAuth 2.0 authorization server's token endpoint + URI.""" + return self._token_uri + + @property + def id_token(self): + """Optional[str]: The Open ID Connect ID Token. + + Depending on the authorization server and the scopes requested, this + may be populated when credentials are obtained and updated when + :meth:`refresh` is called. This token is a JWT. It can be verified + and decoded using :func:`google.oauth2.id_token.verify_oauth2_token`. + """ + return self._id_token + + @property + def client_id(self): + """Optional[str]: The OAuth 2.0 client ID.""" + return self._client_id + + @property + def client_secret(self): + """Optional[str]: The OAuth 2.0 client secret.""" + return self._client_secret + + @property + def requires_scopes(self): + """False: OAuth 2.0 credentials have their scopes set when + the initial token is requested and can not be changed.""" + return False + + @property + def rapt_token(self): + """Optional[str]: The reauth Proof Token.""" + return self._rapt_token + + @property + def refresh_handler(self): + """Returns the refresh handler if available. + + Returns: + Optional[Callable[[google.auth.transport.Request, Sequence[str]], [str, datetime]]]: + The current refresh handler. + """ + return self._refresh_handler + + @refresh_handler.setter + def refresh_handler(self, value): + """Updates the current refresh handler. + + Args: + value (Optional[Callable[[google.auth.transport.Request, Sequence[str]], [str, datetime]]]): + The updated value of the refresh handler. + + Raises: + TypeError: If the value is not a callable or None. + """ + if not callable(value) and value is not None: + raise TypeError("The provided refresh_handler is not a callable or None.") + self._refresh_handler = value + + @property + def account(self): + """str: The user account associated with the credential. If the account is unknown an empty string is returned.""" + return self._account + + def _make_copy(self): + cred = self.__class__( + self.token, + refresh_token=self.refresh_token, + id_token=self.id_token, + token_uri=self.token_uri, + client_id=self.client_id, + client_secret=self.client_secret, + scopes=self.scopes, + default_scopes=self.default_scopes, + granted_scopes=self.granted_scopes, + quota_project_id=self.quota_project_id, + rapt_token=self.rapt_token, + enable_reauth_refresh=self._enable_reauth_refresh, + trust_boundary=self._trust_boundary, + universe_domain=self._universe_domain, + account=self._account, + ) + cred._cred_file_path = self._cred_file_path + return cred + + @_helpers.copy_docstring(credentials.Credentials) + def get_cred_info(self): + if self._cred_file_path: + cred_info = { + "credential_source": self._cred_file_path, + "credential_type": "user credentials", + } + if self.account: + cred_info["principal"] = self.account + return cred_info + return None + + @_helpers.copy_docstring(credentials.CredentialsWithQuotaProject) + def with_quota_project(self, quota_project_id): + cred = self._make_copy() + cred._quota_project_id = quota_project_id + return cred + + @_helpers.copy_docstring(credentials.CredentialsWithTokenUri) + def with_token_uri(self, token_uri): + cred = self._make_copy() + cred._token_uri = token_uri + return cred + + def with_account(self, account): + """Returns a copy of these credentials with a modified account. + + Args: + account (str): The account to set + + Returns: + google.oauth2.credentials.Credentials: A new credentials instance. + """ + cred = self._make_copy() + cred._account = account + return cred + + @_helpers.copy_docstring(credentials.CredentialsWithUniverseDomain) + def with_universe_domain(self, universe_domain): + cred = self._make_copy() + cred._universe_domain = universe_domain + return cred + + def _metric_header_for_usage(self): + return metrics.CRED_TYPE_USER + + @_helpers.copy_docstring(credentials.Credentials) + def refresh(self, request): + if self._universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN: + raise exceptions.RefreshError( + "User credential refresh is only supported in the default " + "googleapis.com universe domain, but the current universe " + "domain is {}. If you created the credential with an access " + "token, it's likely that the provided token is expired now, " + "please update your code with a valid token.".format( + self._universe_domain + ) + ) + + scopes = self._scopes if self._scopes is not None else self._default_scopes + # Use refresh handler if available and no refresh token is + # available. This is useful in general when tokens are obtained by calling + # some external process on demand. It is particularly useful for retrieving + # downscoped tokens from a token broker. + if self._refresh_token is None and self.refresh_handler: + token, expiry = self.refresh_handler(request, scopes=scopes) + # Validate returned data. + if not isinstance(token, str): + raise exceptions.RefreshError( + "The refresh_handler returned token is not a string." + ) + if not isinstance(expiry, datetime): + raise exceptions.RefreshError( + "The refresh_handler returned expiry is not a datetime object." + ) + if _helpers.utcnow() >= expiry - _helpers.REFRESH_THRESHOLD: + raise exceptions.RefreshError( + "The credentials returned by the refresh_handler are " + "already expired." + ) + self.token = token + self.expiry = expiry + return + + if ( + self._refresh_token is None + or self._token_uri is None + or self._client_id is None + or self._client_secret is None + ): + raise exceptions.RefreshError( + "The credentials do not contain the necessary fields need to " + "refresh the access token. You must specify refresh_token, " + "token_uri, client_id, and client_secret." + ) + + ( + access_token, + refresh_token, + expiry, + grant_response, + rapt_token, + ) = reauth.refresh_grant( + request, + self._token_uri, + self._refresh_token, + self._client_id, + self._client_secret, + scopes=scopes, + rapt_token=self._rapt_token, + enable_reauth_refresh=self._enable_reauth_refresh, + ) + + self.token = access_token + self.expiry = expiry + self._refresh_token = refresh_token + self._id_token = grant_response.get("id_token") + self._rapt_token = rapt_token + + if scopes and "scope" in grant_response: + requested_scopes = frozenset(scopes) + self._granted_scopes = grant_response["scope"].split() + granted_scopes = frozenset(self._granted_scopes) + scopes_requested_but_not_granted = requested_scopes - granted_scopes + if scopes_requested_but_not_granted: + # User might be presented with unbundled scopes at the time of + # consent. So it is a valid scenario to not have all the requested + # scopes as part of granted scopes but log a warning in case the + # developer wants to debug the scenario. + _LOGGER.warning( + "Not all requested scopes were granted by the " + "authorization server, missing scopes {}.".format( + ", ".join(scopes_requested_but_not_granted) + ) + ) + + @classmethod + def from_authorized_user_info(cls, info, scopes=None): + """Creates a Credentials instance from parsed authorized user info. + + Args: + info (Mapping[str, str]): The authorized user info in Google + format. + scopes (Sequence[str]): Optional list of scopes to include in the + credentials. + + Returns: + google.oauth2.credentials.Credentials: The constructed + credentials. + + Raises: + ValueError: If the info is not in the expected format. + """ + keys_needed = set(("refresh_token", "client_id", "client_secret")) + missing = keys_needed.difference(info.keys()) + + if missing: + raise ValueError( + "Authorized user info was not in the expected format, missing " + "fields {}.".format(", ".join(missing)) + ) + + # access token expiry (datetime obj); auto-expire if not saved + expiry = info.get("expiry") + if expiry: + expiry = datetime.strptime( + expiry.rstrip("Z").split(".")[0], "%Y-%m-%dT%H:%M:%S" + ) + else: + expiry = _helpers.utcnow() - _helpers.REFRESH_THRESHOLD + + # process scopes, which needs to be a seq + if scopes is None and "scopes" in info: + scopes = info.get("scopes") + if isinstance(scopes, str): + scopes = scopes.split(" ") + + return cls( + token=info.get("token"), + refresh_token=info.get("refresh_token"), + token_uri=_GOOGLE_OAUTH2_TOKEN_ENDPOINT, # always overrides + scopes=scopes, + client_id=info.get("client_id"), + client_secret=info.get("client_secret"), + quota_project_id=info.get("quota_project_id"), # may not exist + expiry=expiry, + rapt_token=info.get("rapt_token"), # may not exist + trust_boundary=info.get("trust_boundary"), # may not exist + universe_domain=info.get("universe_domain"), # may not exist + account=info.get("account", ""), # may not exist + ) + + @classmethod + def from_authorized_user_file(cls, filename, scopes=None): + """Creates a Credentials instance from an authorized user json file. + + Args: + filename (str): The path to the authorized user json file. + scopes (Sequence[str]): Optional list of scopes to include in the + credentials. + + Returns: + google.oauth2.credentials.Credentials: The constructed + credentials. + + Raises: + ValueError: If the file is not in the expected format. + """ + with io.open(filename, "r", encoding="utf-8") as json_file: + data = json.load(json_file) + return cls.from_authorized_user_info(data, scopes) + + def to_json(self, strip=None): + """Utility function that creates a JSON representation of a Credentials + object. + + Args: + strip (Sequence[str]): Optional list of members to exclude from the + generated JSON. + + Returns: + str: A JSON representation of this instance. When converted into + a dictionary, it can be passed to from_authorized_user_info() + to create a new credential instance. + """ + prep = { + "token": self.token, + "refresh_token": self.refresh_token, + "token_uri": self.token_uri, + "client_id": self.client_id, + "client_secret": self.client_secret, + "scopes": self.scopes, + "rapt_token": self.rapt_token, + "universe_domain": self._universe_domain, + "account": self._account, + } + if self.expiry: # flatten expiry timestamp + prep["expiry"] = self.expiry.isoformat() + "Z" + + # Remove empty entries (those which are None) + prep = {k: v for k, v in prep.items() if v is not None} + + # Remove entries that explicitely need to be removed + if strip is not None: + prep = {k: v for k, v in prep.items() if k not in strip} + + return json.dumps(prep) + + +class UserAccessTokenCredentials(credentials.CredentialsWithQuotaProject): + """Access token credentials for user account. + + Obtain the access token for a given user account or the current active + user account with the ``gcloud auth print-access-token`` command. + + Args: + account (Optional[str]): Account to get the access token for. If not + specified, the current active account will be used. + quota_project_id (Optional[str]): The project ID used for quota + and billing. + """ + + def __init__(self, account=None, quota_project_id=None): + warnings.warn( + "UserAccessTokenCredentials is deprecated, please use " + "google.oauth2.credentials.Credentials instead. To use " + "that credential type, simply run " + "`gcloud auth application-default login` and let the " + "client libraries pick up the application default credentials." + ) + super(UserAccessTokenCredentials, self).__init__() + self._account = account + self._quota_project_id = quota_project_id + + def with_account(self, account): + """Create a new instance with the given account. + + Args: + account (str): Account to get the access token for. + + Returns: + google.oauth2.credentials.UserAccessTokenCredentials: The created + credentials with the given account. + """ + return self.__class__(account=account, quota_project_id=self._quota_project_id) + + @_helpers.copy_docstring(credentials.CredentialsWithQuotaProject) + def with_quota_project(self, quota_project_id): + return self.__class__(account=self._account, quota_project_id=quota_project_id) + + def refresh(self, request): + """Refreshes the access token. + + Args: + request (google.auth.transport.Request): This argument is required + by the base class interface but not used in this implementation, + so just set it to `None`. + + Raises: + google.auth.exceptions.UserAccessTokenError: If the access token + refresh failed. + """ + self.token = _cloud_sdk.get_auth_access_token(self._account) + + @_helpers.copy_docstring(credentials.Credentials) + def before_request(self, request, method, url, headers): + self.refresh(request) + self.apply(headers) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/gdch_credentials.py b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/gdch_credentials.py new file mode 100644 index 0000000000000000000000000000000000000000..7410cfc2e05eaa84ab490ab4c5ca6c80b4d61891 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/gdch_credentials.py @@ -0,0 +1,251 @@ +# Copyright 2022 Google LLC +# +# Licensed 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. + +"""Experimental GDCH credentials support. +""" + +import datetime + +from google.auth import _helpers +from google.auth import _service_account_info +from google.auth import credentials +from google.auth import exceptions +from google.auth import jwt +from google.oauth2 import _client + + +TOKEN_EXCHANGE_TYPE = "urn:ietf:params:oauth:token-type:token-exchange" +ACCESS_TOKEN_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token" +SERVICE_ACCOUNT_TOKEN_TYPE = "urn:k8s:params:oauth:token-type:serviceaccount" +JWT_LIFETIME = datetime.timedelta(seconds=3600) # 1 hour + + +class ServiceAccountCredentials(credentials.Credentials): + """Credentials for GDCH (`Google Distributed Cloud Hosted`_) for service + account users. + + .. _Google Distributed Cloud Hosted: + https://cloud.google.com/blog/topics/hybrid-cloud/\ + announcing-google-distributed-cloud-edge-and-hosted + + To create a GDCH service account credential, first create a JSON file of + the following format:: + + { + "type": "gdch_service_account", + "format_version": "1", + "project": "", + "private_key_id": "", + "private_key": "-----BEGIN EC PRIVATE KEY-----\n\n-----END EC PRIVATE KEY-----\n", + "name": "", + "ca_cert_path": "", + "token_uri": "https://service-identity./authenticate" + } + + The "format_version" field stands for the format of the JSON file. For now + it is always "1". The `private_key_id` and `private_key` is used for signing. + The `ca_cert_path` is used for token server TLS certificate verification. + + After the JSON file is created, set `GOOGLE_APPLICATION_CREDENTIALS` environment + variable to the JSON file path, then use the following code to create the + credential:: + + import google.auth + + credential, _ = google.auth.default() + credential = credential.with_gdch_audience("") + + We can also create the credential directly:: + + from google.oauth import gdch_credentials + + credential = gdch_credentials.ServiceAccountCredentials.from_service_account_file("") + credential = credential.with_gdch_audience("") + + The token is obtained in the following way. This class first creates a + self signed JWT. It uses the `name` value as the `iss` and `sub` claim, and + the `token_uri` as the `aud` claim, and signs the JWT with the `private_key`. + It then sends the JWT to the `token_uri` to exchange a final token for + `audience`. + """ + + def __init__( + self, signer, service_identity_name, project, audience, token_uri, ca_cert_path + ): + """ + Args: + signer (google.auth.crypt.Signer): The signer used to sign JWTs. + service_identity_name (str): The service identity name. It will be + used as the `iss` and `sub` claim in the self signed JWT. + project (str): The project. + audience (str): The audience for the final token. + token_uri (str): The token server uri. + ca_cert_path (str): The CA cert path for token server side TLS + certificate verification. If the token server uses well known + CA, then this parameter can be `None`. + """ + super(ServiceAccountCredentials, self).__init__() + self._signer = signer + self._service_identity_name = service_identity_name + self._project = project + self._audience = audience + self._token_uri = token_uri + self._ca_cert_path = ca_cert_path + + def _create_jwt(self): + now = _helpers.utcnow() + expiry = now + JWT_LIFETIME + iss_sub_value = "system:serviceaccount:{}:{}".format( + self._project, self._service_identity_name + ) + + payload = { + "iss": iss_sub_value, + "sub": iss_sub_value, + "aud": self._token_uri, + "iat": _helpers.datetime_to_secs(now), + "exp": _helpers.datetime_to_secs(expiry), + } + + return _helpers.from_bytes(jwt.encode(self._signer, payload)) + + @_helpers.copy_docstring(credentials.Credentials) + def refresh(self, request): + import google.auth.transport.requests + + if not isinstance(request, google.auth.transport.requests.Request): + raise exceptions.RefreshError( + "For GDCH service account credentials, request must be a google.auth.transport.requests.Request object" + ) + + # Create a self signed JWT, and do token exchange. + jwt_token = self._create_jwt() + request_body = { + "grant_type": TOKEN_EXCHANGE_TYPE, + "audience": self._audience, + "requested_token_type": ACCESS_TOKEN_TOKEN_TYPE, + "subject_token": jwt_token, + "subject_token_type": SERVICE_ACCOUNT_TOKEN_TYPE, + } + response_data = _client._token_endpoint_request( + request, + self._token_uri, + request_body, + access_token=None, + use_json=True, + verify=self._ca_cert_path, + ) + + self.token, _, self.expiry, _ = _client._handle_refresh_grant_response( + response_data, None + ) + + def with_gdch_audience(self, audience): + """Create a copy of GDCH credentials with the specified audience. + + Args: + audience (str): The intended audience for GDCH credentials. + """ + return self.__class__( + self._signer, + self._service_identity_name, + self._project, + audience, + self._token_uri, + self._ca_cert_path, + ) + + @classmethod + def _from_signer_and_info(cls, signer, info): + """Creates a Credentials instance from a signer and service account + info. + + Args: + signer (google.auth.crypt.Signer): The signer used to sign JWTs. + info (Mapping[str, str]): The service account info. + + Returns: + google.oauth2.gdch_credentials.ServiceAccountCredentials: The constructed + credentials. + + Raises: + ValueError: If the info is not in the expected format. + """ + if info["format_version"] != "1": + raise ValueError("Only format version 1 is supported") + + return cls( + signer, + info["name"], # service_identity_name + info["project"], + None, # audience + info["token_uri"], + info.get("ca_cert_path", None), + ) + + @classmethod + def from_service_account_info(cls, info): + """Creates a Credentials instance from parsed service account info. + + Args: + info (Mapping[str, str]): The service account info in Google + format. + kwargs: Additional arguments to pass to the constructor. + + Returns: + google.oauth2.gdch_credentials.ServiceAccountCredentials: The constructed + credentials. + + Raises: + ValueError: If the info is not in the expected format. + """ + signer = _service_account_info.from_dict( + info, + require=[ + "format_version", + "private_key_id", + "private_key", + "name", + "project", + "token_uri", + ], + use_rsa_signer=False, + ) + return cls._from_signer_and_info(signer, info) + + @classmethod + def from_service_account_file(cls, filename): + """Creates a Credentials instance from a service account json file. + + Args: + filename (str): The path to the service account json file. + kwargs: Additional arguments to pass to the constructor. + + Returns: + google.oauth2.gdch_credentials.ServiceAccountCredentials: The constructed + credentials. + """ + info, signer = _service_account_info.from_filename( + filename, + require=[ + "format_version", + "private_key_id", + "private_key", + "name", + "project", + "token_uri", + ], + use_rsa_signer=False, + ) + return cls._from_signer_and_info(signer, info) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/id_token.py b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/id_token.py new file mode 100644 index 0000000000000000000000000000000000000000..d21be1a06c848fdc5157cd2f2cbfe832b571c990 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/id_token.py @@ -0,0 +1,373 @@ +# Copyright 2016 Google LLC +# +# Licensed 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. + +"""Google ID Token helpers. + +Provides support for verifying `OpenID Connect ID Tokens`_, especially ones +generated by Google infrastructure. + +To parse and verify an ID Token issued by Google's OAuth 2.0 authorization +server use :func:`verify_oauth2_token`. To verify an ID Token issued by +Firebase, use :func:`verify_firebase_token`. + +A general purpose ID Token verifier is available as :func:`verify_token`. + +Example:: + + from google.oauth2 import id_token + from google.auth.transport import requests + + request = requests.Request() + + id_info = id_token.verify_oauth2_token( + token, request, 'my-client-id.example.com') + + userid = id_info['sub'] + +By default, this will re-fetch certificates for each verification. Because +Google's public keys are only changed infrequently (on the order of once per +day), you may wish to take advantage of caching to reduce latency and the +potential for network errors. This can be accomplished using an external +library like `CacheControl`_ to create a cache-aware +:class:`google.auth.transport.Request`:: + + import cachecontrol + import google.auth.transport.requests + import requests + + session = requests.session() + cached_session = cachecontrol.CacheControl(session) + request = google.auth.transport.requests.Request(session=cached_session) + +.. _OpenID Connect ID Tokens: + http://openid.net/specs/openid-connect-core-1_0.html#IDToken +.. _CacheControl: https://cachecontrol.readthedocs.io +""" +from __future__ import annotations + +import http.client as http_client +import json +import os +from typing import Any, Mapping, Union + +from google.auth import environment_vars +from google.auth import exceptions +from google.auth import jwt +from google.auth import transport + + +# The URL that provides public certificates for verifying ID tokens issued +# by Google's OAuth 2.0 authorization server. +_GOOGLE_OAUTH2_CERTS_URL = "https://www.googleapis.com/oauth2/v1/certs" + +# The URL that provides public certificates for verifying ID tokens issued +# by Firebase and the Google APIs infrastructure +_GOOGLE_APIS_CERTS_URL = ( + "https://www.googleapis.com/robot/v1/metadata/x509" + "/securetoken@system.gserviceaccount.com" +) + +_GOOGLE_ISSUERS = ["accounts.google.com", "https://accounts.google.com"] + + +def _fetch_certs(request, certs_url): + """Fetches certificates. + + Google-style certificate endpoints return JSON in the format of + ``{'key id': 'x509 certificate'}`` or a certificate array according + to the JWK spec (see https://tools.ietf.org/html/rfc7517). + + Args: + request (google.auth.transport.Request): The object used to make + HTTP requests. + certs_url (str): The certificate endpoint URL. + + Returns: + Mapping[str, str] | Mapping[str, list]: A mapping of public keys + in x.509 or JWK spec. + """ + response = request(certs_url, method="GET") + + if response.status != http_client.OK: + raise exceptions.TransportError( + "Could not fetch certificates at {}".format(certs_url) + ) + + return json.loads(response.data.decode("utf-8")) + + +def verify_token( + id_token: Union[str, bytes], + request: transport.Request, + audience: Union[str, list[str], None] = None, + certs_url: str = _GOOGLE_OAUTH2_CERTS_URL, + clock_skew_in_seconds: int = 0, +) -> Mapping[str, Any]: + """Verifies an ID token and returns the decoded token. + + Args: + id_token (Union[str, bytes]): The encoded token. + request (google.auth.transport.Request): The object used to make + HTTP requests. + audience (str or list): The audience or audiences that this token is + intended for. If None then the audience is not verified. + certs_url (str): The URL that specifies the certificates to use to + verify the token. This URL should return JSON in the format of + ``{'key id': 'x509 certificate'}`` or a certificate array according to + the JWK spec (see https://tools.ietf.org/html/rfc7517). + clock_skew_in_seconds (int): The clock skew used for `iat` and `exp` + validation. + + Returns: + Mapping[str, Any]: The decoded token. + """ + certs = _fetch_certs(request, certs_url) + + if "keys" in certs: + try: + import jwt as jwt_lib # type: ignore + except ImportError as caught_exc: # pragma: NO COVER + raise ImportError( + "The pyjwt library is not installed, please install the pyjwt package to use the jwk certs format." + ) from caught_exc + jwks_client = jwt_lib.PyJWKClient(certs_url) + signing_key = jwks_client.get_signing_key_from_jwt(id_token) + return jwt_lib.decode( + id_token, + signing_key.key, + algorithms=[signing_key.algorithm_name], + audience=audience, + ) + else: + return jwt.decode( + id_token, + certs=certs, + audience=audience, + clock_skew_in_seconds=clock_skew_in_seconds, + ) + + +def verify_oauth2_token(id_token, request, audience=None, clock_skew_in_seconds=0): + """Verifies an ID Token issued by Google's OAuth 2.0 authorization server. + + Args: + id_token (Union[str, bytes]): The encoded token. + request (google.auth.transport.Request): The object used to make + HTTP requests. + audience (str): The audience that this token is intended for. This is + typically your application's OAuth 2.0 client ID. If None then the + audience is not verified. + clock_skew_in_seconds (int): The clock skew used for `iat` and `exp` + validation. + + Returns: + Mapping[str, Any]: The decoded token. + + Raises: + exceptions.GoogleAuthError: If the issuer is invalid. + ValueError: If token verification fails + """ + idinfo = verify_token( + id_token, + request, + audience=audience, + certs_url=_GOOGLE_OAUTH2_CERTS_URL, + clock_skew_in_seconds=clock_skew_in_seconds, + ) + + if idinfo["iss"] not in _GOOGLE_ISSUERS: + raise exceptions.GoogleAuthError( + "Wrong issuer. 'iss' should be one of the following: {}".format( + _GOOGLE_ISSUERS + ) + ) + + return idinfo + + +def verify_firebase_token(id_token, request, audience=None, clock_skew_in_seconds=0): + """Verifies an ID Token issued by Firebase Authentication. + + Args: + id_token (Union[str, bytes]): The encoded token. + request (google.auth.transport.Request): The object used to make + HTTP requests. + audience (str): The audience that this token is intended for. This is + typically your Firebase application ID. If None then the audience + is not verified. + clock_skew_in_seconds (int): The clock skew used for `iat` and `exp` + validation. + + Returns: + Mapping[str, Any]: The decoded token. + """ + return verify_token( + id_token, + request, + audience=audience, + certs_url=_GOOGLE_APIS_CERTS_URL, + clock_skew_in_seconds=clock_skew_in_seconds, + ) + + +def fetch_id_token_credentials(audience, request=None): + """Create the ID Token credentials from the current environment. + + This function acquires ID token from the environment in the following order. + See https://google.aip.dev/auth/4110. + + 1. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set + to the path of a valid service account JSON file, then ID token is + acquired using this service account credentials. + 2. If the application is running in Compute Engine, App Engine or Cloud Run, + then the ID token are obtained from the metadata server. + 3. If metadata server doesn't exist and no valid service account credentials + are found, :class:`~google.auth.exceptions.DefaultCredentialsError` will + be raised. + + Example:: + + import google.oauth2.id_token + import google.auth.transport.requests + + request = google.auth.transport.requests.Request() + target_audience = "https://pubsub.googleapis.com" + + # Create ID token credentials. + credentials = google.oauth2.id_token.fetch_id_token_credentials(target_audience, request=request) + + # Refresh the credential to obtain an ID token. + credentials.refresh(request) + + id_token = credentials.token + id_token_expiry = credentials.expiry + + Args: + audience (str): The audience that this ID token is intended for. + request (Optional[google.auth.transport.Request]): A callable used to make + HTTP requests. A request object will be created if not provided. + + Returns: + google.auth.credentials.Credentials: The ID token credentials. + + Raises: + ~google.auth.exceptions.DefaultCredentialsError: + If metadata server doesn't exist and no valid service account + credentials are found. + """ + # 1. Try to get credentials from the GOOGLE_APPLICATION_CREDENTIALS environment + # variable. + credentials_filename = os.environ.get(environment_vars.CREDENTIALS) + if credentials_filename: + if not ( + os.path.exists(credentials_filename) + and os.path.isfile(credentials_filename) + ): + raise exceptions.DefaultCredentialsError( + "GOOGLE_APPLICATION_CREDENTIALS path is either not found or invalid." + ) + + try: + with open(credentials_filename, "r") as f: + from google.oauth2 import service_account + + info = json.load(f) + if info.get("type") == "service_account": + return service_account.IDTokenCredentials.from_service_account_info( + info, target_audience=audience + ) + elif info.get("type") == "impersonated_service_account": + from google.auth import impersonated_credentials + + target_credentials = impersonated_credentials.Credentials.from_impersonated_service_account_info( + info + ) + + return impersonated_credentials.IDTokenCredentials( + target_credentials=target_credentials, + target_audience=audience, + include_email=True, + ) + except ValueError as caught_exc: + new_exc = exceptions.DefaultCredentialsError( + "GOOGLE_APPLICATION_CREDENTIALS is not valid service account credentials.", + caught_exc, + ) + raise new_exc from caught_exc + + # 2. Try to fetch ID token from metada server if it exists. The code + # works for GAE and Cloud Run metadata server as well. + try: + from google.auth import compute_engine + from google.auth.compute_engine import _metadata + + # Create a request object if not provided. + if not request: + import google.auth.transport.requests + + request = google.auth.transport.requests.Request() + + if _metadata.ping(request): + return compute_engine.IDTokenCredentials( + request, audience, use_metadata_identity_endpoint=True + ) + except (ImportError, exceptions.TransportError): + pass + + raise exceptions.DefaultCredentialsError( + "Neither metadata server or valid service account credentials are found." + ) + + +def fetch_id_token(request, audience): + """Fetch the ID Token from the current environment. + + This function acquires ID token from the environment in the following order. + See https://google.aip.dev/auth/4110. + + 1. If the environment variable ``GOOGLE_APPLICATION_CREDENTIALS`` is set + to the path of a valid service account JSON file, then ID token is + acquired using this service account credentials. + 2. If the application is running in Compute Engine, App Engine or Cloud Run, + then the ID token are obtained from the metadata server. + 3. If metadata server doesn't exist and no valid service account credentials + are found, :class:`~google.auth.exceptions.DefaultCredentialsError` will + be raised. + + Example:: + + import google.oauth2.id_token + import google.auth.transport.requests + + request = google.auth.transport.requests.Request() + target_audience = "https://pubsub.googleapis.com" + + id_token = google.oauth2.id_token.fetch_id_token(request, target_audience) + + Args: + request (google.auth.transport.Request): A callable used to make + HTTP requests. + audience (str): The audience that this ID token is intended for. + + Returns: + str: The ID token. + + Raises: + ~google.auth.exceptions.DefaultCredentialsError: + If metadata server doesn't exist and no valid service account + credentials are found. + """ + id_token_credentials = fetch_id_token_credentials(audience, request=request) + id_token_credentials.refresh(request) + return id_token_credentials.token diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/py.typed b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..d82ed62c2f052f2d46ea9843ac82ed475f223593 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-oauth2 package uses inline types. diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/reauth.py b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/reauth.py new file mode 100644 index 0000000000000000000000000000000000000000..abf691d58a64018d17efbd0d7a36f39d6d494c65 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/reauth.py @@ -0,0 +1,373 @@ +# Copyright 2021 Google LLC +# +# Licensed 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. + +"""A module that provides functions for handling rapt authentication. + +Reauth is a process of obtaining additional authentication (such as password, +security token, etc.) while refreshing OAuth 2.0 credentials for a user. + +Credentials that use the Reauth flow must have the reauth scope, +``https://www.googleapis.com/auth/accounts.reauth``. + +This module provides a high-level function for executing the Reauth process, +:func:`refresh_grant`, and lower-level helpers for doing the individual +steps of the reauth process. + +Those steps are: + +1. Obtaining a list of challenges from the reauth server. +2. Running through each challenge and sending the result back to the reauth + server. +3. Refreshing the access token using the returned rapt token. +""" + +import sys + +from google.auth import exceptions +from google.auth import metrics +from google.oauth2 import _client +from google.oauth2 import challenges + + +_REAUTH_SCOPE = "https://www.googleapis.com/auth/accounts.reauth" +_REAUTH_API = "https://reauth.googleapis.com/v2/sessions" + +_REAUTH_NEEDED_ERROR = "invalid_grant" +_REAUTH_NEEDED_ERROR_INVALID_RAPT = "invalid_rapt" +_REAUTH_NEEDED_ERROR_RAPT_REQUIRED = "rapt_required" + +_AUTHENTICATED = "AUTHENTICATED" +_CHALLENGE_REQUIRED = "CHALLENGE_REQUIRED" +_CHALLENGE_PENDING = "CHALLENGE_PENDING" + + +# Override this global variable to set custom max number of rounds of reauth +# challenges should be run. +RUN_CHALLENGE_RETRY_LIMIT = 5 + + +def is_interactive(): + """Check if we are in an interractive environment. + + Override this function with a different logic if you are using this library + outside a CLI. + + If the rapt token needs refreshing, the user needs to answer the challenges. + If the user is not in an interractive environment, the challenges can not + be answered and we just wait for timeout for no reason. + + Returns: + bool: True if is interactive environment, False otherwise. + """ + + return sys.stdin.isatty() + + +def _get_challenges( + request, supported_challenge_types, access_token, requested_scopes=None +): + """Does initial request to reauth API to get the challenges. + + Args: + request (google.auth.transport.Request): A callable used to make + HTTP requests. + supported_challenge_types (Sequence[str]): list of challenge names + supported by the manager. + access_token (str): Access token with reauth scopes. + requested_scopes (Optional(Sequence[str])): Authorized scopes for the credentials. + + Returns: + dict: The response from the reauth API. + """ + body = {"supportedChallengeTypes": supported_challenge_types} + if requested_scopes: + body["oauthScopesForDomainPolicyLookup"] = requested_scopes + metrics_header = {metrics.API_CLIENT_HEADER: metrics.reauth_start()} + + return _client._token_endpoint_request( + request, + _REAUTH_API + ":start", + body, + access_token=access_token, + use_json=True, + headers=metrics_header, + ) + + +def _send_challenge_result( + request, session_id, challenge_id, client_input, access_token +): + """Attempt to refresh access token by sending next challenge result. + + Args: + request (google.auth.transport.Request): A callable used to make + HTTP requests. + session_id (str): session id returned by the initial reauth call. + challenge_id (str): challenge id returned by the initial reauth call. + client_input: dict with a challenge-specific client input. For example: + ``{'credential': password}`` for password challenge. + access_token (str): Access token with reauth scopes. + + Returns: + dict: The response from the reauth API. + """ + body = { + "sessionId": session_id, + "challengeId": challenge_id, + "action": "RESPOND", + "proposalResponse": client_input, + } + metrics_header = {metrics.API_CLIENT_HEADER: metrics.reauth_continue()} + + return _client._token_endpoint_request( + request, + _REAUTH_API + "/{}:continue".format(session_id), + body, + access_token=access_token, + use_json=True, + headers=metrics_header, + ) + + +def _run_next_challenge(msg, request, access_token): + """Get the next challenge from msg and run it. + + Args: + msg (dict): Reauth API response body (either from the initial request to + https://reauth.googleapis.com/v2/sessions:start or from sending the + previous challenge response to + https://reauth.googleapis.com/v2/sessions/id:continue) + request (google.auth.transport.Request): A callable used to make + HTTP requests. + access_token (str): reauth access token + + Returns: + dict: The response from the reauth API. + + Raises: + google.auth.exceptions.ReauthError: if reauth failed. + """ + for challenge in msg["challenges"]: + if challenge["status"] != "READY": + # Skip non-activated challenges. + continue + c = challenges.AVAILABLE_CHALLENGES.get(challenge["challengeType"], None) + if not c: + raise exceptions.ReauthFailError( + "Unsupported challenge type {0}. Supported types: {1}".format( + challenge["challengeType"], + ",".join(list(challenges.AVAILABLE_CHALLENGES.keys())), + ) + ) + if not c.is_locally_eligible: + raise exceptions.ReauthFailError( + "Challenge {0} is not locally eligible".format( + challenge["challengeType"] + ) + ) + client_input = c.obtain_challenge_input(challenge) + if not client_input: + return None + return _send_challenge_result( + request, + msg["sessionId"], + challenge["challengeId"], + client_input, + access_token, + ) + return None + + +def _obtain_rapt(request, access_token, requested_scopes): + """Given an http request method and reauth access token, get rapt token. + + Args: + request (google.auth.transport.Request): A callable used to make + HTTP requests. + access_token (str): reauth access token + requested_scopes (Sequence[str]): scopes required by the client application + + Returns: + str: The rapt token. + + Raises: + google.auth.exceptions.ReauthError: if reauth failed + """ + msg = _get_challenges( + request, + list(challenges.AVAILABLE_CHALLENGES.keys()), + access_token, + requested_scopes, + ) + + if msg["status"] == _AUTHENTICATED: + return msg["encodedProofOfReauthToken"] + + for _ in range(0, RUN_CHALLENGE_RETRY_LIMIT): + if not ( + msg["status"] == _CHALLENGE_REQUIRED or msg["status"] == _CHALLENGE_PENDING + ): + raise exceptions.ReauthFailError( + "Reauthentication challenge failed due to API error: {}".format( + msg["status"] + ) + ) + + if not is_interactive(): + raise exceptions.ReauthFailError( + "Reauthentication challenge could not be answered because you are not" + " in an interactive session." + ) + + msg = _run_next_challenge(msg, request, access_token) + + if not msg: + raise exceptions.ReauthFailError("Failed to obtain rapt token.") + if msg["status"] == _AUTHENTICATED: + return msg["encodedProofOfReauthToken"] + + # If we got here it means we didn't get authenticated. + raise exceptions.ReauthFailError("Failed to obtain rapt token.") + + +def get_rapt_token( + request, client_id, client_secret, refresh_token, token_uri, scopes=None +): + """Given an http request method and refresh_token, get rapt token. + + Args: + request (google.auth.transport.Request): A callable used to make + HTTP requests. + client_id (str): client id to get access token for reauth scope. + client_secret (str): client secret for the client_id + refresh_token (str): refresh token to refresh access token + token_uri (str): uri to refresh access token + scopes (Optional(Sequence[str])): scopes required by the client application + + Returns: + str: The rapt token. + Raises: + google.auth.exceptions.RefreshError: If reauth failed. + """ + sys.stderr.write("Reauthentication required.\n") + + # Get access token for reauth. + access_token, _, _, _ = _client.refresh_grant( + request=request, + client_id=client_id, + client_secret=client_secret, + refresh_token=refresh_token, + token_uri=token_uri, + scopes=[_REAUTH_SCOPE], + ) + + # Get rapt token from reauth API. + rapt_token = _obtain_rapt(request, access_token, requested_scopes=scopes) + sys.stderr.write("Reauthentication successful.\n") + + return rapt_token + + +def refresh_grant( + request, + token_uri, + refresh_token, + client_id, + client_secret, + scopes=None, + rapt_token=None, + enable_reauth_refresh=False, +): + """Implements the reauthentication flow. + + Args: + request (google.auth.transport.Request): A callable used to make + HTTP requests. + token_uri (str): The OAuth 2.0 authorizations server's token endpoint + URI. + refresh_token (str): The refresh token to use to get a new access + token. + client_id (str): The OAuth 2.0 application's client ID. + client_secret (str): The Oauth 2.0 appliaction's client secret. + scopes (Optional(Sequence[str])): Scopes to request. If present, all + scopes must be authorized for the refresh token. Useful if refresh + token has a wild card scope (e.g. + 'https://www.googleapis.com/auth/any-api'). + rapt_token (Optional(str)): The rapt token for reauth. + enable_reauth_refresh (Optional[bool]): Whether reauth refresh flow + should be used. The default value is False. This option is for + gcloud only, other users should use the default value. + + Returns: + Tuple[str, Optional[str], Optional[datetime], Mapping[str, str], str]: The + access token, new refresh token, expiration, the additional data + returned by the token endpoint, and the rapt token. + + Raises: + google.auth.exceptions.RefreshError: If the token endpoint returned + an error. + """ + body = { + "grant_type": _client._REFRESH_GRANT_TYPE, + "client_id": client_id, + "client_secret": client_secret, + "refresh_token": refresh_token, + } + if scopes: + body["scope"] = " ".join(scopes) + if rapt_token: + body["rapt"] = rapt_token + metrics_header = {metrics.API_CLIENT_HEADER: metrics.token_request_user()} + + ( + response_status_ok, + response_data, + retryable_error, + ) = _client._token_endpoint_request_no_throw( + request, token_uri, body, headers=metrics_header + ) + + if not response_status_ok and isinstance(response_data, str): + raise exceptions.RefreshError(response_data, retryable=False) + + if ( + not response_status_ok + and response_data.get("error") == _REAUTH_NEEDED_ERROR + and ( + response_data.get("error_subtype") == _REAUTH_NEEDED_ERROR_INVALID_RAPT + or response_data.get("error_subtype") == _REAUTH_NEEDED_ERROR_RAPT_REQUIRED + ) + ): + if not enable_reauth_refresh: + raise exceptions.RefreshError( + "Reauthentication is needed. Please run `gcloud auth application-default login` to reauthenticate." + ) + + rapt_token = get_rapt_token( + request, client_id, client_secret, refresh_token, token_uri, scopes=scopes + ) + body["rapt"] = rapt_token + ( + response_status_ok, + response_data, + retryable_error, + ) = _client._token_endpoint_request_no_throw( + request, token_uri, body, headers=metrics_header + ) + + if not response_status_ok: + _client._handle_error_response(response_data, retryable_error) + return _client._handle_refresh_grant_response(response_data, refresh_token) + ( + rapt_token, + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/service_account.py b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/service_account.py new file mode 100644 index 0000000000000000000000000000000000000000..f897b3b75d51e15fd4f6cfcf8bd7641199c96539 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/service_account.py @@ -0,0 +1,880 @@ +# Copyright 2016 Google LLC +# +# Licensed 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. + +"""Service Accounts: JSON Web Token (JWT) Profile for OAuth 2.0 + +This module implements the JWT Profile for OAuth 2.0 Authorization Grants +as defined by `RFC 7523`_ with particular support for how this RFC is +implemented in Google's infrastructure. Google refers to these credentials +as *Service Accounts*. + +Service accounts are used for server-to-server communication, such as +interactions between a web application server and a Google service. The +service account belongs to your application instead of to an individual end +user. In contrast to other OAuth 2.0 profiles, no users are involved and your +application "acts" as the service account. + +Typically an application uses a service account when the application uses +Google APIs to work with its own data rather than a user's data. For example, +an application that uses Google Cloud Datastore for data persistence would use +a service account to authenticate its calls to the Google Cloud Datastore API. +However, an application that needs to access a user's Drive documents would +use the normal OAuth 2.0 profile. + +Additionally, Google Apps domain administrators can grant service accounts +`domain-wide delegation`_ authority to access user data on behalf of users in +the domain. + +This profile uses a JWT to acquire an OAuth 2.0 access token. The JWT is used +in place of the usual authorization token returned during the standard +OAuth 2.0 Authorization Code grant. The JWT is only used for this purpose, as +the acquired access token is used as the bearer token when making requests +using these credentials. + +This profile differs from normal OAuth 2.0 profile because no user consent +step is required. The use of the private key allows this profile to assert +identity directly. + +This profile also differs from the :mod:`google.auth.jwt` authentication +because the JWT credentials use the JWT directly as the bearer token. This +profile instead only uses the JWT to obtain an OAuth 2.0 access token. The +obtained OAuth 2.0 access token is used as the bearer token. + +Domain-wide delegation +---------------------- + +Domain-wide delegation allows a service account to access user data on +behalf of any user in a Google Apps domain without consent from the user. +For example, an application that uses the Google Calendar API to add events to +the calendars of all users in a Google Apps domain would use a service account +to access the Google Calendar API on behalf of users. + +The Google Apps administrator must explicitly authorize the service account to +do this. This authorization step is referred to as "delegating domain-wide +authority" to a service account. + +You can use domain-wise delegation by creating a set of credentials with a +specific subject using :meth:`~Credentials.with_subject`. + +.. _RFC 7523: https://tools.ietf.org/html/rfc7523 +""" + +import copy +import datetime + +from google.auth import _constants +from google.auth import _helpers +from google.auth import _service_account_info +from google.auth import credentials +from google.auth import exceptions +from google.auth import iam +from google.auth import jwt +from google.auth import metrics +from google.oauth2 import _client + +_DEFAULT_TOKEN_LIFETIME_SECS = 3600 # 1 hour in seconds +_GOOGLE_OAUTH2_TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token" + + +class Credentials( + credentials.Signing, + credentials.Scoped, + credentials.CredentialsWithQuotaProject, + credentials.CredentialsWithTokenUri, + credentials.CredentialsWithTrustBoundary, +): + """Service account credentials + + Usually, you'll create these credentials with one of the helper + constructors. To create credentials using a Google service account + private key JSON file:: + + credentials = service_account.Credentials.from_service_account_file( + 'service-account.json') + + Or if you already have the service account file loaded:: + + service_account_info = json.load(open('service_account.json')) + credentials = service_account.Credentials.from_service_account_info( + service_account_info) + + Both helper methods pass on arguments to the constructor, so you can + specify additional scopes and a subject if necessary:: + + credentials = service_account.Credentials.from_service_account_file( + 'service-account.json', + scopes=['email'], + subject='user@example.com') + + The credentials are considered immutable. If you want to modify the scopes + or the subject used for delegation, use :meth:`with_scopes` or + :meth:`with_subject`:: + + scoped_credentials = credentials.with_scopes(['email']) + delegated_credentials = credentials.with_subject(subject) + + To add a quota project, use :meth:`with_quota_project`:: + + credentials = credentials.with_quota_project('myproject-123') + """ + + def __init__( + self, + signer, + service_account_email, + token_uri, + scopes=None, + default_scopes=None, + subject=None, + project_id=None, + quota_project_id=None, + additional_claims=None, + always_use_jwt_access=False, + universe_domain=credentials.DEFAULT_UNIVERSE_DOMAIN, + trust_boundary=None, + ): + """ + Args: + signer (google.auth.crypt.Signer): The signer used to sign JWTs. + service_account_email (str): The service account's email. + scopes (Sequence[str]): User-defined scopes to request during the + authorization grant. + default_scopes (Sequence[str]): Default scopes passed by a + Google client library. Use 'scopes' for user-defined scopes. + token_uri (str): The OAuth 2.0 Token URI. + subject (str): For domain-wide delegation, the email address of the + user to for which to request delegated access. + project_id (str): Project ID associated with the service account + credential. + quota_project_id (Optional[str]): The project ID used for quota and + billing. + additional_claims (Mapping[str, str]): Any additional claims for + the JWT assertion used in the authorization grant. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be always used. + universe_domain (str): The universe domain. The default + universe domain is googleapis.com. For default value self + signed jwt is used for token refresh. + trust_boundary (Mapping[str,str]): A credential trust boundary. + + .. note:: Typically one of the helper constructors + :meth:`from_service_account_file` or + :meth:`from_service_account_info` are used instead of calling the + constructor directly. + """ + super(Credentials, self).__init__() + + self._cred_file_path = None + self._scopes = scopes + self._default_scopes = default_scopes + self._signer = signer + self._service_account_email = service_account_email + self._subject = subject + self._project_id = project_id + self._quota_project_id = quota_project_id + self._token_uri = token_uri + self._always_use_jwt_access = always_use_jwt_access + self._universe_domain = universe_domain or credentials.DEFAULT_UNIVERSE_DOMAIN + + if universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN: + self._always_use_jwt_access = True + + self._jwt_credentials = None + + if additional_claims is not None: + self._additional_claims = additional_claims + else: + self._additional_claims = {} + self._trust_boundary = trust_boundary + + @classmethod + def _from_signer_and_info(cls, signer, info, **kwargs): + """Creates a Credentials instance from a signer and service account + info. + + Args: + signer (google.auth.crypt.Signer): The signer used to sign JWTs. + info (Mapping[str, str]): The service account info. + kwargs: Additional arguments to pass to the constructor. + + Returns: + google.auth.jwt.Credentials: The constructed credentials. + + Raises: + ValueError: If the info is not in the expected format. + """ + return cls( + signer, + service_account_email=info["client_email"], + token_uri=info["token_uri"], + project_id=info.get("project_id"), + universe_domain=info.get( + "universe_domain", credentials.DEFAULT_UNIVERSE_DOMAIN + ), + trust_boundary=info.get("trust_boundary"), + **kwargs, + ) + + @classmethod + def from_service_account_info(cls, info, **kwargs): + """Creates a Credentials instance from parsed service account info. + + Args: + info (Mapping[str, str]): The service account info in Google + format. + kwargs: Additional arguments to pass to the constructor. + + Returns: + google.auth.service_account.Credentials: The constructed + credentials. + + Raises: + ValueError: If the info is not in the expected format. + """ + signer = _service_account_info.from_dict( + info, require=["client_email", "token_uri"] + ) + return cls._from_signer_and_info(signer, info, **kwargs) + + @classmethod + def from_service_account_file(cls, filename, **kwargs): + """Creates a Credentials instance from a service account json file. + + Args: + filename (str): The path to the service account json file. + kwargs: Additional arguments to pass to the constructor. + + Returns: + google.auth.service_account.Credentials: The constructed + credentials. + """ + info, signer = _service_account_info.from_filename( + filename, require=["client_email", "token_uri"] + ) + return cls._from_signer_and_info(signer, info, **kwargs) + + @property + def service_account_email(self): + """The service account email.""" + return self._service_account_email + + @property + def project_id(self): + """Project ID associated with this credential.""" + return self._project_id + + @property + def requires_scopes(self): + """Checks if the credentials requires scopes. + + Returns: + bool: True if there are no scopes set otherwise False. + """ + return True if not self._scopes else False + + def _make_copy(self): + cred = self.__class__( + self._signer, + service_account_email=self._service_account_email, + scopes=copy.copy(self._scopes), + default_scopes=copy.copy(self._default_scopes), + token_uri=self._token_uri, + subject=self._subject, + project_id=self._project_id, + quota_project_id=self._quota_project_id, + additional_claims=self._additional_claims.copy(), + always_use_jwt_access=self._always_use_jwt_access, + universe_domain=self._universe_domain, + trust_boundary=self._trust_boundary, + ) + cred._cred_file_path = self._cred_file_path + return cred + + @_helpers.copy_docstring(credentials.Scoped) + def with_scopes(self, scopes, default_scopes=None): + cred = self._make_copy() + cred._scopes = scopes + cred._default_scopes = default_scopes + return cred + + def with_always_use_jwt_access(self, always_use_jwt_access): + """Create a copy of these credentials with the specified always_use_jwt_access value. + + Args: + always_use_jwt_access (bool): Whether always use self signed JWT or not. + + Returns: + google.auth.service_account.Credentials: A new credentials + instance. + Raises: + google.auth.exceptions.InvalidValue: If the universe domain is not + default and always_use_jwt_access is False. + """ + cred = self._make_copy() + if ( + cred._universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN + and not always_use_jwt_access + ): + raise exceptions.InvalidValue( + "always_use_jwt_access should be True for non-default universe domain" + ) + cred._always_use_jwt_access = always_use_jwt_access + return cred + + @_helpers.copy_docstring(credentials.CredentialsWithUniverseDomain) + def with_universe_domain(self, universe_domain): + cred = self._make_copy() + cred._universe_domain = universe_domain + if universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN: + cred._always_use_jwt_access = True + return cred + + def with_subject(self, subject): + """Create a copy of these credentials with the specified subject. + + Args: + subject (str): The subject claim. + + Returns: + google.auth.service_account.Credentials: A new credentials + instance. + """ + cred = self._make_copy() + cred._subject = subject + return cred + + def with_claims(self, additional_claims): + """Returns a copy of these credentials with modified claims. + + Args: + additional_claims (Mapping[str, str]): Any additional claims for + the JWT payload. This will be merged with the current + additional claims. + + Returns: + google.auth.service_account.Credentials: A new credentials + instance. + """ + new_additional_claims = copy.deepcopy(self._additional_claims) + new_additional_claims.update(additional_claims or {}) + cred = self._make_copy() + cred._additional_claims = new_additional_claims + return cred + + @_helpers.copy_docstring(credentials.CredentialsWithQuotaProject) + def with_quota_project(self, quota_project_id): + cred = self._make_copy() + cred._quota_project_id = quota_project_id + return cred + + @_helpers.copy_docstring(credentials.CredentialsWithTokenUri) + def with_token_uri(self, token_uri): + cred = self._make_copy() + cred._token_uri = token_uri + return cred + + @_helpers.copy_docstring(credentials.CredentialsWithTrustBoundary) + def with_trust_boundary(self, trust_boundary): + cred = self._make_copy() + cred._trust_boundary = trust_boundary + return cred + + def _make_authorization_grant_assertion(self): + """Create the OAuth 2.0 assertion. + + This assertion is used during the OAuth 2.0 grant to acquire an + access token. + + Returns: + bytes: The authorization grant assertion. + """ + now = _helpers.utcnow() + lifetime = datetime.timedelta(seconds=_DEFAULT_TOKEN_LIFETIME_SECS) + expiry = now + lifetime + + payload = { + "iat": _helpers.datetime_to_secs(now), + "exp": _helpers.datetime_to_secs(expiry), + # The issuer must be the service account email. + "iss": self._service_account_email, + # The audience must be the auth token endpoint's URI + "aud": _GOOGLE_OAUTH2_TOKEN_ENDPOINT, + "scope": _helpers.scopes_to_string(self._scopes or ()), + } + + payload.update(self._additional_claims) + + # The subject can be a user email for domain-wide delegation. + if self._subject: + payload.setdefault("sub", self._subject) + + token = jwt.encode(self._signer, payload) + + return token + + def _use_self_signed_jwt(self): + # Since domain wide delegation doesn't work with self signed JWT. If + # subject exists, then we should not use self signed JWT. + return self._subject is None and self._jwt_credentials is not None + + def _metric_header_for_usage(self): + if self._use_self_signed_jwt(): + return metrics.CRED_TYPE_SA_JWT + return metrics.CRED_TYPE_SA_ASSERTION + + @_helpers.copy_docstring(credentials.CredentialsWithTrustBoundary) + def _perform_refresh_token(self, request): + if self._always_use_jwt_access and not self._jwt_credentials: + # If self signed jwt should be used but jwt credential is not + # created, try to create one with scopes + self._create_self_signed_jwt(None) + + if ( + self._universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN + and self._subject + ): + raise exceptions.RefreshError( + "domain wide delegation is not supported for non-default universe domain" + ) + + if self._use_self_signed_jwt(): + self._jwt_credentials.refresh(request) + self.token = self._jwt_credentials.token.decode() + self.expiry = self._jwt_credentials.expiry + else: + assertion = self._make_authorization_grant_assertion() + access_token, expiry, _ = _client.jwt_grant( + request, self._token_uri, assertion + ) + self.token = access_token + self.expiry = expiry + + def _create_self_signed_jwt(self, audience): + """Create a self-signed JWT from the credentials if requirements are met. + + Args: + audience (str): The service URL. ``https://[API_ENDPOINT]/`` + """ + # https://google.aip.dev/auth/4111 + if self._always_use_jwt_access: + if self._scopes: + additional_claims = {"scope": " ".join(self._scopes)} + if ( + self._jwt_credentials is None + or self._jwt_credentials.additional_claims != additional_claims + ): + self._jwt_credentials = jwt.Credentials.from_signing_credentials( + self, None, additional_claims=additional_claims + ) + elif audience: + if ( + self._jwt_credentials is None + or self._jwt_credentials._audience != audience + ): + self._jwt_credentials = jwt.Credentials.from_signing_credentials( + self, audience + ) + elif self._default_scopes: + additional_claims = {"scope": " ".join(self._default_scopes)} + if ( + self._jwt_credentials is None + or additional_claims != self._jwt_credentials.additional_claims + ): + self._jwt_credentials = jwt.Credentials.from_signing_credentials( + self, None, additional_claims=additional_claims + ) + elif not self._scopes and audience: + self._jwt_credentials = jwt.Credentials.from_signing_credentials( + self, audience + ) + + def _build_trust_boundary_lookup_url(self): + """Builds and returns the URL for the trust boundary lookup API. + + This method constructs the specific URL for the IAM Credentials API's + `allowedLocations` endpoint, using the credential's universe domain + and service account email. + + Raises: + ValueError: If `self.service_account_email` is None or an empty + string, as it's required to form the URL. + + Returns: + str: The URL for the trust boundary lookup endpoint. + """ + if not self.service_account_email: + raise ValueError( + "Service account email is required to build the trust boundary lookup URL." + ) + return _constants._SERVICE_ACCOUNT_TRUST_BOUNDARY_LOOKUP_ENDPOINT.format( + universe_domain=self._universe_domain, + service_account_email=self._service_account_email, + ) + + @_helpers.copy_docstring(credentials.Signing) + def sign_bytes(self, message): + return self._signer.sign(message) + + @property # type: ignore + @_helpers.copy_docstring(credentials.Signing) + def signer(self): + return self._signer + + @property # type: ignore + @_helpers.copy_docstring(credentials.Signing) + def signer_email(self): + return self._service_account_email + + @_helpers.copy_docstring(credentials.Credentials) + def get_cred_info(self): + if self._cred_file_path: + return { + "credential_source": self._cred_file_path, + "credential_type": "service account credentials", + "principal": self.service_account_email, + } + return None + + +class IDTokenCredentials( + credentials.Signing, + credentials.CredentialsWithQuotaProject, + credentials.CredentialsWithTokenUri, +): + """Open ID Connect ID Token-based service account credentials. + + These credentials are largely similar to :class:`.Credentials`, but instead + of using an OAuth 2.0 Access Token as the bearer token, they use an Open + ID Connect ID Token as the bearer token. These credentials are useful when + communicating to services that require ID Tokens and can not accept access + tokens. + + Usually, you'll create these credentials with one of the helper + constructors. To create credentials using a Google service account + private key JSON file:: + + credentials = ( + service_account.IDTokenCredentials.from_service_account_file( + 'service-account.json')) + + + Or if you already have the service account file loaded:: + + service_account_info = json.load(open('service_account.json')) + credentials = ( + service_account.IDTokenCredentials.from_service_account_info( + service_account_info)) + + + Both helper methods pass on arguments to the constructor, so you can + specify additional scopes and a subject if necessary:: + + credentials = ( + service_account.IDTokenCredentials.from_service_account_file( + 'service-account.json', + scopes=['email'], + subject='user@example.com')) + + + The credentials are considered immutable. If you want to modify the scopes + or the subject used for delegation, use :meth:`with_scopes` or + :meth:`with_subject`:: + + scoped_credentials = credentials.with_scopes(['email']) + delegated_credentials = credentials.with_subject(subject) + + """ + + def __init__( + self, + signer, + service_account_email, + token_uri, + target_audience, + additional_claims=None, + quota_project_id=None, + universe_domain=credentials.DEFAULT_UNIVERSE_DOMAIN, + ): + """ + Args: + signer (google.auth.crypt.Signer): The signer used to sign JWTs. + service_account_email (str): The service account's email. + token_uri (str): The OAuth 2.0 Token URI. + target_audience (str): The intended audience for these credentials, + used when requesting the ID Token. The ID Token's ``aud`` claim + will be set to this string. + additional_claims (Mapping[str, str]): Any additional claims for + the JWT assertion used in the authorization grant. + quota_project_id (Optional[str]): The project ID used for quota and billing. + universe_domain (str): The universe domain. The default + universe domain is googleapis.com. For default value IAM ID + token endponint is used for token refresh. Note that + iam.serviceAccountTokenCreator role is required to use the IAM + endpoint. + + .. note:: Typically one of the helper constructors + :meth:`from_service_account_file` or + :meth:`from_service_account_info` are used instead of calling the + constructor directly. + """ + super(IDTokenCredentials, self).__init__() + self._signer = signer + self._service_account_email = service_account_email + self._token_uri = token_uri + self._target_audience = target_audience + self._quota_project_id = quota_project_id + self._use_iam_endpoint = False + + if not universe_domain: + self._universe_domain = credentials.DEFAULT_UNIVERSE_DOMAIN + else: + self._universe_domain = universe_domain + self._iam_id_token_endpoint = iam._IAM_IDTOKEN_ENDPOINT.replace( + "googleapis.com", self._universe_domain + ) + + if self._universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN: + self._use_iam_endpoint = True + + if additional_claims is not None: + self._additional_claims = additional_claims + else: + self._additional_claims = {} + + @classmethod + def _from_signer_and_info(cls, signer, info, **kwargs): + """Creates a credentials instance from a signer and service account + info. + + Args: + signer (google.auth.crypt.Signer): The signer used to sign JWTs. + info (Mapping[str, str]): The service account info. + kwargs: Additional arguments to pass to the constructor. + + Returns: + google.auth.jwt.IDTokenCredentials: The constructed credentials. + + Raises: + ValueError: If the info is not in the expected format. + """ + kwargs.setdefault("service_account_email", info["client_email"]) + kwargs.setdefault("token_uri", info["token_uri"]) + if "universe_domain" in info: + kwargs["universe_domain"] = info["universe_domain"] + return cls(signer, **kwargs) + + @classmethod + def from_service_account_info(cls, info, **kwargs): + """Creates a credentials instance from parsed service account info. + + Args: + info (Mapping[str, str]): The service account info in Google + format. + kwargs: Additional arguments to pass to the constructor. + + Returns: + google.auth.service_account.IDTokenCredentials: The constructed + credentials. + + Raises: + ValueError: If the info is not in the expected format. + """ + signer = _service_account_info.from_dict( + info, require=["client_email", "token_uri"] + ) + return cls._from_signer_and_info(signer, info, **kwargs) + + @classmethod + def from_service_account_file(cls, filename, **kwargs): + """Creates a credentials instance from a service account json file. + + Args: + filename (str): The path to the service account json file. + kwargs: Additional arguments to pass to the constructor. + + Returns: + google.auth.service_account.IDTokenCredentials: The constructed + credentials. + """ + info, signer = _service_account_info.from_filename( + filename, require=["client_email", "token_uri"] + ) + return cls._from_signer_and_info(signer, info, **kwargs) + + def _make_copy(self): + cred = self.__class__( + self._signer, + service_account_email=self._service_account_email, + token_uri=self._token_uri, + target_audience=self._target_audience, + additional_claims=self._additional_claims.copy(), + quota_project_id=self.quota_project_id, + universe_domain=self._universe_domain, + ) + # _use_iam_endpoint is not exposed in the constructor + cred._use_iam_endpoint = self._use_iam_endpoint + return cred + + def with_target_audience(self, target_audience): + """Create a copy of these credentials with the specified target + audience. + + Args: + target_audience (str): The intended audience for these credentials, + used when requesting the ID Token. + + Returns: + google.auth.service_account.IDTokenCredentials: A new credentials + instance. + """ + cred = self._make_copy() + cred._target_audience = target_audience + return cred + + def _with_use_iam_endpoint(self, use_iam_endpoint): + """Create a copy of these credentials with the use_iam_endpoint value. + + Args: + use_iam_endpoint (bool): If True, IAM generateIdToken endpoint will + be used instead of the token_uri. Note that + iam.serviceAccountTokenCreator role is required to use the IAM + endpoint. The default value is False. This feature is currently + experimental and subject to change without notice. + + Returns: + google.auth.service_account.IDTokenCredentials: A new credentials + instance. + Raises: + google.auth.exceptions.InvalidValue: If the universe domain is not + default and use_iam_endpoint is False. + """ + cred = self._make_copy() + if ( + cred._universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN + and not use_iam_endpoint + ): + raise exceptions.InvalidValue( + "use_iam_endpoint should be True for non-default universe domain" + ) + cred._use_iam_endpoint = use_iam_endpoint + return cred + + @_helpers.copy_docstring(credentials.CredentialsWithQuotaProject) + def with_quota_project(self, quota_project_id): + cred = self._make_copy() + cred._quota_project_id = quota_project_id + return cred + + @_helpers.copy_docstring(credentials.CredentialsWithTokenUri) + def with_token_uri(self, token_uri): + cred = self._make_copy() + cred._token_uri = token_uri + return cred + + def _make_authorization_grant_assertion(self): + """Create the OAuth 2.0 assertion. + + This assertion is used during the OAuth 2.0 grant to acquire an + ID token. + + Returns: + bytes: The authorization grant assertion. + """ + now = _helpers.utcnow() + lifetime = datetime.timedelta(seconds=_DEFAULT_TOKEN_LIFETIME_SECS) + expiry = now + lifetime + + payload = { + "iat": _helpers.datetime_to_secs(now), + "exp": _helpers.datetime_to_secs(expiry), + # The issuer must be the service account email. + "iss": self.service_account_email, + # The audience must be the auth token endpoint's URI + "aud": _GOOGLE_OAUTH2_TOKEN_ENDPOINT, + # The target audience specifies which service the ID token is + # intended for. + "target_audience": self._target_audience, + } + + payload.update(self._additional_claims) + + token = jwt.encode(self._signer, payload) + + return token + + def _refresh_with_iam_endpoint(self, request): + """Use IAM generateIdToken endpoint to obtain an ID token. + + It works as follows: + + 1. First we create a self signed jwt with + https://www.googleapis.com/auth/iam being the scope. + + 2. Next we use the self signed jwt as the access token, and make a POST + request to IAM generateIdToken endpoint. The request body is: + { + "audience": self._target_audience, + "includeEmail": "true", + "useEmailAzp": "true", + } + + If the request is succesfully, it will return {"token":"the ID token"}, + and we can extract the ID token and compute its expiry. + """ + jwt_credentials = jwt.Credentials.from_signing_credentials( + self, + None, + additional_claims={"scope": "https://www.googleapis.com/auth/iam"}, + ) + jwt_credentials.refresh(request) + + self.token, self.expiry = _client.call_iam_generate_id_token_endpoint( + request, + self._iam_id_token_endpoint, + self.signer_email, + self._target_audience, + jwt_credentials.token.decode(), + self._universe_domain, + ) + + @_helpers.copy_docstring(credentials.Credentials) + def refresh(self, request): + if self._use_iam_endpoint: + self._refresh_with_iam_endpoint(request) + else: + assertion = self._make_authorization_grant_assertion() + access_token, expiry, _ = _client.id_token_jwt_grant( + request, self._token_uri, assertion + ) + self.token = access_token + self.expiry = expiry + + @property + def service_account_email(self): + """The service account email.""" + return self._service_account_email + + @_helpers.copy_docstring(credentials.Signing) + def sign_bytes(self, message): + return self._signer.sign(message) + + @property # type: ignore + @_helpers.copy_docstring(credentials.Signing) + def signer(self): + return self._signer + + @property # type: ignore + @_helpers.copy_docstring(credentials.Signing) + def signer_email(self): + return self._service_account_email diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/sts.py b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/sts.py new file mode 100644 index 0000000000000000000000000000000000000000..60d6f83c4d9f2681ae111211918c543d853b5113 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/sts.py @@ -0,0 +1,201 @@ +# Copyright 2020 Google LLC +# +# Licensed 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. + +"""OAuth 2.0 Token Exchange Spec. + +This module defines a token exchange utility based on the `OAuth 2.0 Token +Exchange`_ spec. This will be mainly used to exchange external credentials +for GCP access tokens in workload identity pools to access Google APIs. + +The implementation will support various types of client authentication as +allowed in the spec. + +A deviation on the spec will be for additional Google specific options that +cannot be easily mapped to parameters defined in the RFC. + +The returned dictionary response will be based on the `rfc8693 section 2.2.1`_ +spec JSON response. + +.. _OAuth 2.0 Token Exchange: https://tools.ietf.org/html/rfc8693 +.. _rfc8693 section 2.2.1: https://tools.ietf.org/html/rfc8693#section-2.2.1 +""" + +import http.client as http_client +import json +import urllib + +from google.oauth2 import utils + + +_URLENCODED_HEADERS = {"Content-Type": "application/x-www-form-urlencoded"} + + +class Client(utils.OAuthClientAuthHandler): + """Implements the OAuth 2.0 token exchange spec based on + https://tools.ietf.org/html/rfc8693. + """ + + def __init__(self, token_exchange_endpoint, client_authentication=None): + """Initializes an STS client instance. + + Args: + token_exchange_endpoint (str): The token exchange endpoint. + client_authentication (Optional(google.oauth2.oauth2_utils.ClientAuthentication)): + The optional OAuth client authentication credentials if available. + """ + super(Client, self).__init__(client_authentication) + self._token_exchange_endpoint = token_exchange_endpoint + + def _make_request(self, request, headers, request_body, url=None): + # Initialize request headers. + request_headers = _URLENCODED_HEADERS.copy() + + # Inject additional headers. + if headers: + for k, v in dict(headers).items(): + request_headers[k] = v + + # Apply OAuth client authentication. + self.apply_client_authentication_options(request_headers, request_body) + + # Use default token exchange endpoint if no url is provided. + url = url or self._token_exchange_endpoint + + # Execute request. + response = request( + url=url, + method="POST", + headers=request_headers, + body=urllib.parse.urlencode(request_body).encode("utf-8"), + ) + + response_body = ( + response.data.decode("utf-8") + if hasattr(response.data, "decode") + else response.data + ) + + # If non-200 response received, translate to OAuthError exception. + if response.status != http_client.OK: + utils.handle_error_response(response_body) + + # A successful token revocation returns an empty response body. + if not response_body: + return {} + + # Other successful responses should be valid JSON. + return json.loads(response_body) + + def exchange_token( + self, + request, + grant_type, + subject_token, + subject_token_type, + resource=None, + audience=None, + scopes=None, + requested_token_type=None, + actor_token=None, + actor_token_type=None, + additional_options=None, + additional_headers=None, + ): + """Exchanges the provided token for another type of token based on the + rfc8693 spec. + + Args: + request (google.auth.transport.Request): A callable used to make + HTTP requests. + grant_type (str): The OAuth 2.0 token exchange grant type. + subject_token (str): The OAuth 2.0 token exchange subject token. + subject_token_type (str): The OAuth 2.0 token exchange subject token type. + resource (Optional[str]): The optional OAuth 2.0 token exchange resource field. + audience (Optional[str]): The optional OAuth 2.0 token exchange audience field. + scopes (Optional[Sequence[str]]): The optional list of scopes to use. + requested_token_type (Optional[str]): The optional OAuth 2.0 token exchange requested + token type. + actor_token (Optional[str]): The optional OAuth 2.0 token exchange actor token. + actor_token_type (Optional[str]): The optional OAuth 2.0 token exchange actor token type. + additional_options (Optional[Mapping[str, str]]): The optional additional + non-standard Google specific options. + additional_headers (Optional[Mapping[str, str]]): The optional additional + headers to pass to the token exchange endpoint. + + Returns: + Mapping[str, str]: The token exchange JSON-decoded response data containing + the requested token and its expiration time. + + Raises: + google.auth.exceptions.OAuthError: If the token endpoint returned + an error. + """ + # Initialize request body. + request_body = { + "grant_type": grant_type, + "resource": resource, + "audience": audience, + "scope": " ".join(scopes or []), + "requested_token_type": requested_token_type, + "subject_token": subject_token, + "subject_token_type": subject_token_type, + "actor_token": actor_token, + "actor_token_type": actor_token_type, + "options": None, + } + # Add additional non-standard options. + if additional_options: + request_body["options"] = urllib.parse.quote(json.dumps(additional_options)) + # Remove empty fields in request body. + for k, v in dict(request_body).items(): + if v is None or v == "": + del request_body[k] + + return self._make_request(request, additional_headers, request_body) + + def refresh_token(self, request, refresh_token): + """Exchanges a refresh token for an access token based on the + RFC6749 spec. + + Args: + request (google.auth.transport.Request): A callable used to make + HTTP requests. + subject_token (str): The OAuth 2.0 refresh token. + """ + + return self._make_request( + request, + None, + {"grant_type": "refresh_token", "refresh_token": refresh_token}, + ) + + def revoke_token(self, request, token, token_type_hint, revoke_url): + """Revokes the provided token based on the RFC7009 spec. + + Args: + request (google.auth.transport.Request): A callable used to make + HTTP requests. + token (str): The OAuth 2.0 token to revoke. + token_type_hint (str): Hint for the type of token being revoked. + revoke_url (str): The STS endpoint URL for revoking tokens. + + Raises: + google.auth.exceptions.OAuthError: If the token revocation endpoint + returned an error. + """ + request_body = {"token": token} + if token_type_hint: + request_body["token_type_hint"] = token_type_hint + + return self._make_request(request, None, request_body, revoke_url) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/utils.py b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d72ff1916631f17773d63244eac0179b9109c8d1 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/utils.py @@ -0,0 +1,168 @@ +# Copyright 2020 Google LLC +# +# Licensed 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. + +"""OAuth 2.0 Utilities. + +This module provides implementations for various OAuth 2.0 utilities. +This includes `OAuth error handling`_ and +`Client authentication for OAuth flows`_. + +OAuth error handling +-------------------- +This will define interfaces for handling OAuth related error responses as +stated in `RFC 6749 section 5.2`_. +This will include a common function to convert these HTTP error responses to a +:class:`google.auth.exceptions.OAuthError` exception. + + +Client authentication for OAuth flows +------------------------------------- +We introduce an interface for defining client authentication credentials based +on `RFC 6749 section 2.3.1`_. This will expose the following +capabilities: + + * Ability to support basic authentication via request header. + * Ability to support bearer token authentication via request header. + * Ability to support client ID / secret authentication via request body. + +.. _RFC 6749 section 2.3.1: https://tools.ietf.org/html/rfc6749#section-2.3.1 +.. _RFC 6749 section 5.2: https://tools.ietf.org/html/rfc6749#section-5.2 +""" + +import abc +import base64 +import enum +import json + +from google.auth import exceptions + + +# OAuth client authentication based on +# https://tools.ietf.org/html/rfc6749#section-2.3. +class ClientAuthType(enum.Enum): + basic = 1 + request_body = 2 + + +class ClientAuthentication(object): + """Defines the client authentication credentials for basic and request-body + types based on https://tools.ietf.org/html/rfc6749#section-2.3.1. + """ + + def __init__(self, client_auth_type, client_id, client_secret=None): + """Instantiates a client authentication object containing the client ID + and secret credentials for basic and response-body auth. + + Args: + client_auth_type (google.oauth2.oauth_utils.ClientAuthType): The + client authentication type. + client_id (str): The client ID. + client_secret (Optional[str]): The client secret. + """ + self.client_auth_type = client_auth_type + self.client_id = client_id + self.client_secret = client_secret + + +class OAuthClientAuthHandler(metaclass=abc.ABCMeta): + """Abstract class for handling client authentication in OAuth-based + operations. + """ + + def __init__(self, client_authentication=None): + """Instantiates an OAuth client authentication handler. + + Args: + client_authentication (Optional[google.oauth2.utils.ClientAuthentication]): + The OAuth client authentication credentials if available. + """ + super(OAuthClientAuthHandler, self).__init__() + self._client_authentication = client_authentication + + def apply_client_authentication_options( + self, headers, request_body=None, bearer_token=None + ): + """Applies client authentication on the OAuth request's headers or POST + body. + + Args: + headers (Mapping[str, str]): The HTTP request header. + request_body (Optional[Mapping[str, str]]): The HTTP request body + dictionary. For requests that do not support request body, this + is None and will be ignored. + bearer_token (Optional[str]): The optional bearer token. + """ + # Inject authenticated header. + self._inject_authenticated_headers(headers, bearer_token) + # Inject authenticated request body. + if bearer_token is None: + self._inject_authenticated_request_body(request_body) + + def _inject_authenticated_headers(self, headers, bearer_token=None): + if bearer_token is not None: + headers["Authorization"] = "Bearer %s" % bearer_token + elif ( + self._client_authentication is not None + and self._client_authentication.client_auth_type is ClientAuthType.basic + ): + username = self._client_authentication.client_id + password = self._client_authentication.client_secret or "" + + credentials = base64.b64encode( + ("%s:%s" % (username, password)).encode() + ).decode() + headers["Authorization"] = "Basic %s" % credentials + + def _inject_authenticated_request_body(self, request_body): + if ( + self._client_authentication is not None + and self._client_authentication.client_auth_type + is ClientAuthType.request_body + ): + if request_body is None: + raise exceptions.OAuthError( + "HTTP request does not support request-body" + ) + else: + request_body["client_id"] = self._client_authentication.client_id + request_body["client_secret"] = ( + self._client_authentication.client_secret or "" + ) + + +def handle_error_response(response_body): + """Translates an error response from an OAuth operation into an + OAuthError exception. + + Args: + response_body (str): The decoded response data. + + Raises: + google.auth.exceptions.OAuthError + """ + try: + error_components = [] + error_data = json.loads(response_body) + + error_components.append("Error code {}".format(error_data["error"])) + if "error_description" in error_data: + error_components.append(": {}".format(error_data["error_description"])) + if "error_uri" in error_data: + error_components.append(" - {}".format(error_data["error_uri"])) + error_details = "".join(error_components) + # If no details could be extracted, use the response data. + except (KeyError, ValueError): + error_details = response_body + + raise exceptions.OAuthError(error_details, response_body) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/webauthn_handler.py b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/webauthn_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..d46832dfd6332394938bcc830232676cef2b9770 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/webauthn_handler.py @@ -0,0 +1,82 @@ +import abc +import os +import struct +import subprocess + +from google.auth import exceptions +from google.oauth2.webauthn_types import GetRequest, GetResponse + + +class WebAuthnHandler(abc.ABC): + @abc.abstractmethod + def is_available(self) -> bool: + """Check whether this WebAuthn handler is available""" + raise NotImplementedError("is_available method must be implemented") + + @abc.abstractmethod + def get(self, get_request: GetRequest) -> GetResponse: + """WebAuthn get (assertion)""" + raise NotImplementedError("get method must be implemented") + + +class PluginHandler(WebAuthnHandler): + """Offloads WebAuthn get request to a pluggable command-line tool. + + Offloads WebAuthn get to a plugin which takes the form of a + command-line tool. The command-line tool is configurable via the + PluginHandler._ENV_VAR environment variable. + + The WebAuthn plugin should implement the following interface: + + Communication occurs over stdin/stdout, and messages are both sent and + received in the form: + + [4 bytes - payload size (little-endian)][variable bytes - json payload] + """ + + _ENV_VAR = "GOOGLE_AUTH_WEBAUTHN_PLUGIN" + + def is_available(self) -> bool: + try: + self._find_plugin() + except Exception: + return False + else: + return True + + def get(self, get_request: GetRequest) -> GetResponse: + request_json = get_request.to_json() + cmd = self._find_plugin() + response_json = self._call_plugin(cmd, request_json) + return GetResponse.from_json(response_json) + + def _call_plugin(self, cmd: str, input_json: str) -> str: + # Calculate length of input + input_length = len(input_json) + length_bytes_le = struct.pack(" str: + plugin_cmd = os.environ.get(PluginHandler._ENV_VAR) + if plugin_cmd is None: + raise exceptions.InvalidResource( + "{} env var is not set".format(PluginHandler._ENV_VAR) + ) + return plugin_cmd diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/webauthn_handler_factory.py b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/webauthn_handler_factory.py new file mode 100644 index 0000000000000000000000000000000000000000..184329fed7e921cff1003a91ddd4c9819618a065 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/webauthn_handler_factory.py @@ -0,0 +1,16 @@ +from typing import List, Optional + +from google.oauth2.webauthn_handler import PluginHandler, WebAuthnHandler + + +class WebauthnHandlerFactory: + handlers: List[WebAuthnHandler] + + def __init__(self): + self.handlers = [PluginHandler()] + + def get_handler(self) -> Optional[WebAuthnHandler]: + for handler in self.handlers: + if handler.is_available(): + return handler + return None diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/webauthn_types.py b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/webauthn_types.py new file mode 100644 index 0000000000000000000000000000000000000000..24e984f3d33636259b60819fd372207267fd6ce4 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/oauth2/webauthn_types.py @@ -0,0 +1,156 @@ +from dataclasses import dataclass +import json +from typing import Any, Dict, List, Optional + +from google.auth import exceptions + + +@dataclass(frozen=True) +class PublicKeyCredentialDescriptor: + """Descriptor for a security key based credential. + + https://www.w3.org/TR/webauthn-3/#dictionary-credential-descriptor + + Args: + id: credential id (key handle). + transports: <'usb'|'nfc'|'ble'|'internal'> List of supported transports. + """ + + id: str + transports: Optional[List[str]] = None + + def to_dict(self): + cred = {"type": "public-key", "id": self.id} + if self.transports: + cred["transports"] = self.transports + return cred + + +@dataclass +class AuthenticationExtensionsClientInputs: + """Client extensions inputs for WebAuthn extensions. + + Args: + appid: app id that can be asserted with in addition to rpid. + https://www.w3.org/TR/webauthn-3/#sctn-appid-extension + """ + + appid: Optional[str] = None + + def to_dict(self): + extensions = {} + if self.appid: + extensions["appid"] = self.appid + return extensions + + +@dataclass +class GetRequest: + """WebAuthn get request + + Args: + origin: Origin where the WebAuthn get assertion takes place. + rpid: Relying Party ID. + challenge: raw challenge. + timeout_ms: Timeout number in millisecond. + allow_credentials: List of allowed credentials. + user_verification: <'required'|'preferred'|'discouraged'> User verification requirement. + extensions: WebAuthn authentication extensions inputs. + """ + + origin: str + rpid: str + challenge: str + timeout_ms: Optional[int] = None + allow_credentials: Optional[List[PublicKeyCredentialDescriptor]] = None + user_verification: Optional[str] = None + extensions: Optional[AuthenticationExtensionsClientInputs] = None + + def to_json(self) -> str: + req_options: Dict[str, Any] = {"rpId": self.rpid, "challenge": self.challenge} + if self.timeout_ms: + req_options["timeout"] = self.timeout_ms + if self.allow_credentials: + req_options["allowCredentials"] = [ + c.to_dict() for c in self.allow_credentials + ] + if self.user_verification: + req_options["userVerification"] = self.user_verification + if self.extensions: + req_options["extensions"] = self.extensions.to_dict() + return json.dumps( + {"type": "get", "origin": self.origin, "requestData": req_options} + ) + + +@dataclass(frozen=True) +class AuthenticatorAssertionResponse: + """Authenticator response to a WebAuthn get (assertion) request. + + https://www.w3.org/TR/webauthn-3/#authenticatorassertionresponse + + Args: + client_data_json: client data JSON. + authenticator_data: authenticator data. + signature: signature. + user_handle: user handle. + """ + + client_data_json: str + authenticator_data: str + signature: str + user_handle: Optional[str] + + +@dataclass(frozen=True) +class GetResponse: + """WebAuthn get (assertion) response. + + Args: + id: credential id (key handle). + response: The authenticator assertion response. + authenticator_attachment: <'cross-platform'|'platform'> The attachment status of the authenticator. + client_extension_results: WebAuthn authentication extensions output results in a dictionary. + """ + + id: str + response: AuthenticatorAssertionResponse + authenticator_attachment: Optional[str] + client_extension_results: Optional[Dict] + + @staticmethod + def from_json(json_str: str): + """Verify and construct GetResponse from a JSON string.""" + try: + resp_json = json.loads(json_str) + except ValueError: + raise exceptions.MalformedError("Invalid Get JSON response") + if resp_json.get("type") != "getResponse": + raise exceptions.MalformedError( + "Invalid Get response type: {}".format(resp_json.get("type")) + ) + pk_cred = resp_json.get("responseData") + if pk_cred is None: + if resp_json.get("error"): + raise exceptions.ReauthFailError( + "WebAuthn.get failure: {}".format(resp_json["error"]) + ) + else: + raise exceptions.MalformedError("Get response is empty") + if pk_cred.get("type") != "public-key": + raise exceptions.MalformedError( + "Invalid credential type: {}".format(pk_cred.get("type")) + ) + assertion_json = pk_cred["response"] + assertion_resp = AuthenticatorAssertionResponse( + client_data_json=assertion_json["clientDataJSON"], + authenticator_data=assertion_json["authenticatorData"], + signature=assertion_json["signature"], + user_handle=assertion_json.get("userHandle"), + ) + return GetResponse( + id=pk_cred["id"], + response=assertion_resp, + authenticator_attachment=pk_cred.get("authenticatorAttachment"), + client_extension_results=pk_cred.get("clientExtensionResults"), + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1d5d631295ae6e3c411dc3654ea496f6affaa258 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__init__.py @@ -0,0 +1,10 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +# Copyright 2007 Google Inc. All Rights Reserved. + +__version__ = '6.33.6' diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/__init__.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13c8fa4b93f332f2590226ffd07529591bd6c81b Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/__init__.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/any_pb2.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/any_pb2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..59cc119a961cfc13795a08d57cb6439291984de9 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/any_pb2.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/descriptor.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/descriptor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f46c6a1c2e878bdbf0c3f26e6b6a8fd7fc8c0d13 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/descriptor.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/descriptor_database.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/descriptor_database.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f00d48e3e45401c3680936d6fd3c746e585a490b Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/descriptor_database.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/descriptor_pb2.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/descriptor_pb2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..def202fda268cf85e8172ff84a829dbd6b66a29b --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/descriptor_pb2.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b128412ab233c41674040546116f36d86e6c2453deead72f41867bb058947c4e +size 343671 diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/descriptor_pool.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/descriptor_pool.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb21a98a5d320fc976a531e9aae67ab6035f2901 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/descriptor_pool.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/duration_pb2.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/duration_pb2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..08c4067532b5b2dfa8e1bbbb3caa4e316b14ffbb Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/duration_pb2.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/empty_pb2.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/empty_pb2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d22c138db4d9d77b320198ba2fce2ed4041a2c8 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/empty_pb2.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/field_mask_pb2.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/field_mask_pb2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9c0a7cf32854bfbd8cc32a63b4a5689611cd8221 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/field_mask_pb2.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/json_format.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/json_format.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a431b2450658434b22860107ae40dd8d83319978 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/json_format.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/message.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/message.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..77dac4745dfa2fa2999ed75a2e30b93a1f6c44da Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/message.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/message_factory.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/message_factory.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38f90e0dd3bbfc8fbf7ce0e7faecb54d55fe5c2b Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/message_factory.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/reflection.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/reflection.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a5c7cfe56ffe73c512a1abc31f567716338c4922 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/reflection.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/runtime_version.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/runtime_version.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7670ecaca160740bea482503f725e3e2ce8bdbd4 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/runtime_version.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/struct_pb2.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/struct_pb2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0378f12b88ed8e791c26ca8b6dd6fa237429de3a Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/struct_pb2.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/symbol_database.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/symbol_database.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c32cdda265a31ac363c0e3b95ab03c394f649b29 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/symbol_database.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/text_encoding.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/text_encoding.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db902ada7bb935a71fab7ab48c4f787eb4ab1959 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/text_encoding.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/text_format.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/text_format.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b7c558837afda16dd922116132b5a82e086fecf3 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/text_format.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/timestamp_pb2.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/timestamp_pb2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2a4cd70ce5328b102a99feffe39a2c063c6f550 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/timestamp_pb2.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/unknown_fields.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/unknown_fields.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b0f024723df146f9fc0cba4cb42a23945e26b3c Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/unknown_fields.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/wrappers_pb2.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/wrappers_pb2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c5d76fc6466b72110be83d82fdb81baa18c2289 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/__pycache__/wrappers_pb2.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/any.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/any.py new file mode 100644 index 0000000000000000000000000000000000000000..acf37cf24c700f58a1a1d3080a9ddfd6403aa993 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/any.py @@ -0,0 +1,53 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""Contains the Any helper APIs.""" + +from typing import Optional, TypeVar + +from google.protobuf import descriptor +from google.protobuf.message import Message + +from google.protobuf.any_pb2 import Any + + +_MessageT = TypeVar('_MessageT', bound=Message) + + +def pack( + msg: Message, + type_url_prefix: Optional[str] = 'type.googleapis.com/', + deterministic: Optional[bool] = None, +) -> Any: + any_msg = Any() + any_msg.Pack( + msg=msg, type_url_prefix=type_url_prefix, deterministic=deterministic + ) + return any_msg + + +def unpack(any_msg: Any, msg: Message) -> bool: + return any_msg.Unpack(msg=msg) + + +def unpack_as(any_msg: Any, message_type: type[_MessageT]) -> _MessageT: + unpacked = message_type() + if unpack(any_msg, unpacked): + return unpacked + else: + raise TypeError( + f'Attempted to unpack {type_name(any_msg)} to' + f' {message_type.__qualname__}' + ) + + +def type_name(any_msg: Any) -> str: + return any_msg.TypeName() + + +def is_type(any_msg: Any, des: descriptor.Descriptor) -> bool: + return any_msg.Is(des) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/any_pb2.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/any_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..41fb5798cdef5ab4c3102f6cf4fc36b2675e4ed9 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/any_pb2.py @@ -0,0 +1,37 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# NO CHECKED-IN PROTOBUF GENCODE +# source: google/protobuf/any.proto +# Protobuf Python Version: 6.33.6 +"""Generated protocol buffer code.""" +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import runtime_version as _runtime_version +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder +_runtime_version.ValidateProtobufRuntimeVersion( + _runtime_version.Domain.PUBLIC, + 6, + 33, + 6, + '', + 'google/protobuf/any.proto' +) +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x19google/protobuf/any.proto\x12\x0fgoogle.protobuf\"6\n\x03\x41ny\x12\x19\n\x08type_url\x18\x01 \x01(\tR\x07typeUrl\x12\x14\n\x05value\x18\x02 \x01(\x0cR\x05valueBv\n\x13\x63om.google.protobufB\x08\x41nyProtoP\x01Z,google.golang.org/protobuf/types/known/anypb\xa2\x02\x03GPB\xaa\x02\x1eGoogle.Protobuf.WellKnownTypesb\x06proto3') + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.any_pb2', _globals) +if not _descriptor._USE_C_DESCRIPTORS: + _globals['DESCRIPTOR']._loaded_options = None + _globals['DESCRIPTOR']._serialized_options = b'\n\023com.google.protobufB\010AnyProtoP\001Z,google.golang.org/protobuf/types/known/anypb\242\002\003GPB\252\002\036Google.Protobuf.WellKnownTypes' + _globals['_ANY']._serialized_start=46 + _globals['_ANY']._serialized_end=100 +# @@protoc_insertion_point(module_scope) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/api_pb2.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/api_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..1274ad89fc39f61bb70fa923a7c74bc891c0cfa0 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/api_pb2.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# NO CHECKED-IN PROTOBUF GENCODE +# source: google/protobuf/api.proto +# Protobuf Python Version: 6.33.6 +"""Generated protocol buffer code.""" +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import runtime_version as _runtime_version +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder +_runtime_version.ValidateProtobufRuntimeVersion( + _runtime_version.Domain.PUBLIC, + 6, + 33, + 6, + '', + 'google/protobuf/api.proto' +) +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.protobuf import source_context_pb2 as google_dot_protobuf_dot_source__context__pb2 +from google.protobuf import type_pb2 as google_dot_protobuf_dot_type__pb2 + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x19google/protobuf/api.proto\x12\x0fgoogle.protobuf\x1a$google/protobuf/source_context.proto\x1a\x1agoogle/protobuf/type.proto\"\xdb\x02\n\x03\x41pi\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\x12\x31\n\x07methods\x18\x02 \x03(\x0b\x32\x17.google.protobuf.MethodR\x07methods\x12\x31\n\x07options\x18\x03 \x03(\x0b\x32\x17.google.protobuf.OptionR\x07options\x12\x18\n\x07version\x18\x04 \x01(\tR\x07version\x12\x45\n\x0esource_context\x18\x05 \x01(\x0b\x32\x1e.google.protobuf.SourceContextR\rsourceContext\x12.\n\x06mixins\x18\x06 \x03(\x0b\x32\x16.google.protobuf.MixinR\x06mixins\x12/\n\x06syntax\x18\x07 \x01(\x0e\x32\x17.google.protobuf.SyntaxR\x06syntax\x12\x18\n\x07\x65\x64ition\x18\x08 \x01(\tR\x07\x65\x64ition\"\xd4\x02\n\x06Method\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\x12(\n\x10request_type_url\x18\x02 \x01(\tR\x0erequestTypeUrl\x12+\n\x11request_streaming\x18\x03 \x01(\x08R\x10requestStreaming\x12*\n\x11response_type_url\x18\x04 \x01(\tR\x0fresponseTypeUrl\x12-\n\x12response_streaming\x18\x05 \x01(\x08R\x11responseStreaming\x12\x31\n\x07options\x18\x06 \x03(\x0b\x32\x17.google.protobuf.OptionR\x07options\x12\x33\n\x06syntax\x18\x07 \x01(\x0e\x32\x17.google.protobuf.SyntaxB\x02\x18\x01R\x06syntax\x12\x1c\n\x07\x65\x64ition\x18\x08 \x01(\tB\x02\x18\x01R\x07\x65\x64ition\"/\n\x05Mixin\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\x12\x12\n\x04root\x18\x02 \x01(\tR\x04rootBv\n\x13\x63om.google.protobufB\x08\x41piProtoP\x01Z,google.golang.org/protobuf/types/known/apipb\xa2\x02\x03GPB\xaa\x02\x1eGoogle.Protobuf.WellKnownTypesb\x06proto3') + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.api_pb2', _globals) +if not _descriptor._USE_C_DESCRIPTORS: + _globals['DESCRIPTOR']._loaded_options = None + _globals['DESCRIPTOR']._serialized_options = b'\n\023com.google.protobufB\010ApiProtoP\001Z,google.golang.org/protobuf/types/known/apipb\242\002\003GPB\252\002\036Google.Protobuf.WellKnownTypes' + _globals['_METHOD'].fields_by_name['syntax']._loaded_options = None + _globals['_METHOD'].fields_by_name['syntax']._serialized_options = b'\030\001' + _globals['_METHOD'].fields_by_name['edition']._loaded_options = None + _globals['_METHOD'].fields_by_name['edition']._serialized_options = b'\030\001' + _globals['_API']._serialized_start=113 + _globals['_API']._serialized_end=460 + _globals['_METHOD']._serialized_start=463 + _globals['_METHOD']._serialized_end=803 + _globals['_MIXIN']._serialized_start=805 + _globals['_MIXIN']._serialized_end=852 +# @@protoc_insertion_point(module_scope) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/compiler/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/compiler/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/compiler/plugin_pb2.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/compiler/plugin_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..8d882dedd5e97e10020d3cee64240420398b61bd --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/compiler/plugin_pb2.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# NO CHECKED-IN PROTOBUF GENCODE +# source: google/protobuf/compiler/plugin.proto +# Protobuf Python Version: 6.33.6 +"""Generated protocol buffer code.""" +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import runtime_version as _runtime_version +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder +_runtime_version.ValidateProtobufRuntimeVersion( + _runtime_version.Domain.PUBLIC, + 6, + 33, + 6, + '', + 'google/protobuf/compiler/plugin.proto' +) +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.protobuf import descriptor_pb2 as google_dot_protobuf_dot_descriptor__pb2 + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n%google/protobuf/compiler/plugin.proto\x12\x18google.protobuf.compiler\x1a google/protobuf/descriptor.proto\"c\n\x07Version\x12\x14\n\x05major\x18\x01 \x01(\x05R\x05major\x12\x14\n\x05minor\x18\x02 \x01(\x05R\x05minor\x12\x14\n\x05patch\x18\x03 \x01(\x05R\x05patch\x12\x16\n\x06suffix\x18\x04 \x01(\tR\x06suffix\"\xcf\x02\n\x14\x43odeGeneratorRequest\x12(\n\x10\x66ile_to_generate\x18\x01 \x03(\tR\x0e\x66ileToGenerate\x12\x1c\n\tparameter\x18\x02 \x01(\tR\tparameter\x12\x43\n\nproto_file\x18\x0f \x03(\x0b\x32$.google.protobuf.FileDescriptorProtoR\tprotoFile\x12\\\n\x17source_file_descriptors\x18\x11 \x03(\x0b\x32$.google.protobuf.FileDescriptorProtoR\x15sourceFileDescriptors\x12L\n\x10\x63ompiler_version\x18\x03 \x01(\x0b\x32!.google.protobuf.compiler.VersionR\x0f\x63ompilerVersion\"\x85\x04\n\x15\x43odeGeneratorResponse\x12\x14\n\x05\x65rror\x18\x01 \x01(\tR\x05\x65rror\x12-\n\x12supported_features\x18\x02 \x01(\x04R\x11supportedFeatures\x12\'\n\x0fminimum_edition\x18\x03 \x01(\x05R\x0eminimumEdition\x12\'\n\x0fmaximum_edition\x18\x04 \x01(\x05R\x0emaximumEdition\x12H\n\x04\x66ile\x18\x0f \x03(\x0b\x32\x34.google.protobuf.compiler.CodeGeneratorResponse.FileR\x04\x66ile\x1a\xb1\x01\n\x04\x46ile\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\x12\'\n\x0finsertion_point\x18\x02 \x01(\tR\x0einsertionPoint\x12\x18\n\x07\x63ontent\x18\x0f \x01(\tR\x07\x63ontent\x12R\n\x13generated_code_info\x18\x10 \x01(\x0b\x32\".google.protobuf.GeneratedCodeInfoR\x11generatedCodeInfo\"W\n\x07\x46\x65\x61ture\x12\x10\n\x0c\x46\x45\x41TURE_NONE\x10\x00\x12\x1b\n\x17\x46\x45\x41TURE_PROTO3_OPTIONAL\x10\x01\x12\x1d\n\x19\x46\x45\x41TURE_SUPPORTS_EDITIONS\x10\x02\x42r\n\x1c\x63om.google.protobuf.compilerB\x0cPluginProtosZ)google.golang.org/protobuf/types/pluginpb\xaa\x02\x18Google.Protobuf.Compiler') + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.compiler.plugin_pb2', _globals) +if not _descriptor._USE_C_DESCRIPTORS: + _globals['DESCRIPTOR']._loaded_options = None + _globals['DESCRIPTOR']._serialized_options = b'\n\034com.google.protobuf.compilerB\014PluginProtosZ)google.golang.org/protobuf/types/pluginpb\252\002\030Google.Protobuf.Compiler' + _globals['_VERSION']._serialized_start=101 + _globals['_VERSION']._serialized_end=200 + _globals['_CODEGENERATORREQUEST']._serialized_start=203 + _globals['_CODEGENERATORREQUEST']._serialized_end=538 + _globals['_CODEGENERATORRESPONSE']._serialized_start=541 + _globals['_CODEGENERATORRESPONSE']._serialized_end=1058 + _globals['_CODEGENERATORRESPONSE_FILE']._serialized_start=792 + _globals['_CODEGENERATORRESPONSE_FILE']._serialized_end=969 + _globals['_CODEGENERATORRESPONSE_FEATURE']._serialized_start=971 + _globals['_CODEGENERATORRESPONSE_FEATURE']._serialized_end=1058 +# @@protoc_insertion_point(module_scope) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/descriptor.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/descriptor.py new file mode 100644 index 0000000000000000000000000000000000000000..db46ae9f64831150899116d74ffb87a2510f9aa5 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/descriptor.py @@ -0,0 +1,1676 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""Descriptors essentially contain exactly the information found in a .proto + +file, in types that make this information accessible in Python. +""" + +__author__ = 'robinson@google.com (Will Robinson)' + +import abc +import binascii +import os +import threading +import warnings + +from google.protobuf.internal import api_implementation + +_USE_C_DESCRIPTORS = False +if api_implementation.Type() != 'python': + # pylint: disable=protected-access + _message = api_implementation._c_module + # TODO: Remove this import after fix api_implementation + if _message is None: + from google.protobuf.pyext import _message + _USE_C_DESCRIPTORS = True + + +class Error(Exception): + """Base error for this module.""" + + +class TypeTransformationError(Error): + """Error transforming between python proto type and corresponding C++ type.""" + + +if _USE_C_DESCRIPTORS: + # This metaclass allows to override the behavior of code like + # isinstance(my_descriptor, FieldDescriptor) + # and make it return True when the descriptor is an instance of the extension + # type written in C++. + class DescriptorMetaclass(type): + + def __instancecheck__(cls, obj): + if super(DescriptorMetaclass, cls).__instancecheck__(obj): + return True + if isinstance(obj, cls._C_DESCRIPTOR_CLASS): + return True + return False + +else: + # The standard metaclass; nothing changes. + DescriptorMetaclass = abc.ABCMeta + + +class _Lock(object): + """Wrapper class of threading.Lock(), which is allowed by 'with'.""" + + def __new__(cls): + self = object.__new__(cls) + self._lock = threading.Lock() # pylint: disable=protected-access + return self + + def __enter__(self): + self._lock.acquire() + + def __exit__(self, exc_type, exc_value, exc_tb): + self._lock.release() + + +_lock = threading.Lock() + + +def _Deprecated( + name, + alternative='get/find descriptors from generated code or query the descriptor_pool', +): + if _Deprecated.count > 0: + _Deprecated.count -= 1 + warnings.warn( + 'Call to deprecated %s, use %s instead.' % (name, alternative), + category=DeprecationWarning, + stacklevel=3, + ) + + +# These must match the values in descriptor.proto, but we can't use them +# directly because we sometimes need to reference them in feature helpers +# below *during* the build of descriptor.proto. +_FEATURESET_MESSAGE_ENCODING_DELIMITED = 2 +_FEATURESET_FIELD_PRESENCE_IMPLICIT = 2 +_FEATURESET_FIELD_PRESENCE_LEGACY_REQUIRED = 3 +_FEATURESET_REPEATED_FIELD_ENCODING_PACKED = 1 +_FEATURESET_ENUM_TYPE_CLOSED = 2 + +# Deprecated warnings will print 100 times at most which should be enough for +# users to notice and do not cause timeout. +_Deprecated.count = 100 + + +_internal_create_key = object() + + +class DescriptorBase(metaclass=DescriptorMetaclass): + """Descriptors base class. + + This class is the base of all descriptor classes. It provides common options + related functionality. + + Attributes: + has_options: True if the descriptor has non-default options. Usually it is + not necessary to read this -- just call GetOptions() which will happily + return the default instance. However, it's sometimes useful for + efficiency, and also useful inside the protobuf implementation to avoid + some bootstrapping issues. + file (FileDescriptor): Reference to file info. + """ + + if _USE_C_DESCRIPTORS: + # The class, or tuple of classes, that are considered as "virtual + # subclasses" of this descriptor class. + _C_DESCRIPTOR_CLASS = () + + def __init__(self, file, options, serialized_options, options_class_name): + """Initialize the descriptor given its options message and the name of the + + class of the options message. The name of the class is required in case + the options message is None and has to be created. + """ + self._features = None + self.file = file + self._original_options = options + # These two fields are duplicated as a compatibility shim for old gencode + # that resets them. In 26.x (cl/580304039) we renamed _options to, + # _loaded_options breaking backwards compatibility. + self._options = self._loaded_options = None + self._options_class_name = options_class_name + self._serialized_options = serialized_options + + # Does this descriptor have non-default options? + self.has_options = (self._original_options is not None) or ( + self._serialized_options is not None + ) + + @property + @abc.abstractmethod + def _parent(self): + pass + + def _InferLegacyFeatures(self, edition, options, features): + """Infers features from proto2/proto3 syntax so that editions logic can be used everywhere. + + Args: + edition: The edition to infer features for. + options: The options for this descriptor that are being processed. + features: The feature set object to modify with inferred features. + """ + pass + + def _GetFeatures(self): + if not self._features: + self._LazyLoadOptions() + return self._features + + def _ResolveFeatures(self, edition, raw_options): + """Resolves features from the raw options of this descriptor. + + Args: + edition: The edition to use for feature defaults. + raw_options: The options for this descriptor that are being processed. + + Returns: + A fully resolved feature set for making runtime decisions. + """ + # pylint: disable=g-import-not-at-top + from google.protobuf import descriptor_pb2 + + if self._parent: + features = descriptor_pb2.FeatureSet() + features.CopyFrom(self._parent._GetFeatures()) + else: + features = self.file.pool._CreateDefaultFeatures(edition) + unresolved = descriptor_pb2.FeatureSet() + unresolved.CopyFrom(raw_options.features) + self._InferLegacyFeatures(edition, raw_options, unresolved) + features.MergeFrom(unresolved) + + # Use the feature cache to reduce memory bloat. + return self.file.pool._InternFeatures(features) + + def _LazyLoadOptions(self): + """Lazily initializes descriptor options towards the end of the build.""" + if self._options and self._loaded_options == self._options: + # If neither has been reset by gencode, use the cache. + return + + # pylint: disable=g-import-not-at-top + from google.protobuf import descriptor_pb2 + + if not hasattr(descriptor_pb2, self._options_class_name): + raise RuntimeError( + 'Unknown options class name %s!' % self._options_class_name + ) + options_class = getattr(descriptor_pb2, self._options_class_name) + features = None + edition = self.file._edition + + if not self.has_options: + if not self._features: + features = self._ResolveFeatures( + descriptor_pb2.Edition.Value(edition), options_class() + ) + with _lock: + self._options = self._loaded_options = options_class() + if not self._features: + self._features = features + else: + if not self._serialized_options: + options = self._original_options + else: + options = _ParseOptions(options_class(), self._serialized_options) + + if not self._features: + features = self._ResolveFeatures( + descriptor_pb2.Edition.Value(edition), options + ) + with _lock: + self._options = self._loaded_options = options + if not self._features: + self._features = features + if options.HasField('features'): + options.ClearField('features') + if not options.SerializeToString(): + self._options = self._loaded_options = options_class() + self.has_options = False + + def GetOptions(self): + """Retrieves descriptor options. + + Returns: + The options set on this descriptor. + """ + # If either has been reset by gencode, reload options. + if not self._options or not self._loaded_options: + self._LazyLoadOptions() + return self._options + + +class _NestedDescriptorBase(DescriptorBase): + """Common class for descriptors that can be nested.""" + + def __init__( + self, + options, + options_class_name, + name, + full_name, + file, + containing_type, + serialized_start=None, + serialized_end=None, + serialized_options=None, + ): + """Constructor. + + Args: + options: Protocol message options or None to use default message options. + options_class_name (str): The class name of the above options. + name (str): Name of this protocol message type. + full_name (str): Fully-qualified name of this protocol message type, which + will include protocol "package" name and the name of any enclosing + types. + containing_type: if provided, this is a nested descriptor, with this + descriptor as parent, otherwise None. + serialized_start: The start index (inclusive) in block in the + file.serialized_pb that describes this descriptor. + serialized_end: The end index (exclusive) in block in the + file.serialized_pb that describes this descriptor. + serialized_options: Protocol message serialized options or None. + """ + super(_NestedDescriptorBase, self).__init__( + file, options, serialized_options, options_class_name + ) + + self.name = name + # TODO: Add function to calculate full_name instead of having it in + # memory? + self.full_name = full_name + self.containing_type = containing_type + + self._serialized_start = serialized_start + self._serialized_end = serialized_end + + def CopyToProto(self, proto): + """Copies this to the matching proto in descriptor_pb2. + + Args: + proto: An empty proto instance from descriptor_pb2. + + Raises: + Error: If self couldn't be serialized, due to to few constructor + arguments. + """ + if ( + self.file is not None + and self._serialized_start is not None + and self._serialized_end is not None + ): + proto.ParseFromString( + self.file.serialized_pb[self._serialized_start : self._serialized_end] + ) + else: + raise Error('Descriptor does not contain serialization.') + + +class Descriptor(_NestedDescriptorBase): + """Descriptor for a protocol message type. + + Attributes: + name (str): Name of this protocol message type. + full_name (str): Fully-qualified name of this protocol message type, which + will include protocol "package" name and the name of any enclosing + types. + containing_type (Descriptor): Reference to the descriptor of the type + containing us, or None if this is top-level. + fields (list[FieldDescriptor]): Field descriptors for all fields in this + type. + fields_by_number (dict(int, FieldDescriptor)): Same + :class:`FieldDescriptor` objects as in :attr:`fields`, but indexed by + "number" attribute in each FieldDescriptor. + fields_by_name (dict(str, FieldDescriptor)): Same :class:`FieldDescriptor` + objects as in :attr:`fields`, but indexed by "name" attribute in each + :class:`FieldDescriptor`. + nested_types (list[Descriptor]): Descriptor references for all protocol + message types nested within this one. + nested_types_by_name (dict(str, Descriptor)): Same Descriptor objects as + in :attr:`nested_types`, but indexed by "name" attribute in each + Descriptor. + enum_types (list[EnumDescriptor]): :class:`EnumDescriptor` references for + all enums contained within this type. + enum_types_by_name (dict(str, EnumDescriptor)): Same + :class:`EnumDescriptor` objects as in :attr:`enum_types`, but indexed by + "name" attribute in each EnumDescriptor. + enum_values_by_name (dict(str, EnumValueDescriptor)): Dict mapping from + enum value name to :class:`EnumValueDescriptor` for that value. + extensions (list[FieldDescriptor]): All extensions defined directly within + this message type (NOT within a nested type). + extensions_by_name (dict(str, FieldDescriptor)): Same FieldDescriptor + objects as :attr:`extensions`, but indexed by "name" attribute of each + FieldDescriptor. + is_extendable (bool): Does this type define any extension ranges? + oneofs (list[OneofDescriptor]): The list of descriptors for oneof fields + in this message. + oneofs_by_name (dict(str, OneofDescriptor)): Same objects as in + :attr:`oneofs`, but indexed by "name" attribute. + file (FileDescriptor): Reference to file descriptor. + is_map_entry: If the message type is a map entry. + """ + + if _USE_C_DESCRIPTORS: + _C_DESCRIPTOR_CLASS = _message.Descriptor + + def __new__( + cls, + name=None, + full_name=None, + filename=None, + containing_type=None, + fields=None, + nested_types=None, + enum_types=None, + extensions=None, + options=None, + serialized_options=None, + is_extendable=True, + extension_ranges=None, + oneofs=None, + file=None, # pylint: disable=redefined-builtin + serialized_start=None, + serialized_end=None, + syntax=None, + is_map_entry=False, + create_key=None, + ): + _message.Message._CheckCalledFromGeneratedFile() + return _message.default_pool.FindMessageTypeByName(full_name) + + # NOTE: The file argument redefining a builtin is nothing we can + # fix right now since we don't know how many clients already rely on the + # name of the argument. + def __init__( + self, + name, + full_name, + filename, + containing_type, + fields, + nested_types, + enum_types, + extensions, + options=None, + serialized_options=None, + is_extendable=True, + extension_ranges=None, + oneofs=None, + file=None, + serialized_start=None, + serialized_end=None, # pylint: disable=redefined-builtin + syntax=None, + is_map_entry=False, + create_key=None, + ): + """Arguments to __init__() are as described in the description + + of Descriptor fields above. + + Note that filename is an obsolete argument, that is not used anymore. + Please use file.name to access this as an attribute. + """ + if create_key is not _internal_create_key: + _Deprecated('create function Descriptor()') + + super(Descriptor, self).__init__( + options, + 'MessageOptions', + name, + full_name, + file, + containing_type, + serialized_start=serialized_start, + serialized_end=serialized_end, + serialized_options=serialized_options, + ) + + # We have fields in addition to fields_by_name and fields_by_number, + # so that: + # 1. Clients can index fields by "order in which they're listed." + # 2. Clients can easily iterate over all fields with the terse + # syntax: for f in descriptor.fields: ... + self.fields = fields + for field in self.fields: + field.containing_type = self + field.file = file + self.fields_by_number = dict((f.number, f) for f in fields) + self.fields_by_name = dict((f.name, f) for f in fields) + self._fields_by_camelcase_name = None + + self.nested_types = nested_types + for nested_type in nested_types: + nested_type.containing_type = self + self.nested_types_by_name = dict((t.name, t) for t in nested_types) + + self.enum_types = enum_types + for enum_type in self.enum_types: + enum_type.containing_type = self + self.enum_types_by_name = dict((t.name, t) for t in enum_types) + self.enum_values_by_name = dict( + (v.name, v) for t in enum_types for v in t.values + ) + + self.extensions = extensions + for extension in self.extensions: + extension.extension_scope = self + self.extensions_by_name = dict((f.name, f) for f in extensions) + self.is_extendable = is_extendable + self.extension_ranges = extension_ranges + self.oneofs = oneofs if oneofs is not None else [] + self.oneofs_by_name = dict((o.name, o) for o in self.oneofs) + for oneof in self.oneofs: + oneof.containing_type = self + oneof.file = file + self._is_map_entry = is_map_entry + + @property + def _parent(self): + return self.containing_type or self.file + + @property + def fields_by_camelcase_name(self): + """Same FieldDescriptor objects as in :attr:`fields`, but indexed by + + :attr:`FieldDescriptor.camelcase_name`. + """ + if self._fields_by_camelcase_name is None: + self._fields_by_camelcase_name = dict( + (f.camelcase_name, f) for f in self.fields + ) + return self._fields_by_camelcase_name + + def EnumValueName(self, enum, value): + """Returns the string name of an enum value. + + This is just a small helper method to simplify a common operation. + + Args: + enum: string name of the Enum. + value: int, value of the enum. + + Returns: + string name of the enum value. + + Raises: + KeyError if either the Enum doesn't exist or the value is not a valid + value for the enum. + """ + return self.enum_types_by_name[enum].values_by_number[value].name + + def CopyToProto(self, proto): + """Copies this to a descriptor_pb2.DescriptorProto. + + Args: + proto: An empty descriptor_pb2.DescriptorProto. + """ + # This function is overridden to give a better doc comment. + super(Descriptor, self).CopyToProto(proto) + + +# TODO: We should have aggressive checking here, +# for example: +# * If you specify a repeated field, you should not be allowed +# to specify a default value. +# * [Other examples here as needed]. +# +# TODO: for this and other *Descriptor classes, we +# might also want to lock things down aggressively (e.g., +# prevent clients from setting the attributes). Having +# stronger invariants here in general will reduce the number +# of runtime checks we must do in reflection.py... +class FieldDescriptor(DescriptorBase): + """Descriptor for a single field in a .proto file. + + Attributes: + name (str): Name of this field, exactly as it appears in .proto. + full_name (str): Name of this field, including containing scope. This is + particularly relevant for extensions. + index (int): Dense, 0-indexed index giving the order that this field + textually appears within its message in the .proto file. + number (int): Tag number declared for this field in the .proto file. + type (int): (One of the TYPE_* constants below) Declared type. + cpp_type (int): (One of the CPPTYPE_* constants below) C++ type used to + represent this field. + label (int): (One of the LABEL_* constants below) Tells whether this field + is optional, required, or repeated. + has_default_value (bool): True if this field has a default value defined, + otherwise false. + default_value (Varies): Default value of this field. Only meaningful for + non-repeated scalar fields. Repeated fields should always set this to [], + and non-repeated composite fields should always set this to None. + containing_type (Descriptor): Descriptor of the protocol message type that + contains this field. Set by the Descriptor constructor if we're passed + into one. Somewhat confusingly, for extension fields, this is the + descriptor of the EXTENDED message, not the descriptor of the message + containing this field. (See is_extension and extension_scope below). + message_type (Descriptor): If a composite field, a descriptor of the message + type contained in this field. Otherwise, this is None. + enum_type (EnumDescriptor): If this field contains an enum, a descriptor of + that enum. Otherwise, this is None. + is_extension: True iff this describes an extension field. + extension_scope (Descriptor): Only meaningful if is_extension is True. Gives + the message that immediately contains this extension field. Will be None + iff we're a top-level (file-level) extension field. + options (descriptor_pb2.FieldOptions): Protocol message field options or + None to use default field options. + containing_oneof (OneofDescriptor): If the field is a member of a oneof + union, contains its descriptor. Otherwise, None. + file (FileDescriptor): Reference to file descriptor. + """ + + # Must be consistent with C++ FieldDescriptor::Type enum in + # descriptor.h. + # + # TODO: Find a way to eliminate this repetition. + TYPE_DOUBLE = 1 + TYPE_FLOAT = 2 + TYPE_INT64 = 3 + TYPE_UINT64 = 4 + TYPE_INT32 = 5 + TYPE_FIXED64 = 6 + TYPE_FIXED32 = 7 + TYPE_BOOL = 8 + TYPE_STRING = 9 + TYPE_GROUP = 10 + TYPE_MESSAGE = 11 + TYPE_BYTES = 12 + TYPE_UINT32 = 13 + TYPE_ENUM = 14 + TYPE_SFIXED32 = 15 + TYPE_SFIXED64 = 16 + TYPE_SINT32 = 17 + TYPE_SINT64 = 18 + MAX_TYPE = 18 + + # Must be consistent with C++ FieldDescriptor::CppType enum in + # descriptor.h. + # + # TODO: Find a way to eliminate this repetition. + CPPTYPE_INT32 = 1 + CPPTYPE_INT64 = 2 + CPPTYPE_UINT32 = 3 + CPPTYPE_UINT64 = 4 + CPPTYPE_DOUBLE = 5 + CPPTYPE_FLOAT = 6 + CPPTYPE_BOOL = 7 + CPPTYPE_ENUM = 8 + CPPTYPE_STRING = 9 + CPPTYPE_MESSAGE = 10 + MAX_CPPTYPE = 10 + + _PYTHON_TO_CPP_PROTO_TYPE_MAP = { + TYPE_DOUBLE: CPPTYPE_DOUBLE, + TYPE_FLOAT: CPPTYPE_FLOAT, + TYPE_ENUM: CPPTYPE_ENUM, + TYPE_INT64: CPPTYPE_INT64, + TYPE_SINT64: CPPTYPE_INT64, + TYPE_SFIXED64: CPPTYPE_INT64, + TYPE_UINT64: CPPTYPE_UINT64, + TYPE_FIXED64: CPPTYPE_UINT64, + TYPE_INT32: CPPTYPE_INT32, + TYPE_SFIXED32: CPPTYPE_INT32, + TYPE_SINT32: CPPTYPE_INT32, + TYPE_UINT32: CPPTYPE_UINT32, + TYPE_FIXED32: CPPTYPE_UINT32, + TYPE_BYTES: CPPTYPE_STRING, + TYPE_STRING: CPPTYPE_STRING, + TYPE_BOOL: CPPTYPE_BOOL, + TYPE_MESSAGE: CPPTYPE_MESSAGE, + TYPE_GROUP: CPPTYPE_MESSAGE, + } + + # Must be consistent with C++ FieldDescriptor::Label enum in + # descriptor.h. + # + # TODO: Find a way to eliminate this repetition. + LABEL_OPTIONAL = 1 + LABEL_REQUIRED = 2 + LABEL_REPEATED = 3 + MAX_LABEL = 3 + + # Must be consistent with C++ constants kMaxNumber, kFirstReservedNumber, + # and kLastReservedNumber in descriptor.h + MAX_FIELD_NUMBER = (1 << 29) - 1 + FIRST_RESERVED_FIELD_NUMBER = 19000 + LAST_RESERVED_FIELD_NUMBER = 19999 + + if _USE_C_DESCRIPTORS: + _C_DESCRIPTOR_CLASS = _message.FieldDescriptor + + def __new__( + cls, + name, + full_name, + index, + number, + type, + cpp_type, + label, + default_value, + message_type, + enum_type, + containing_type, + is_extension, + extension_scope, + options=None, + serialized_options=None, + has_default_value=True, + containing_oneof=None, + json_name=None, + file=None, + create_key=None, + ): # pylint: disable=redefined-builtin + _message.Message._CheckCalledFromGeneratedFile() + if is_extension: + return _message.default_pool.FindExtensionByName(full_name) + else: + return _message.default_pool.FindFieldByName(full_name) + + def __init__( + self, + name, + full_name, + index, + number, + type, + cpp_type, + label, + default_value, + message_type, + enum_type, + containing_type, + is_extension, + extension_scope, + options=None, + serialized_options=None, + has_default_value=True, + containing_oneof=None, + json_name=None, + file=None, + create_key=None, + ): # pylint: disable=redefined-builtin + """The arguments are as described in the description of FieldDescriptor + + attributes above. + + Note that containing_type may be None, and may be set later if necessary + (to deal with circular references between message types, for example). + Likewise for extension_scope. + """ + if create_key is not _internal_create_key: + _Deprecated('create function FieldDescriptor()') + + super(FieldDescriptor, self).__init__( + file, options, serialized_options, 'FieldOptions' + ) + self.name = name + self.full_name = full_name + self._camelcase_name = None + if json_name is None: + self.json_name = _ToJsonName(name) + else: + self.json_name = json_name + self.index = index + self.number = number + self._type = type + self.cpp_type = cpp_type + self._label = label + self.has_default_value = has_default_value + self.default_value = default_value + self.containing_type = containing_type + self.message_type = message_type + self.enum_type = enum_type + self.is_extension = is_extension + self.extension_scope = extension_scope + self.containing_oneof = containing_oneof + if api_implementation.Type() == 'python': + self._cdescriptor = None + else: + if is_extension: + self._cdescriptor = _message.default_pool.FindExtensionByName(full_name) + else: + self._cdescriptor = _message.default_pool.FindFieldByName(full_name) + + @property + def _parent(self): + if self.containing_oneof: + return self.containing_oneof + if self.is_extension: + return self.extension_scope or self.file + return self.containing_type + + def _InferLegacyFeatures(self, edition, options, features): + # pylint: disable=g-import-not-at-top + from google.protobuf import descriptor_pb2 + + if edition >= descriptor_pb2.Edition.EDITION_2023: + return + + if self._label == FieldDescriptor.LABEL_REQUIRED: + features.field_presence = ( + descriptor_pb2.FeatureSet.FieldPresence.LEGACY_REQUIRED + ) + + if self._type == FieldDescriptor.TYPE_GROUP: + features.message_encoding = ( + descriptor_pb2.FeatureSet.MessageEncoding.DELIMITED + ) + + if options.HasField('packed'): + features.repeated_field_encoding = ( + descriptor_pb2.FeatureSet.RepeatedFieldEncoding.PACKED + if options.packed + else descriptor_pb2.FeatureSet.RepeatedFieldEncoding.EXPANDED + ) + + @property + def type(self): + if ( + self._GetFeatures().message_encoding + == _FEATURESET_MESSAGE_ENCODING_DELIMITED + and self.message_type + and not self.message_type.GetOptions().map_entry + and not self.containing_type.GetOptions().map_entry + ): + return FieldDescriptor.TYPE_GROUP + return self._type + + @type.setter + def type(self, val): + self._type = val + + @property + def label(self): + _Deprecated('label property', 'is_required or is_repeated properties') + + if ( + self._GetFeatures().field_presence + == _FEATURESET_FIELD_PRESENCE_LEGACY_REQUIRED + ): + return FieldDescriptor.LABEL_REQUIRED + return self._label + + @property + def is_required(self): + """Returns if the field is required.""" + return ( + self._GetFeatures().field_presence + == _FEATURESET_FIELD_PRESENCE_LEGACY_REQUIRED + ) + + @property + def is_repeated(self): + """Returns if the field is repeated.""" + return self._label == FieldDescriptor.LABEL_REPEATED + + @property + def camelcase_name(self): + """Camelcase name of this field. + + Returns: + str: the name in CamelCase. + """ + if self._camelcase_name is None: + self._camelcase_name = _ToCamelCase(self.name) + return self._camelcase_name + + @property + def has_presence(self): + """Whether the field distinguishes between unpopulated and default values. + + Raises: + RuntimeError: singular field that is not linked with message nor file. + """ + if self.is_repeated: + return False + if ( + self.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE + or self.is_extension + or self.containing_oneof + ): + return True + + return ( + self._GetFeatures().field_presence + != _FEATURESET_FIELD_PRESENCE_IMPLICIT + ) + + @property + def is_packed(self): + """Returns if the field is packed.""" + if not self.is_repeated: + return False + field_type = self.type + if ( + field_type == FieldDescriptor.TYPE_STRING + or field_type == FieldDescriptor.TYPE_GROUP + or field_type == FieldDescriptor.TYPE_MESSAGE + or field_type == FieldDescriptor.TYPE_BYTES + ): + return False + + return ( + self._GetFeatures().repeated_field_encoding + == _FEATURESET_REPEATED_FIELD_ENCODING_PACKED + ) + + @staticmethod + def ProtoTypeToCppProtoType(proto_type): + """Converts from a Python proto type to a C++ Proto Type. + + The Python ProtocolBuffer classes specify both the 'Python' datatype and the + 'C++' datatype - and they're not the same. This helper method should + translate from one to another. + + Args: + proto_type: the Python proto type (descriptor.FieldDescriptor.TYPE_*) + + Returns: + int: descriptor.FieldDescriptor.CPPTYPE_*, the C++ type. + Raises: + TypeTransformationError: when the Python proto type isn't known. + """ + try: + return FieldDescriptor._PYTHON_TO_CPP_PROTO_TYPE_MAP[proto_type] + except KeyError: + raise TypeTransformationError('Unknown proto_type: %s' % proto_type) + + +class EnumDescriptor(_NestedDescriptorBase): + """Descriptor for an enum defined in a .proto file. + + Attributes: + name (str): Name of the enum type. + full_name (str): Full name of the type, including package name and any + enclosing type(s). + values (list[EnumValueDescriptor]): List of the values in this enum. + values_by_name (dict(str, EnumValueDescriptor)): Same as :attr:`values`, but + indexed by the "name" field of each EnumValueDescriptor. + values_by_number (dict(int, EnumValueDescriptor)): Same as :attr:`values`, + but indexed by the "number" field of each EnumValueDescriptor. + containing_type (Descriptor): Descriptor of the immediate containing type of + this enum, or None if this is an enum defined at the top level in a .proto + file. Set by Descriptor's constructor if we're passed into one. + file (FileDescriptor): Reference to file descriptor. + options (descriptor_pb2.EnumOptions): Enum options message or None to use + default enum options. + """ + + if _USE_C_DESCRIPTORS: + _C_DESCRIPTOR_CLASS = _message.EnumDescriptor + + def __new__( + cls, + name, + full_name, + filename, + values, + containing_type=None, + options=None, + serialized_options=None, + file=None, # pylint: disable=redefined-builtin + serialized_start=None, + serialized_end=None, + create_key=None, + ): + _message.Message._CheckCalledFromGeneratedFile() + return _message.default_pool.FindEnumTypeByName(full_name) + + def __init__( + self, + name, + full_name, + filename, + values, + containing_type=None, + options=None, + serialized_options=None, + file=None, # pylint: disable=redefined-builtin + serialized_start=None, + serialized_end=None, + create_key=None, + ): + """Arguments are as described in the attribute description above. + + Note that filename is an obsolete argument, that is not used anymore. + Please use file.name to access this as an attribute. + """ + if create_key is not _internal_create_key: + _Deprecated('create function EnumDescriptor()') + + super(EnumDescriptor, self).__init__( + options, + 'EnumOptions', + name, + full_name, + file, + containing_type, + serialized_start=serialized_start, + serialized_end=serialized_end, + serialized_options=serialized_options, + ) + + self.values = values + for value in self.values: + value.file = file + value.type = self + self.values_by_name = dict((v.name, v) for v in values) + # Values are reversed to ensure that the first alias is retained. + self.values_by_number = dict((v.number, v) for v in reversed(values)) + + @property + def _parent(self): + return self.containing_type or self.file + + @property + def is_closed(self): + """Returns true whether this is a "closed" enum. + + This means that it: + - Has a fixed set of values, rather than being equivalent to an int32. + - Encountering values not in this set causes them to be treated as unknown + fields. + - The first value (i.e., the default) may be nonzero. + + WARNING: Some runtimes currently have a quirk where non-closed enums are + treated as closed when used as the type of fields defined in a + `syntax = proto2;` file. This quirk is not present in all runtimes; as of + writing, we know that: + + - C++, Java, and C++-based Python share this quirk. + - UPB and UPB-based Python do not. + - PHP and Ruby treat all enums as open regardless of declaration. + + Care should be taken when using this function to respect the target + runtime's enum handling quirks. + """ + return self._GetFeatures().enum_type == _FEATURESET_ENUM_TYPE_CLOSED + + def CopyToProto(self, proto): + """Copies this to a descriptor_pb2.EnumDescriptorProto. + + Args: + proto (descriptor_pb2.EnumDescriptorProto): An empty descriptor proto. + """ + # This function is overridden to give a better doc comment. + super(EnumDescriptor, self).CopyToProto(proto) + + +class EnumValueDescriptor(DescriptorBase): + """Descriptor for a single value within an enum. + + Attributes: + name (str): Name of this value. + index (int): Dense, 0-indexed index giving the order that this value appears + textually within its enum in the .proto file. + number (int): Actual number assigned to this enum value. + type (EnumDescriptor): :class:`EnumDescriptor` to which this value belongs. + Set by :class:`EnumDescriptor`'s constructor if we're passed into one. + options (descriptor_pb2.EnumValueOptions): Enum value options message or + None to use default enum value options options. + """ + + if _USE_C_DESCRIPTORS: + _C_DESCRIPTOR_CLASS = _message.EnumValueDescriptor + + def __new__( + cls, + name, + index, + number, + type=None, # pylint: disable=redefined-builtin + options=None, + serialized_options=None, + create_key=None, + ): + _message.Message._CheckCalledFromGeneratedFile() + # There is no way we can build a complete EnumValueDescriptor with the + # given parameters (the name of the Enum is not known, for example). + # Fortunately generated files just pass it to the EnumDescriptor() + # constructor, which will ignore it, so returning None is good enough. + return None + + def __init__( + self, + name, + index, + number, + type=None, # pylint: disable=redefined-builtin + options=None, + serialized_options=None, + create_key=None, + ): + """Arguments are as described in the attribute description above.""" + if create_key is not _internal_create_key: + _Deprecated('create function EnumValueDescriptor()') + + super(EnumValueDescriptor, self).__init__( + type.file if type else None, + options, + serialized_options, + 'EnumValueOptions', + ) + self.name = name + self.index = index + self.number = number + self.type = type + + @property + def _parent(self): + return self.type + + +class OneofDescriptor(DescriptorBase): + """Descriptor for a oneof field. + + Attributes: + name (str): Name of the oneof field. + full_name (str): Full name of the oneof field, including package name. + index (int): 0-based index giving the order of the oneof field inside its + containing type. + containing_type (Descriptor): :class:`Descriptor` of the protocol message + type that contains this field. Set by the :class:`Descriptor` constructor + if we're passed into one. + fields (list[FieldDescriptor]): The list of field descriptors this oneof can + contain. + """ + + if _USE_C_DESCRIPTORS: + _C_DESCRIPTOR_CLASS = _message.OneofDescriptor + + def __new__( + cls, + name, + full_name, + index, + containing_type, + fields, + options=None, + serialized_options=None, + create_key=None, + ): + _message.Message._CheckCalledFromGeneratedFile() + return _message.default_pool.FindOneofByName(full_name) + + def __init__( + self, + name, + full_name, + index, + containing_type, + fields, + options=None, + serialized_options=None, + create_key=None, + ): + """Arguments are as described in the attribute description above.""" + if create_key is not _internal_create_key: + _Deprecated('create function OneofDescriptor()') + + super(OneofDescriptor, self).__init__( + containing_type.file if containing_type else None, + options, + serialized_options, + 'OneofOptions', + ) + self.name = name + self.full_name = full_name + self.index = index + self.containing_type = containing_type + self.fields = fields + + @property + def _parent(self): + return self.containing_type + + +class ServiceDescriptor(_NestedDescriptorBase): + """Descriptor for a service. + + Attributes: + name (str): Name of the service. + full_name (str): Full name of the service, including package name. + index (int): 0-indexed index giving the order that this services definition + appears within the .proto file. + methods (list[MethodDescriptor]): List of methods provided by this service. + methods_by_name (dict(str, MethodDescriptor)): Same + :class:`MethodDescriptor` objects as in :attr:`methods_by_name`, but + indexed by "name" attribute in each :class:`MethodDescriptor`. + options (descriptor_pb2.ServiceOptions): Service options message or None to + use default service options. + file (FileDescriptor): Reference to file info. + """ + + if _USE_C_DESCRIPTORS: + _C_DESCRIPTOR_CLASS = _message.ServiceDescriptor + + def __new__( + cls, + name=None, + full_name=None, + index=None, + methods=None, + options=None, + serialized_options=None, + file=None, # pylint: disable=redefined-builtin + serialized_start=None, + serialized_end=None, + create_key=None, + ): + _message.Message._CheckCalledFromGeneratedFile() # pylint: disable=protected-access + return _message.default_pool.FindServiceByName(full_name) + + def __init__( + self, + name, + full_name, + index, + methods, + options=None, + serialized_options=None, + file=None, # pylint: disable=redefined-builtin + serialized_start=None, + serialized_end=None, + create_key=None, + ): + if create_key is not _internal_create_key: + _Deprecated('create function ServiceDescriptor()') + + super(ServiceDescriptor, self).__init__( + options, + 'ServiceOptions', + name, + full_name, + file, + None, + serialized_start=serialized_start, + serialized_end=serialized_end, + serialized_options=serialized_options, + ) + self.index = index + self.methods = methods + self.methods_by_name = dict((m.name, m) for m in methods) + # Set the containing service for each method in this service. + for method in self.methods: + method.file = self.file + method.containing_service = self + + @property + def _parent(self): + return self.file + + def FindMethodByName(self, name): + """Searches for the specified method, and returns its descriptor. + + Args: + name (str): Name of the method. + + Returns: + MethodDescriptor: The descriptor for the requested method. + + Raises: + KeyError: if the method cannot be found in the service. + """ + return self.methods_by_name[name] + + def CopyToProto(self, proto): + """Copies this to a descriptor_pb2.ServiceDescriptorProto. + + Args: + proto (descriptor_pb2.ServiceDescriptorProto): An empty descriptor proto. + """ + # This function is overridden to give a better doc comment. + super(ServiceDescriptor, self).CopyToProto(proto) + + +class MethodDescriptor(DescriptorBase): + """Descriptor for a method in a service. + + Attributes: + name (str): Name of the method within the service. + full_name (str): Full name of method. + index (int): 0-indexed index of the method inside the service. + containing_service (ServiceDescriptor): The service that contains this + method. + input_type (Descriptor): The descriptor of the message that this method + accepts. + output_type (Descriptor): The descriptor of the message that this method + returns. + client_streaming (bool): Whether this method uses client streaming. + server_streaming (bool): Whether this method uses server streaming. + options (descriptor_pb2.MethodOptions or None): Method options message, or + None to use default method options. + """ + + if _USE_C_DESCRIPTORS: + _C_DESCRIPTOR_CLASS = _message.MethodDescriptor + + def __new__( + cls, + name, + full_name, + index, + containing_service, + input_type, + output_type, + client_streaming=False, + server_streaming=False, + options=None, + serialized_options=None, + create_key=None, + ): + _message.Message._CheckCalledFromGeneratedFile() # pylint: disable=protected-access + return _message.default_pool.FindMethodByName(full_name) + + def __init__( + self, + name, + full_name, + index, + containing_service, + input_type, + output_type, + client_streaming=False, + server_streaming=False, + options=None, + serialized_options=None, + create_key=None, + ): + """The arguments are as described in the description of MethodDescriptor + + attributes above. + + Note that containing_service may be None, and may be set later if necessary. + """ + if create_key is not _internal_create_key: + _Deprecated('create function MethodDescriptor()') + + super(MethodDescriptor, self).__init__( + containing_service.file if containing_service else None, + options, + serialized_options, + 'MethodOptions', + ) + self.name = name + self.full_name = full_name + self.index = index + self.containing_service = containing_service + self.input_type = input_type + self.output_type = output_type + self.client_streaming = client_streaming + self.server_streaming = server_streaming + + @property + def _parent(self): + return self.containing_service + + def CopyToProto(self, proto): + """Copies this to a descriptor_pb2.MethodDescriptorProto. + + Args: + proto (descriptor_pb2.MethodDescriptorProto): An empty descriptor proto. + + Raises: + Error: If self couldn't be serialized, due to too few constructor + arguments. + """ + if self.containing_service is not None: + from google.protobuf import descriptor_pb2 + + service_proto = descriptor_pb2.ServiceDescriptorProto() + self.containing_service.CopyToProto(service_proto) + proto.CopyFrom(service_proto.method[self.index]) + else: + raise Error('Descriptor does not contain a service.') + + +class FileDescriptor(DescriptorBase): + """Descriptor for a file. Mimics the descriptor_pb2.FileDescriptorProto. + + Note that :attr:`enum_types_by_name`, :attr:`extensions_by_name`, and + :attr:`dependencies` fields are only set by the + :py:mod:`google.protobuf.message_factory` module, and not by the generated + proto code. + + Attributes: + name (str): Name of file, relative to root of source tree. + package (str): Name of the package + edition (Edition): Enum value indicating edition of the file + serialized_pb (bytes): Byte string of serialized + :class:`descriptor_pb2.FileDescriptorProto`. + dependencies (list[FileDescriptor]): List of other :class:`FileDescriptor` + objects this :class:`FileDescriptor` depends on. + public_dependencies (list[FileDescriptor]): A subset of + :attr:`dependencies`, which were declared as "public". + message_types_by_name (dict(str, Descriptor)): Mapping from message names to + their :class:`Descriptor`. + enum_types_by_name (dict(str, EnumDescriptor)): Mapping from enum names to + their :class:`EnumDescriptor`. + extensions_by_name (dict(str, FieldDescriptor)): Mapping from extension + names declared at file scope to their :class:`FieldDescriptor`. + services_by_name (dict(str, ServiceDescriptor)): Mapping from services' + names to their :class:`ServiceDescriptor`. + pool (DescriptorPool): The pool this descriptor belongs to. When not passed + to the constructor, the global default pool is used. + """ + + if _USE_C_DESCRIPTORS: + _C_DESCRIPTOR_CLASS = _message.FileDescriptor + + def __new__( + cls, + name, + package, + options=None, + serialized_options=None, + serialized_pb=None, + dependencies=None, + public_dependencies=None, + syntax=None, + edition=None, + pool=None, + create_key=None, + ): + # FileDescriptor() is called from various places, not only from generated + # files, to register dynamic proto files and messages. + # pylint: disable=g-explicit-bool-comparison + if serialized_pb: + return _message.default_pool.AddSerializedFile(serialized_pb) + else: + return super(FileDescriptor, cls).__new__(cls) + + def __init__( + self, + name, + package, + options=None, + serialized_options=None, + serialized_pb=None, + dependencies=None, + public_dependencies=None, + syntax=None, + edition=None, + pool=None, + create_key=None, + ): + """Constructor.""" + if create_key is not _internal_create_key: + _Deprecated('create function FileDescriptor()') + + super(FileDescriptor, self).__init__( + self, options, serialized_options, 'FileOptions' + ) + + if edition and edition != 'EDITION_UNKNOWN': + self._edition = edition + elif syntax == 'proto3': + self._edition = 'EDITION_PROTO3' + else: + self._edition = 'EDITION_PROTO2' + + if pool is None: + from google.protobuf import descriptor_pool + + pool = descriptor_pool.Default() + self.pool = pool + self.message_types_by_name = {} + self.name = name + self.package = package + self.serialized_pb = serialized_pb + + self.enum_types_by_name = {} + self.extensions_by_name = {} + self.services_by_name = {} + self.dependencies = dependencies or [] + self.public_dependencies = public_dependencies or [] + + def CopyToProto(self, proto): + """Copies this to a descriptor_pb2.FileDescriptorProto. + + Args: + proto: An empty descriptor_pb2.FileDescriptorProto. + """ + proto.ParseFromString(self.serialized_pb) + + @property + def _parent(self): + return None + + +def _ParseOptions(message, string): + """Parses serialized options. + + This helper function is used to parse serialized options in generated + proto2 files. It must not be used outside proto2. + """ + message.ParseFromString(string) + return message + + +def _ToCamelCase(name): + """Converts name to camel-case and returns it.""" + capitalize_next = False + result = [] + + for c in name: + if c == '_': + if result: + capitalize_next = True + elif capitalize_next: + result.append(c.upper()) + capitalize_next = False + else: + result += c + + # Lower-case the first letter. + if result and result[0].isupper(): + result[0] = result[0].lower() + return ''.join(result) + + +def _OptionsOrNone(descriptor_proto): + """Returns the value of the field `options`, or None if it is not set.""" + if descriptor_proto.HasField('options'): + return descriptor_proto.options + else: + return None + + +def _ToJsonName(name): + """Converts name to Json name and returns it.""" + capitalize_next = False + result = [] + + for c in name: + if c == '_': + capitalize_next = True + elif capitalize_next: + result.append(c.upper()) + capitalize_next = False + else: + result += c + + return ''.join(result) + + +def MakeDescriptor( + desc_proto, + package='', + build_file_if_cpp=True, + syntax=None, + edition=None, + file_desc=None, +): + """Make a protobuf Descriptor given a DescriptorProto protobuf. + + Handles nested descriptors. Note that this is limited to the scope of defining + a message inside of another message. Composite fields can currently only be + resolved if the message is defined in the same scope as the field. + + Args: + desc_proto: The descriptor_pb2.DescriptorProto protobuf message. + package: Optional package name for the new message Descriptor (string). + build_file_if_cpp: Update the C++ descriptor pool if api matches. Set to + False on recursion, so no duplicates are created. + syntax: The syntax/semantics that should be used. Set to "proto3" to get + proto3 field presence semantics. + edition: The edition that should be used if syntax is "edition". + file_desc: A FileDescriptor to place this descriptor into. + + Returns: + A Descriptor for protobuf messages. + """ + # pylint: disable=g-import-not-at-top + from google.protobuf import descriptor_pb2 + + # Generate a random name for this proto file to prevent conflicts with any + # imported ones. We need to specify a file name so the descriptor pool + # accepts our FileDescriptorProto, but it is not important what that file + # name is actually set to. + proto_name = binascii.hexlify(os.urandom(16)).decode('ascii') + + if package: + file_name = os.path.join(package.replace('.', '/'), proto_name + '.proto') + else: + file_name = proto_name + '.proto' + + if api_implementation.Type() != 'python' and build_file_if_cpp: + # The C++ implementation requires all descriptors to be backed by the same + # definition in the C++ descriptor pool. To do this, we build a + # FileDescriptorProto with the same definition as this descriptor and build + # it into the pool. + file_descriptor_proto = descriptor_pb2.FileDescriptorProto() + file_descriptor_proto.message_type.add().MergeFrom(desc_proto) + + if package: + file_descriptor_proto.package = package + file_descriptor_proto.name = file_name + + _message.default_pool.Add(file_descriptor_proto) + result = _message.default_pool.FindFileByName(file_descriptor_proto.name) + + if _USE_C_DESCRIPTORS: + return result.message_types_by_name[desc_proto.name] + + if file_desc is None: + file_desc = FileDescriptor( + pool=None, + name=file_name, + package=package, + syntax=syntax, + edition=edition, + options=None, + serialized_pb='', + dependencies=[], + public_dependencies=[], + create_key=_internal_create_key, + ) + full_message_name = [desc_proto.name] + if package: + full_message_name.insert(0, package) + + # Create Descriptors for enum types + enum_types = {} + for enum_proto in desc_proto.enum_type: + full_name = '.'.join(full_message_name + [enum_proto.name]) + enum_desc = EnumDescriptor( + enum_proto.name, + full_name, + None, + [ + EnumValueDescriptor( + enum_val.name, + ii, + enum_val.number, + create_key=_internal_create_key, + ) + for ii, enum_val in enumerate(enum_proto.value) + ], + file=file_desc, + create_key=_internal_create_key, + ) + enum_types[full_name] = enum_desc + + # Create Descriptors for nested types + nested_types = {} + for nested_proto in desc_proto.nested_type: + full_name = '.'.join(full_message_name + [nested_proto.name]) + # Nested types are just those defined inside of the message, not all types + # used by fields in the message, so no loops are possible here. + nested_desc = MakeDescriptor( + nested_proto, + package='.'.join(full_message_name), + build_file_if_cpp=False, + syntax=syntax, + edition=edition, + file_desc=file_desc, + ) + nested_types[full_name] = nested_desc + + fields = [] + for field_proto in desc_proto.field: + full_name = '.'.join(full_message_name + [field_proto.name]) + enum_desc = None + nested_desc = None + if field_proto.json_name: + json_name = field_proto.json_name + else: + json_name = None + if field_proto.HasField('type_name'): + type_name = field_proto.type_name + full_type_name = '.'.join( + full_message_name + [type_name[type_name.rfind('.') + 1 :]] + ) + if full_type_name in nested_types: + nested_desc = nested_types[full_type_name] + elif full_type_name in enum_types: + enum_desc = enum_types[full_type_name] + # Else type_name references a non-local type, which isn't implemented + field = FieldDescriptor( + field_proto.name, + full_name, + field_proto.number - 1, + field_proto.number, + field_proto.type, + FieldDescriptor.ProtoTypeToCppProtoType(field_proto.type), + field_proto.label, + None, + nested_desc, + enum_desc, + None, + False, + None, + options=_OptionsOrNone(field_proto), + has_default_value=False, + json_name=json_name, + file=file_desc, + create_key=_internal_create_key, + ) + fields.append(field) + + desc_name = '.'.join(full_message_name) + return Descriptor( + desc_proto.name, + desc_name, + None, + None, + fields, + list(nested_types.values()), + list(enum_types.values()), + [], + options=_OptionsOrNone(desc_proto), + file=file_desc, + create_key=_internal_create_key, + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/descriptor_database.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/descriptor_database.py new file mode 100644 index 0000000000000000000000000000000000000000..eeb8599372827ea36346e1cb579cf6066d1fb674 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/descriptor_database.py @@ -0,0 +1,172 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""Provides a container for DescriptorProtos.""" + +__author__ = 'matthewtoia@google.com (Matt Toia)' + +import warnings + + +class Error(Exception): + pass + + +class DescriptorDatabaseConflictingDefinitionError(Error): + """Raised when a proto is added with the same name & different descriptor.""" + + +class DescriptorDatabase(object): + """A container accepting FileDescriptorProtos and maps DescriptorProtos.""" + + def __init__(self): + self._file_desc_protos_by_file = {} + self._file_desc_protos_by_symbol = {} + + def Add(self, file_desc_proto): + """Adds the FileDescriptorProto and its types to this database. + + Args: + file_desc_proto: The FileDescriptorProto to add. + Raises: + DescriptorDatabaseConflictingDefinitionError: if an attempt is made to + add a proto with the same name but different definition than an + existing proto in the database. + """ + proto_name = file_desc_proto.name + if proto_name not in self._file_desc_protos_by_file: + self._file_desc_protos_by_file[proto_name] = file_desc_proto + elif self._file_desc_protos_by_file[proto_name] != file_desc_proto: + raise DescriptorDatabaseConflictingDefinitionError( + '%s already added, but with different descriptor.' % proto_name) + else: + return + + # Add all the top-level descriptors to the index. + package = file_desc_proto.package + for message in file_desc_proto.message_type: + for name in _ExtractSymbols(message, package): + self._AddSymbol(name, file_desc_proto) + for enum in file_desc_proto.enum_type: + self._AddSymbol( + ('.'.join((package, enum.name)) if package else enum.name), + file_desc_proto, + ) + for enum_value in enum.value: + self._file_desc_protos_by_symbol[ + '.'.join((package, enum_value.name)) if package else enum_value.name + ] = file_desc_proto + for extension in file_desc_proto.extension: + self._AddSymbol( + ('.'.join((package, extension.name)) if package else extension.name), + file_desc_proto, + ) + for service in file_desc_proto.service: + self._AddSymbol( + ('.'.join((package, service.name)) if package else service.name), + file_desc_proto, + ) + + def FindFileByName(self, name): + """Finds the file descriptor proto by file name. + + Typically the file name is a relative path ending to a .proto file. The + proto with the given name will have to have been added to this database + using the Add method or else an error will be raised. + + Args: + name: The file name to find. + + Returns: + The file descriptor proto matching the name. + + Raises: + KeyError if no file by the given name was added. + """ + + return self._file_desc_protos_by_file[name] + + def FindFileContainingSymbol(self, symbol): + """Finds the file descriptor proto containing the specified symbol. + + The symbol should be a fully qualified name including the file descriptor's + package and any containing messages. Some examples: + + 'some.package.name.Message' + 'some.package.name.Message.NestedEnum' + 'some.package.name.Message.some_field' + + The file descriptor proto containing the specified symbol must be added to + this database using the Add method or else an error will be raised. + + Args: + symbol: The fully qualified symbol name. + + Returns: + The file descriptor proto containing the symbol. + + Raises: + KeyError if no file contains the specified symbol. + """ + if symbol.count('.') == 1 and symbol[0] == '.': + symbol = symbol.lstrip('.') + warnings.warn( + 'Please remove the leading "." when ' + 'FindFileContainingSymbol, this will turn to error ' + 'in 2026 Jan.', + RuntimeWarning, + ) + try: + return self._file_desc_protos_by_symbol[symbol] + except KeyError: + # Fields, enum values, and nested extensions are not in + # _file_desc_protos_by_symbol. Try to find the top level + # descriptor. Non-existent nested symbol under a valid top level + # descriptor can also be found. The behavior is the same with + # protobuf C++. + top_level, _, _ = symbol.rpartition('.') + try: + return self._file_desc_protos_by_symbol[top_level] + except KeyError: + # Raise the original symbol as a KeyError for better diagnostics. + raise KeyError(symbol) + + def FindFileContainingExtension(self, extendee_name, extension_number): + # TODO: implement this API. + return None + + def FindAllExtensionNumbers(self, extendee_name): + # TODO: implement this API. + return [] + + def _AddSymbol(self, name, file_desc_proto): + if name in self._file_desc_protos_by_symbol: + warn_msg = ('Conflict register for file "' + file_desc_proto.name + + '": ' + name + + ' is already defined in file "' + + self._file_desc_protos_by_symbol[name].name + '"') + warnings.warn(warn_msg, RuntimeWarning) + self._file_desc_protos_by_symbol[name] = file_desc_proto + + +def _ExtractSymbols(desc_proto, package): + """Pulls out all the symbols from a descriptor proto. + + Args: + desc_proto: The proto to extract symbols from. + package: The package containing the descriptor type. + + Yields: + The fully qualified name found in the descriptor. + """ + message_name = package + '.' + desc_proto.name if package else desc_proto.name + yield message_name + for nested_type in desc_proto.nested_type: + for symbol in _ExtractSymbols(nested_type, message_name): + yield symbol + for enum_type in desc_proto.enum_type: + yield '.'.join((message_name, enum_type.name)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/descriptor_pb2.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/descriptor_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..8de6be148a03914a180e20fed29661b0bd49ab53 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/descriptor_pb2.py @@ -0,0 +1,3369 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# NO CHECKED-IN PROTOBUF GENCODE +# source: google/protobuf/descriptor.proto +# Protobuf Python Version: 6.33.6 +"""Generated protocol buffer code.""" +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import runtime_version as _runtime_version +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder +_runtime_version.ValidateProtobufRuntimeVersion( + _runtime_version.Domain.PUBLIC, + 6, + 33, + 6, + '', + 'google/protobuf/descriptor.proto' +) +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +if not _descriptor._USE_C_DESCRIPTORS: + DESCRIPTOR = _descriptor.FileDescriptor( + name='google/protobuf/descriptor.proto', + package='google.protobuf', + syntax='proto2', + edition='EDITION_PROTO2', + serialized_options=b'\n\023com.google.protobufB\020DescriptorProtosH\001Z-google.golang.org/protobuf/types/descriptorpb\370\001\001\242\002\003GPB\252\002\032Google.Protobuf.Reflection', + create_key=_descriptor._internal_create_key, + serialized_pb=b'\n google/protobuf/descriptor.proto\x12\x0fgoogle.protobuf\"[\n\x11\x46ileDescriptorSet\x12\x38\n\x04\x66ile\x18\x01 \x03(\x0b\x32$.google.protobuf.FileDescriptorProtoR\x04\x66ile*\x0c\x08\x80\xec\xca\xff\x01\x10\x81\xec\xca\xff\x01\"\xc5\x05\n\x13\x46ileDescriptorProto\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\x12\x18\n\x07package\x18\x02 \x01(\tR\x07package\x12\x1e\n\ndependency\x18\x03 \x03(\tR\ndependency\x12+\n\x11public_dependency\x18\n \x03(\x05R\x10publicDependency\x12\'\n\x0fweak_dependency\x18\x0b \x03(\x05R\x0eweakDependency\x12+\n\x11option_dependency\x18\x0f \x03(\tR\x10optionDependency\x12\x43\n\x0cmessage_type\x18\x04 \x03(\x0b\x32 .google.protobuf.DescriptorProtoR\x0bmessageType\x12\x41\n\tenum_type\x18\x05 \x03(\x0b\x32$.google.protobuf.EnumDescriptorProtoR\x08\x65numType\x12\x41\n\x07service\x18\x06 \x03(\x0b\x32\'.google.protobuf.ServiceDescriptorProtoR\x07service\x12\x43\n\textension\x18\x07 \x03(\x0b\x32%.google.protobuf.FieldDescriptorProtoR\textension\x12\x36\n\x07options\x18\x08 \x01(\x0b\x32\x1c.google.protobuf.FileOptionsR\x07options\x12I\n\x10source_code_info\x18\t \x01(\x0b\x32\x1f.google.protobuf.SourceCodeInfoR\x0esourceCodeInfo\x12\x16\n\x06syntax\x18\x0c \x01(\tR\x06syntax\x12\x32\n\x07\x65\x64ition\x18\x0e \x01(\x0e\x32\x18.google.protobuf.EditionR\x07\x65\x64ition\"\xfc\x06\n\x0f\x44\x65scriptorProto\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\x12;\n\x05\x66ield\x18\x02 \x03(\x0b\x32%.google.protobuf.FieldDescriptorProtoR\x05\x66ield\x12\x43\n\textension\x18\x06 \x03(\x0b\x32%.google.protobuf.FieldDescriptorProtoR\textension\x12\x41\n\x0bnested_type\x18\x03 \x03(\x0b\x32 .google.protobuf.DescriptorProtoR\nnestedType\x12\x41\n\tenum_type\x18\x04 \x03(\x0b\x32$.google.protobuf.EnumDescriptorProtoR\x08\x65numType\x12X\n\x0f\x65xtension_range\x18\x05 \x03(\x0b\x32/.google.protobuf.DescriptorProto.ExtensionRangeR\x0e\x65xtensionRange\x12\x44\n\noneof_decl\x18\x08 \x03(\x0b\x32%.google.protobuf.OneofDescriptorProtoR\toneofDecl\x12\x39\n\x07options\x18\x07 \x01(\x0b\x32\x1f.google.protobuf.MessageOptionsR\x07options\x12U\n\x0ereserved_range\x18\t \x03(\x0b\x32..google.protobuf.DescriptorProto.ReservedRangeR\rreservedRange\x12#\n\rreserved_name\x18\n \x03(\tR\x0creservedName\x12\x41\n\nvisibility\x18\x0b \x01(\x0e\x32!.google.protobuf.SymbolVisibilityR\nvisibility\x1az\n\x0e\x45xtensionRange\x12\x14\n\x05start\x18\x01 \x01(\x05R\x05start\x12\x10\n\x03\x65nd\x18\x02 \x01(\x05R\x03\x65nd\x12@\n\x07options\x18\x03 \x01(\x0b\x32&.google.protobuf.ExtensionRangeOptionsR\x07options\x1a\x37\n\rReservedRange\x12\x14\n\x05start\x18\x01 \x01(\x05R\x05start\x12\x10\n\x03\x65nd\x18\x02 \x01(\x05R\x03\x65nd\"\xcc\x04\n\x15\x45xtensionRangeOptions\x12X\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOptionR\x13uninterpretedOption\x12Y\n\x0b\x64\x65\x63laration\x18\x02 \x03(\x0b\x32\x32.google.protobuf.ExtensionRangeOptions.DeclarationB\x03\x88\x01\x02R\x0b\x64\x65\x63laration\x12\x37\n\x08\x66\x65\x61tures\x18\x32 \x01(\x0b\x32\x1b.google.protobuf.FeatureSetR\x08\x66\x65\x61tures\x12m\n\x0cverification\x18\x03 \x01(\x0e\x32\x38.google.protobuf.ExtensionRangeOptions.VerificationState:\nUNVERIFIEDB\x03\x88\x01\x02R\x0cverification\x1a\x94\x01\n\x0b\x44\x65\x63laration\x12\x16\n\x06number\x18\x01 \x01(\x05R\x06number\x12\x1b\n\tfull_name\x18\x02 \x01(\tR\x08\x66ullName\x12\x12\n\x04type\x18\x03 \x01(\tR\x04type\x12\x1a\n\x08reserved\x18\x05 \x01(\x08R\x08reserved\x12\x1a\n\x08repeated\x18\x06 \x01(\x08R\x08repeatedJ\x04\x08\x04\x10\x05\"4\n\x11VerificationState\x12\x0f\n\x0b\x44\x45\x43LARATION\x10\x00\x12\x0e\n\nUNVERIFIED\x10\x01*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02\"\xc1\x06\n\x14\x46ieldDescriptorProto\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\x12\x16\n\x06number\x18\x03 \x01(\x05R\x06number\x12\x41\n\x05label\x18\x04 \x01(\x0e\x32+.google.protobuf.FieldDescriptorProto.LabelR\x05label\x12>\n\x04type\x18\x05 \x01(\x0e\x32*.google.protobuf.FieldDescriptorProto.TypeR\x04type\x12\x1b\n\ttype_name\x18\x06 \x01(\tR\x08typeName\x12\x1a\n\x08\x65xtendee\x18\x02 \x01(\tR\x08\x65xtendee\x12#\n\rdefault_value\x18\x07 \x01(\tR\x0c\x64\x65\x66\x61ultValue\x12\x1f\n\x0boneof_index\x18\t \x01(\x05R\noneofIndex\x12\x1b\n\tjson_name\x18\n \x01(\tR\x08jsonName\x12\x37\n\x07options\x18\x08 \x01(\x0b\x32\x1d.google.protobuf.FieldOptionsR\x07options\x12\'\n\x0fproto3_optional\x18\x11 \x01(\x08R\x0eproto3Optional\"\xb6\x02\n\x04Type\x12\x0f\n\x0bTYPE_DOUBLE\x10\x01\x12\x0e\n\nTYPE_FLOAT\x10\x02\x12\x0e\n\nTYPE_INT64\x10\x03\x12\x0f\n\x0bTYPE_UINT64\x10\x04\x12\x0e\n\nTYPE_INT32\x10\x05\x12\x10\n\x0cTYPE_FIXED64\x10\x06\x12\x10\n\x0cTYPE_FIXED32\x10\x07\x12\r\n\tTYPE_BOOL\x10\x08\x12\x0f\n\x0bTYPE_STRING\x10\t\x12\x0e\n\nTYPE_GROUP\x10\n\x12\x10\n\x0cTYPE_MESSAGE\x10\x0b\x12\x0e\n\nTYPE_BYTES\x10\x0c\x12\x0f\n\x0bTYPE_UINT32\x10\r\x12\r\n\tTYPE_ENUM\x10\x0e\x12\x11\n\rTYPE_SFIXED32\x10\x0f\x12\x11\n\rTYPE_SFIXED64\x10\x10\x12\x0f\n\x0bTYPE_SINT32\x10\x11\x12\x0f\n\x0bTYPE_SINT64\x10\x12\"C\n\x05Label\x12\x12\n\x0eLABEL_OPTIONAL\x10\x01\x12\x12\n\x0eLABEL_REPEATED\x10\x03\x12\x12\n\x0eLABEL_REQUIRED\x10\x02\"c\n\x14OneofDescriptorProto\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\x12\x37\n\x07options\x18\x02 \x01(\x0b\x32\x1d.google.protobuf.OneofOptionsR\x07options\"\xa6\x03\n\x13\x45numDescriptorProto\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\x12?\n\x05value\x18\x02 \x03(\x0b\x32).google.protobuf.EnumValueDescriptorProtoR\x05value\x12\x36\n\x07options\x18\x03 \x01(\x0b\x32\x1c.google.protobuf.EnumOptionsR\x07options\x12]\n\x0ereserved_range\x18\x04 \x03(\x0b\x32\x36.google.protobuf.EnumDescriptorProto.EnumReservedRangeR\rreservedRange\x12#\n\rreserved_name\x18\x05 \x03(\tR\x0creservedName\x12\x41\n\nvisibility\x18\x06 \x01(\x0e\x32!.google.protobuf.SymbolVisibilityR\nvisibility\x1a;\n\x11\x45numReservedRange\x12\x14\n\x05start\x18\x01 \x01(\x05R\x05start\x12\x10\n\x03\x65nd\x18\x02 \x01(\x05R\x03\x65nd\"\x83\x01\n\x18\x45numValueDescriptorProto\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\x12\x16\n\x06number\x18\x02 \x01(\x05R\x06number\x12;\n\x07options\x18\x03 \x01(\x0b\x32!.google.protobuf.EnumValueOptionsR\x07options\"\xb5\x01\n\x16ServiceDescriptorProto\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\x12>\n\x06method\x18\x02 \x03(\x0b\x32&.google.protobuf.MethodDescriptorProtoR\x06method\x12\x39\n\x07options\x18\x03 \x01(\x0b\x32\x1f.google.protobuf.ServiceOptionsR\x07optionsJ\x04\x08\x04\x10\x05R\x06stream\"\x89\x02\n\x15MethodDescriptorProto\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\x12\x1d\n\ninput_type\x18\x02 \x01(\tR\tinputType\x12\x1f\n\x0boutput_type\x18\x03 \x01(\tR\noutputType\x12\x38\n\x07options\x18\x04 \x01(\x0b\x32\x1e.google.protobuf.MethodOptionsR\x07options\x12\x30\n\x10\x63lient_streaming\x18\x05 \x01(\x08:\x05\x66\x61lseR\x0f\x63lientStreaming\x12\x30\n\x10server_streaming\x18\x06 \x01(\x08:\x05\x66\x61lseR\x0fserverStreaming\"\xad\t\n\x0b\x46ileOptions\x12!\n\x0cjava_package\x18\x01 \x01(\tR\x0bjavaPackage\x12\x30\n\x14java_outer_classname\x18\x08 \x01(\tR\x12javaOuterClassname\x12\x35\n\x13java_multiple_files\x18\n \x01(\x08:\x05\x66\x61lseR\x11javaMultipleFiles\x12\x44\n\x1djava_generate_equals_and_hash\x18\x14 \x01(\x08\x42\x02\x18\x01R\x19javaGenerateEqualsAndHash\x12:\n\x16java_string_check_utf8\x18\x1b \x01(\x08:\x05\x66\x61lseR\x13javaStringCheckUtf8\x12S\n\x0coptimize_for\x18\t \x01(\x0e\x32).google.protobuf.FileOptions.OptimizeMode:\x05SPEEDR\x0boptimizeFor\x12\x1d\n\ngo_package\x18\x0b \x01(\tR\tgoPackage\x12\x35\n\x13\x63\x63_generic_services\x18\x10 \x01(\x08:\x05\x66\x61lseR\x11\x63\x63GenericServices\x12\x39\n\x15java_generic_services\x18\x11 \x01(\x08:\x05\x66\x61lseR\x13javaGenericServices\x12\x35\n\x13py_generic_services\x18\x12 \x01(\x08:\x05\x66\x61lseR\x11pyGenericServices\x12%\n\ndeprecated\x18\x17 \x01(\x08:\x05\x66\x61lseR\ndeprecated\x12.\n\x10\x63\x63_enable_arenas\x18\x1f \x01(\x08:\x04trueR\x0e\x63\x63\x45nableArenas\x12*\n\x11objc_class_prefix\x18$ \x01(\tR\x0fobjcClassPrefix\x12)\n\x10\x63sharp_namespace\x18% \x01(\tR\x0f\x63sharpNamespace\x12!\n\x0cswift_prefix\x18\' \x01(\tR\x0bswiftPrefix\x12(\n\x10php_class_prefix\x18( \x01(\tR\x0ephpClassPrefix\x12#\n\rphp_namespace\x18) \x01(\tR\x0cphpNamespace\x12\x34\n\x16php_metadata_namespace\x18, \x01(\tR\x14phpMetadataNamespace\x12!\n\x0cruby_package\x18- \x01(\tR\x0brubyPackage\x12\x37\n\x08\x66\x65\x61tures\x18\x32 \x01(\x0b\x32\x1b.google.protobuf.FeatureSetR\x08\x66\x65\x61tures\x12X\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOptionR\x13uninterpretedOption\":\n\x0cOptimizeMode\x12\t\n\x05SPEED\x10\x01\x12\r\n\tCODE_SIZE\x10\x02\x12\x10\n\x0cLITE_RUNTIME\x10\x03*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02J\x04\x08*\x10+J\x04\x08&\x10\'R\x14php_generic_services\"\xf4\x03\n\x0eMessageOptions\x12<\n\x17message_set_wire_format\x18\x01 \x01(\x08:\x05\x66\x61lseR\x14messageSetWireFormat\x12L\n\x1fno_standard_descriptor_accessor\x18\x02 \x01(\x08:\x05\x66\x61lseR\x1cnoStandardDescriptorAccessor\x12%\n\ndeprecated\x18\x03 \x01(\x08:\x05\x66\x61lseR\ndeprecated\x12\x1b\n\tmap_entry\x18\x07 \x01(\x08R\x08mapEntry\x12V\n&deprecated_legacy_json_field_conflicts\x18\x0b \x01(\x08\x42\x02\x18\x01R\"deprecatedLegacyJsonFieldConflicts\x12\x37\n\x08\x66\x65\x61tures\x18\x0c \x01(\x0b\x32\x1b.google.protobuf.FeatureSetR\x08\x66\x65\x61tures\x12X\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOptionR\x13uninterpretedOption*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02J\x04\x08\x04\x10\x05J\x04\x08\x05\x10\x06J\x04\x08\x06\x10\x07J\x04\x08\x08\x10\tJ\x04\x08\t\x10\n\"\xa1\r\n\x0c\x46ieldOptions\x12\x41\n\x05\x63type\x18\x01 \x01(\x0e\x32#.google.protobuf.FieldOptions.CType:\x06STRINGR\x05\x63type\x12\x16\n\x06packed\x18\x02 \x01(\x08R\x06packed\x12G\n\x06jstype\x18\x06 \x01(\x0e\x32$.google.protobuf.FieldOptions.JSType:\tJS_NORMALR\x06jstype\x12\x19\n\x04lazy\x18\x05 \x01(\x08:\x05\x66\x61lseR\x04lazy\x12.\n\x0funverified_lazy\x18\x0f \x01(\x08:\x05\x66\x61lseR\x0eunverifiedLazy\x12%\n\ndeprecated\x18\x03 \x01(\x08:\x05\x66\x61lseR\ndeprecated\x12\x1d\n\x04weak\x18\n \x01(\x08:\x05\x66\x61lseB\x02\x18\x01R\x04weak\x12(\n\x0c\x64\x65\x62ug_redact\x18\x10 \x01(\x08:\x05\x66\x61lseR\x0b\x64\x65\x62ugRedact\x12K\n\tretention\x18\x11 \x01(\x0e\x32-.google.protobuf.FieldOptions.OptionRetentionR\tretention\x12H\n\x07targets\x18\x13 \x03(\x0e\x32..google.protobuf.FieldOptions.OptionTargetTypeR\x07targets\x12W\n\x10\x65\x64ition_defaults\x18\x14 \x03(\x0b\x32,.google.protobuf.FieldOptions.EditionDefaultR\x0f\x65\x64itionDefaults\x12\x37\n\x08\x66\x65\x61tures\x18\x15 \x01(\x0b\x32\x1b.google.protobuf.FeatureSetR\x08\x66\x65\x61tures\x12U\n\x0f\x66\x65\x61ture_support\x18\x16 \x01(\x0b\x32,.google.protobuf.FieldOptions.FeatureSupportR\x0e\x66\x65\x61tureSupport\x12X\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOptionR\x13uninterpretedOption\x1aZ\n\x0e\x45\x64itionDefault\x12\x32\n\x07\x65\x64ition\x18\x03 \x01(\x0e\x32\x18.google.protobuf.EditionR\x07\x65\x64ition\x12\x14\n\x05value\x18\x02 \x01(\tR\x05value\x1a\x96\x02\n\x0e\x46\x65\x61tureSupport\x12G\n\x12\x65\x64ition_introduced\x18\x01 \x01(\x0e\x32\x18.google.protobuf.EditionR\x11\x65\x64itionIntroduced\x12G\n\x12\x65\x64ition_deprecated\x18\x02 \x01(\x0e\x32\x18.google.protobuf.EditionR\x11\x65\x64itionDeprecated\x12/\n\x13\x64\x65precation_warning\x18\x03 \x01(\tR\x12\x64\x65precationWarning\x12\x41\n\x0f\x65\x64ition_removed\x18\x04 \x01(\x0e\x32\x18.google.protobuf.EditionR\x0e\x65\x64itionRemoved\"/\n\x05\x43Type\x12\n\n\x06STRING\x10\x00\x12\x08\n\x04\x43ORD\x10\x01\x12\x10\n\x0cSTRING_PIECE\x10\x02\"5\n\x06JSType\x12\r\n\tJS_NORMAL\x10\x00\x12\r\n\tJS_STRING\x10\x01\x12\r\n\tJS_NUMBER\x10\x02\"U\n\x0fOptionRetention\x12\x15\n\x11RETENTION_UNKNOWN\x10\x00\x12\x15\n\x11RETENTION_RUNTIME\x10\x01\x12\x14\n\x10RETENTION_SOURCE\x10\x02\"\x8c\x02\n\x10OptionTargetType\x12\x17\n\x13TARGET_TYPE_UNKNOWN\x10\x00\x12\x14\n\x10TARGET_TYPE_FILE\x10\x01\x12\x1f\n\x1bTARGET_TYPE_EXTENSION_RANGE\x10\x02\x12\x17\n\x13TARGET_TYPE_MESSAGE\x10\x03\x12\x15\n\x11TARGET_TYPE_FIELD\x10\x04\x12\x15\n\x11TARGET_TYPE_ONEOF\x10\x05\x12\x14\n\x10TARGET_TYPE_ENUM\x10\x06\x12\x1a\n\x16TARGET_TYPE_ENUM_ENTRY\x10\x07\x12\x17\n\x13TARGET_TYPE_SERVICE\x10\x08\x12\x16\n\x12TARGET_TYPE_METHOD\x10\t*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02J\x04\x08\x04\x10\x05J\x04\x08\x12\x10\x13\"\xac\x01\n\x0cOneofOptions\x12\x37\n\x08\x66\x65\x61tures\x18\x01 \x01(\x0b\x32\x1b.google.protobuf.FeatureSetR\x08\x66\x65\x61tures\x12X\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOptionR\x13uninterpretedOption*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02\"\xd1\x02\n\x0b\x45numOptions\x12\x1f\n\x0b\x61llow_alias\x18\x02 \x01(\x08R\nallowAlias\x12%\n\ndeprecated\x18\x03 \x01(\x08:\x05\x66\x61lseR\ndeprecated\x12V\n&deprecated_legacy_json_field_conflicts\x18\x06 \x01(\x08\x42\x02\x18\x01R\"deprecatedLegacyJsonFieldConflicts\x12\x37\n\x08\x66\x65\x61tures\x18\x07 \x01(\x0b\x32\x1b.google.protobuf.FeatureSetR\x08\x66\x65\x61tures\x12X\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOptionR\x13uninterpretedOption*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02J\x04\x08\x05\x10\x06\"\xd8\x02\n\x10\x45numValueOptions\x12%\n\ndeprecated\x18\x01 \x01(\x08:\x05\x66\x61lseR\ndeprecated\x12\x37\n\x08\x66\x65\x61tures\x18\x02 \x01(\x0b\x32\x1b.google.protobuf.FeatureSetR\x08\x66\x65\x61tures\x12(\n\x0c\x64\x65\x62ug_redact\x18\x03 \x01(\x08:\x05\x66\x61lseR\x0b\x64\x65\x62ugRedact\x12U\n\x0f\x66\x65\x61ture_support\x18\x04 \x01(\x0b\x32,.google.protobuf.FieldOptions.FeatureSupportR\x0e\x66\x65\x61tureSupport\x12X\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOptionR\x13uninterpretedOption*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02\"\xd5\x01\n\x0eServiceOptions\x12\x37\n\x08\x66\x65\x61tures\x18\" \x01(\x0b\x32\x1b.google.protobuf.FeatureSetR\x08\x66\x65\x61tures\x12%\n\ndeprecated\x18! \x01(\x08:\x05\x66\x61lseR\ndeprecated\x12X\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOptionR\x13uninterpretedOption*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02\"\x99\x03\n\rMethodOptions\x12%\n\ndeprecated\x18! \x01(\x08:\x05\x66\x61lseR\ndeprecated\x12q\n\x11idempotency_level\x18\" \x01(\x0e\x32/.google.protobuf.MethodOptions.IdempotencyLevel:\x13IDEMPOTENCY_UNKNOWNR\x10idempotencyLevel\x12\x37\n\x08\x66\x65\x61tures\x18# \x01(\x0b\x32\x1b.google.protobuf.FeatureSetR\x08\x66\x65\x61tures\x12X\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOptionR\x13uninterpretedOption\"P\n\x10IdempotencyLevel\x12\x17\n\x13IDEMPOTENCY_UNKNOWN\x10\x00\x12\x13\n\x0fNO_SIDE_EFFECTS\x10\x01\x12\x0e\n\nIDEMPOTENT\x10\x02*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02\"\x9a\x03\n\x13UninterpretedOption\x12\x41\n\x04name\x18\x02 \x03(\x0b\x32-.google.protobuf.UninterpretedOption.NamePartR\x04name\x12)\n\x10identifier_value\x18\x03 \x01(\tR\x0fidentifierValue\x12,\n\x12positive_int_value\x18\x04 \x01(\x04R\x10positiveIntValue\x12,\n\x12negative_int_value\x18\x05 \x01(\x03R\x10negativeIntValue\x12!\n\x0c\x64ouble_value\x18\x06 \x01(\x01R\x0b\x64oubleValue\x12!\n\x0cstring_value\x18\x07 \x01(\x0cR\x0bstringValue\x12\'\n\x0f\x61ggregate_value\x18\x08 \x01(\tR\x0e\x61ggregateValue\x1aJ\n\x08NamePart\x12\x1b\n\tname_part\x18\x01 \x02(\tR\x08namePart\x12!\n\x0cis_extension\x18\x02 \x02(\x08R\x0bisExtension\"\x8e\x0f\n\nFeatureSet\x12\x91\x01\n\x0e\x66ield_presence\x18\x01 \x01(\x0e\x32).google.protobuf.FeatureSet.FieldPresenceB?\x88\x01\x01\x98\x01\x04\x98\x01\x01\xa2\x01\r\x12\x08\x45XPLICIT\x18\x84\x07\xa2\x01\r\x12\x08IMPLICIT\x18\xe7\x07\xa2\x01\r\x12\x08\x45XPLICIT\x18\xe8\x07\xb2\x01\x03\x08\xe8\x07R\rfieldPresence\x12l\n\tenum_type\x18\x02 \x01(\x0e\x32$.google.protobuf.FeatureSet.EnumTypeB)\x88\x01\x01\x98\x01\x06\x98\x01\x01\xa2\x01\x0b\x12\x06\x43LOSED\x18\x84\x07\xa2\x01\t\x12\x04OPEN\x18\xe7\x07\xb2\x01\x03\x08\xe8\x07R\x08\x65numType\x12\x98\x01\n\x17repeated_field_encoding\x18\x03 \x01(\x0e\x32\x31.google.protobuf.FeatureSet.RepeatedFieldEncodingB-\x88\x01\x01\x98\x01\x04\x98\x01\x01\xa2\x01\r\x12\x08\x45XPANDED\x18\x84\x07\xa2\x01\x0b\x12\x06PACKED\x18\xe7\x07\xb2\x01\x03\x08\xe8\x07R\x15repeatedFieldEncoding\x12~\n\x0futf8_validation\x18\x04 \x01(\x0e\x32*.google.protobuf.FeatureSet.Utf8ValidationB)\x88\x01\x01\x98\x01\x04\x98\x01\x01\xa2\x01\t\x12\x04NONE\x18\x84\x07\xa2\x01\x0b\x12\x06VERIFY\x18\xe7\x07\xb2\x01\x03\x08\xe8\x07R\x0eutf8Validation\x12~\n\x10message_encoding\x18\x05 \x01(\x0e\x32+.google.protobuf.FeatureSet.MessageEncodingB&\x88\x01\x01\x98\x01\x04\x98\x01\x01\xa2\x01\x14\x12\x0fLENGTH_PREFIXED\x18\x84\x07\xb2\x01\x03\x08\xe8\x07R\x0fmessageEncoding\x12\x82\x01\n\x0bjson_format\x18\x06 \x01(\x0e\x32&.google.protobuf.FeatureSet.JsonFormatB9\x88\x01\x01\x98\x01\x03\x98\x01\x06\x98\x01\x01\xa2\x01\x17\x12\x12LEGACY_BEST_EFFORT\x18\x84\x07\xa2\x01\n\x12\x05\x41LLOW\x18\xe7\x07\xb2\x01\x03\x08\xe8\x07R\njsonFormat\x12\xab\x01\n\x14\x65nforce_naming_style\x18\x07 \x01(\x0e\x32..google.protobuf.FeatureSet.EnforceNamingStyleBI\x88\x01\x02\x98\x01\x01\x98\x01\x02\x98\x01\x03\x98\x01\x04\x98\x01\x05\x98\x01\x06\x98\x01\x07\x98\x01\x08\x98\x01\t\xa2\x01\x11\x12\x0cSTYLE_LEGACY\x18\x84\x07\xa2\x01\x0e\x12\tSTYLE2024\x18\xe9\x07\xb2\x01\x03\x08\xe9\x07R\x12\x65nforceNamingStyle\x12\xb9\x01\n\x19\x64\x65\x66\x61ult_symbol_visibility\x18\x08 \x01(\x0e\x32\x45.google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibilityB6\x88\x01\x02\x98\x01\x01\xa2\x01\x0f\x12\nEXPORT_ALL\x18\x84\x07\xa2\x01\x15\x12\x10\x45XPORT_TOP_LEVEL\x18\xe9\x07\xb2\x01\x03\x08\xe9\x07R\x17\x64\x65\x66\x61ultSymbolVisibility\x1a\xa1\x01\n\x11VisibilityFeature\"\x81\x01\n\x17\x44\x65\x66\x61ultSymbolVisibility\x12%\n!DEFAULT_SYMBOL_VISIBILITY_UNKNOWN\x10\x00\x12\x0e\n\nEXPORT_ALL\x10\x01\x12\x14\n\x10\x45XPORT_TOP_LEVEL\x10\x02\x12\r\n\tLOCAL_ALL\x10\x03\x12\n\n\x06STRICT\x10\x04J\x08\x08\x01\x10\x80\x80\x80\x80\x02\"\\\n\rFieldPresence\x12\x1a\n\x16\x46IELD_PRESENCE_UNKNOWN\x10\x00\x12\x0c\n\x08\x45XPLICIT\x10\x01\x12\x0c\n\x08IMPLICIT\x10\x02\x12\x13\n\x0fLEGACY_REQUIRED\x10\x03\"7\n\x08\x45numType\x12\x15\n\x11\x45NUM_TYPE_UNKNOWN\x10\x00\x12\x08\n\x04OPEN\x10\x01\x12\n\n\x06\x43LOSED\x10\x02\"V\n\x15RepeatedFieldEncoding\x12#\n\x1fREPEATED_FIELD_ENCODING_UNKNOWN\x10\x00\x12\n\n\x06PACKED\x10\x01\x12\x0c\n\x08\x45XPANDED\x10\x02\"I\n\x0eUtf8Validation\x12\x1b\n\x17UTF8_VALIDATION_UNKNOWN\x10\x00\x12\n\n\x06VERIFY\x10\x02\x12\x08\n\x04NONE\x10\x03\"\x04\x08\x01\x10\x01\"S\n\x0fMessageEncoding\x12\x1c\n\x18MESSAGE_ENCODING_UNKNOWN\x10\x00\x12\x13\n\x0fLENGTH_PREFIXED\x10\x01\x12\r\n\tDELIMITED\x10\x02\"H\n\nJsonFormat\x12\x17\n\x13JSON_FORMAT_UNKNOWN\x10\x00\x12\t\n\x05\x41LLOW\x10\x01\x12\x16\n\x12LEGACY_BEST_EFFORT\x10\x02\"W\n\x12\x45nforceNamingStyle\x12 \n\x1c\x45NFORCE_NAMING_STYLE_UNKNOWN\x10\x00\x12\r\n\tSTYLE2024\x10\x01\x12\x10\n\x0cSTYLE_LEGACY\x10\x02*\x06\x08\xe8\x07\x10\x8bN*\x06\x08\x8bN\x10\x90N*\x06\x08\x90N\x10\x91NJ\x06\x08\xe7\x07\x10\xe8\x07\"\xef\x03\n\x12\x46\x65\x61tureSetDefaults\x12X\n\x08\x64\x65\x66\x61ults\x18\x01 \x03(\x0b\x32<.google.protobuf.FeatureSetDefaults.FeatureSetEditionDefaultR\x08\x64\x65\x66\x61ults\x12\x41\n\x0fminimum_edition\x18\x04 \x01(\x0e\x32\x18.google.protobuf.EditionR\x0eminimumEdition\x12\x41\n\x0fmaximum_edition\x18\x05 \x01(\x0e\x32\x18.google.protobuf.EditionR\x0emaximumEdition\x1a\xf8\x01\n\x18\x46\x65\x61tureSetEditionDefault\x12\x32\n\x07\x65\x64ition\x18\x03 \x01(\x0e\x32\x18.google.protobuf.EditionR\x07\x65\x64ition\x12N\n\x14overridable_features\x18\x04 \x01(\x0b\x32\x1b.google.protobuf.FeatureSetR\x13overridableFeatures\x12\x42\n\x0e\x66ixed_features\x18\x05 \x01(\x0b\x32\x1b.google.protobuf.FeatureSetR\rfixedFeaturesJ\x04\x08\x01\x10\x02J\x04\x08\x02\x10\x03R\x08\x66\x65\x61tures\"\xb5\x02\n\x0eSourceCodeInfo\x12\x44\n\x08location\x18\x01 \x03(\x0b\x32(.google.protobuf.SourceCodeInfo.LocationR\x08location\x1a\xce\x01\n\x08Location\x12\x16\n\x04path\x18\x01 \x03(\x05\x42\x02\x10\x01R\x04path\x12\x16\n\x04span\x18\x02 \x03(\x05\x42\x02\x10\x01R\x04span\x12)\n\x10leading_comments\x18\x03 \x01(\tR\x0fleadingComments\x12+\n\x11trailing_comments\x18\x04 \x01(\tR\x10trailingComments\x12:\n\x19leading_detached_comments\x18\x06 \x03(\tR\x17leadingDetachedComments*\x0c\x08\x80\xec\xca\xff\x01\x10\x81\xec\xca\xff\x01\"\xd0\x02\n\x11GeneratedCodeInfo\x12M\n\nannotation\x18\x01 \x03(\x0b\x32-.google.protobuf.GeneratedCodeInfo.AnnotationR\nannotation\x1a\xeb\x01\n\nAnnotation\x12\x16\n\x04path\x18\x01 \x03(\x05\x42\x02\x10\x01R\x04path\x12\x1f\n\x0bsource_file\x18\x02 \x01(\tR\nsourceFile\x12\x14\n\x05\x62\x65gin\x18\x03 \x01(\x05R\x05\x62\x65gin\x12\x10\n\x03\x65nd\x18\x04 \x01(\x05R\x03\x65nd\x12R\n\x08semantic\x18\x05 \x01(\x0e\x32\x36.google.protobuf.GeneratedCodeInfo.Annotation.SemanticR\x08semantic\"(\n\x08Semantic\x12\x08\n\x04NONE\x10\x00\x12\x07\n\x03SET\x10\x01\x12\t\n\x05\x41LIAS\x10\x02*\xbe\x02\n\x07\x45\x64ition\x12\x13\n\x0f\x45\x44ITION_UNKNOWN\x10\x00\x12\x13\n\x0e\x45\x44ITION_LEGACY\x10\x84\x07\x12\x13\n\x0e\x45\x44ITION_PROTO2\x10\xe6\x07\x12\x13\n\x0e\x45\x44ITION_PROTO3\x10\xe7\x07\x12\x11\n\x0c\x45\x44ITION_2023\x10\xe8\x07\x12\x11\n\x0c\x45\x44ITION_2024\x10\xe9\x07\x12\x15\n\x10\x45\x44ITION_UNSTABLE\x10\x8fN\x12\x17\n\x13\x45\x44ITION_1_TEST_ONLY\x10\x01\x12\x17\n\x13\x45\x44ITION_2_TEST_ONLY\x10\x02\x12\x1d\n\x17\x45\x44ITION_99997_TEST_ONLY\x10\x9d\x8d\x06\x12\x1d\n\x17\x45\x44ITION_99998_TEST_ONLY\x10\x9e\x8d\x06\x12\x1d\n\x17\x45\x44ITION_99999_TEST_ONLY\x10\x9f\x8d\x06\x12\x13\n\x0b\x45\x44ITION_MAX\x10\xff\xff\xff\xff\x07*U\n\x10SymbolVisibility\x12\x14\n\x10VISIBILITY_UNSET\x10\x00\x12\x14\n\x10VISIBILITY_LOCAL\x10\x01\x12\x15\n\x11VISIBILITY_EXPORT\x10\x02\x42~\n\x13\x63om.google.protobufB\x10\x44\x65scriptorProtosH\x01Z-google.golang.org/protobuf/types/descriptorpb\xf8\x01\x01\xa2\x02\x03GPB\xaa\x02\x1aGoogle.Protobuf.Reflection' + ) +else: + DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n google/protobuf/descriptor.proto\x12\x0fgoogle.protobuf\"[\n\x11\x46ileDescriptorSet\x12\x38\n\x04\x66ile\x18\x01 \x03(\x0b\x32$.google.protobuf.FileDescriptorProtoR\x04\x66ile*\x0c\x08\x80\xec\xca\xff\x01\x10\x81\xec\xca\xff\x01\"\xc5\x05\n\x13\x46ileDescriptorProto\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\x12\x18\n\x07package\x18\x02 \x01(\tR\x07package\x12\x1e\n\ndependency\x18\x03 \x03(\tR\ndependency\x12+\n\x11public_dependency\x18\n \x03(\x05R\x10publicDependency\x12\'\n\x0fweak_dependency\x18\x0b \x03(\x05R\x0eweakDependency\x12+\n\x11option_dependency\x18\x0f \x03(\tR\x10optionDependency\x12\x43\n\x0cmessage_type\x18\x04 \x03(\x0b\x32 .google.protobuf.DescriptorProtoR\x0bmessageType\x12\x41\n\tenum_type\x18\x05 \x03(\x0b\x32$.google.protobuf.EnumDescriptorProtoR\x08\x65numType\x12\x41\n\x07service\x18\x06 \x03(\x0b\x32\'.google.protobuf.ServiceDescriptorProtoR\x07service\x12\x43\n\textension\x18\x07 \x03(\x0b\x32%.google.protobuf.FieldDescriptorProtoR\textension\x12\x36\n\x07options\x18\x08 \x01(\x0b\x32\x1c.google.protobuf.FileOptionsR\x07options\x12I\n\x10source_code_info\x18\t \x01(\x0b\x32\x1f.google.protobuf.SourceCodeInfoR\x0esourceCodeInfo\x12\x16\n\x06syntax\x18\x0c \x01(\tR\x06syntax\x12\x32\n\x07\x65\x64ition\x18\x0e \x01(\x0e\x32\x18.google.protobuf.EditionR\x07\x65\x64ition\"\xfc\x06\n\x0f\x44\x65scriptorProto\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\x12;\n\x05\x66ield\x18\x02 \x03(\x0b\x32%.google.protobuf.FieldDescriptorProtoR\x05\x66ield\x12\x43\n\textension\x18\x06 \x03(\x0b\x32%.google.protobuf.FieldDescriptorProtoR\textension\x12\x41\n\x0bnested_type\x18\x03 \x03(\x0b\x32 .google.protobuf.DescriptorProtoR\nnestedType\x12\x41\n\tenum_type\x18\x04 \x03(\x0b\x32$.google.protobuf.EnumDescriptorProtoR\x08\x65numType\x12X\n\x0f\x65xtension_range\x18\x05 \x03(\x0b\x32/.google.protobuf.DescriptorProto.ExtensionRangeR\x0e\x65xtensionRange\x12\x44\n\noneof_decl\x18\x08 \x03(\x0b\x32%.google.protobuf.OneofDescriptorProtoR\toneofDecl\x12\x39\n\x07options\x18\x07 \x01(\x0b\x32\x1f.google.protobuf.MessageOptionsR\x07options\x12U\n\x0ereserved_range\x18\t \x03(\x0b\x32..google.protobuf.DescriptorProto.ReservedRangeR\rreservedRange\x12#\n\rreserved_name\x18\n \x03(\tR\x0creservedName\x12\x41\n\nvisibility\x18\x0b \x01(\x0e\x32!.google.protobuf.SymbolVisibilityR\nvisibility\x1az\n\x0e\x45xtensionRange\x12\x14\n\x05start\x18\x01 \x01(\x05R\x05start\x12\x10\n\x03\x65nd\x18\x02 \x01(\x05R\x03\x65nd\x12@\n\x07options\x18\x03 \x01(\x0b\x32&.google.protobuf.ExtensionRangeOptionsR\x07options\x1a\x37\n\rReservedRange\x12\x14\n\x05start\x18\x01 \x01(\x05R\x05start\x12\x10\n\x03\x65nd\x18\x02 \x01(\x05R\x03\x65nd\"\xcc\x04\n\x15\x45xtensionRangeOptions\x12X\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOptionR\x13uninterpretedOption\x12Y\n\x0b\x64\x65\x63laration\x18\x02 \x03(\x0b\x32\x32.google.protobuf.ExtensionRangeOptions.DeclarationB\x03\x88\x01\x02R\x0b\x64\x65\x63laration\x12\x37\n\x08\x66\x65\x61tures\x18\x32 \x01(\x0b\x32\x1b.google.protobuf.FeatureSetR\x08\x66\x65\x61tures\x12m\n\x0cverification\x18\x03 \x01(\x0e\x32\x38.google.protobuf.ExtensionRangeOptions.VerificationState:\nUNVERIFIEDB\x03\x88\x01\x02R\x0cverification\x1a\x94\x01\n\x0b\x44\x65\x63laration\x12\x16\n\x06number\x18\x01 \x01(\x05R\x06number\x12\x1b\n\tfull_name\x18\x02 \x01(\tR\x08\x66ullName\x12\x12\n\x04type\x18\x03 \x01(\tR\x04type\x12\x1a\n\x08reserved\x18\x05 \x01(\x08R\x08reserved\x12\x1a\n\x08repeated\x18\x06 \x01(\x08R\x08repeatedJ\x04\x08\x04\x10\x05\"4\n\x11VerificationState\x12\x0f\n\x0b\x44\x45\x43LARATION\x10\x00\x12\x0e\n\nUNVERIFIED\x10\x01*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02\"\xc1\x06\n\x14\x46ieldDescriptorProto\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\x12\x16\n\x06number\x18\x03 \x01(\x05R\x06number\x12\x41\n\x05label\x18\x04 \x01(\x0e\x32+.google.protobuf.FieldDescriptorProto.LabelR\x05label\x12>\n\x04type\x18\x05 \x01(\x0e\x32*.google.protobuf.FieldDescriptorProto.TypeR\x04type\x12\x1b\n\ttype_name\x18\x06 \x01(\tR\x08typeName\x12\x1a\n\x08\x65xtendee\x18\x02 \x01(\tR\x08\x65xtendee\x12#\n\rdefault_value\x18\x07 \x01(\tR\x0c\x64\x65\x66\x61ultValue\x12\x1f\n\x0boneof_index\x18\t \x01(\x05R\noneofIndex\x12\x1b\n\tjson_name\x18\n \x01(\tR\x08jsonName\x12\x37\n\x07options\x18\x08 \x01(\x0b\x32\x1d.google.protobuf.FieldOptionsR\x07options\x12\'\n\x0fproto3_optional\x18\x11 \x01(\x08R\x0eproto3Optional\"\xb6\x02\n\x04Type\x12\x0f\n\x0bTYPE_DOUBLE\x10\x01\x12\x0e\n\nTYPE_FLOAT\x10\x02\x12\x0e\n\nTYPE_INT64\x10\x03\x12\x0f\n\x0bTYPE_UINT64\x10\x04\x12\x0e\n\nTYPE_INT32\x10\x05\x12\x10\n\x0cTYPE_FIXED64\x10\x06\x12\x10\n\x0cTYPE_FIXED32\x10\x07\x12\r\n\tTYPE_BOOL\x10\x08\x12\x0f\n\x0bTYPE_STRING\x10\t\x12\x0e\n\nTYPE_GROUP\x10\n\x12\x10\n\x0cTYPE_MESSAGE\x10\x0b\x12\x0e\n\nTYPE_BYTES\x10\x0c\x12\x0f\n\x0bTYPE_UINT32\x10\r\x12\r\n\tTYPE_ENUM\x10\x0e\x12\x11\n\rTYPE_SFIXED32\x10\x0f\x12\x11\n\rTYPE_SFIXED64\x10\x10\x12\x0f\n\x0bTYPE_SINT32\x10\x11\x12\x0f\n\x0bTYPE_SINT64\x10\x12\"C\n\x05Label\x12\x12\n\x0eLABEL_OPTIONAL\x10\x01\x12\x12\n\x0eLABEL_REPEATED\x10\x03\x12\x12\n\x0eLABEL_REQUIRED\x10\x02\"c\n\x14OneofDescriptorProto\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\x12\x37\n\x07options\x18\x02 \x01(\x0b\x32\x1d.google.protobuf.OneofOptionsR\x07options\"\xa6\x03\n\x13\x45numDescriptorProto\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\x12?\n\x05value\x18\x02 \x03(\x0b\x32).google.protobuf.EnumValueDescriptorProtoR\x05value\x12\x36\n\x07options\x18\x03 \x01(\x0b\x32\x1c.google.protobuf.EnumOptionsR\x07options\x12]\n\x0ereserved_range\x18\x04 \x03(\x0b\x32\x36.google.protobuf.EnumDescriptorProto.EnumReservedRangeR\rreservedRange\x12#\n\rreserved_name\x18\x05 \x03(\tR\x0creservedName\x12\x41\n\nvisibility\x18\x06 \x01(\x0e\x32!.google.protobuf.SymbolVisibilityR\nvisibility\x1a;\n\x11\x45numReservedRange\x12\x14\n\x05start\x18\x01 \x01(\x05R\x05start\x12\x10\n\x03\x65nd\x18\x02 \x01(\x05R\x03\x65nd\"\x83\x01\n\x18\x45numValueDescriptorProto\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\x12\x16\n\x06number\x18\x02 \x01(\x05R\x06number\x12;\n\x07options\x18\x03 \x01(\x0b\x32!.google.protobuf.EnumValueOptionsR\x07options\"\xb5\x01\n\x16ServiceDescriptorProto\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\x12>\n\x06method\x18\x02 \x03(\x0b\x32&.google.protobuf.MethodDescriptorProtoR\x06method\x12\x39\n\x07options\x18\x03 \x01(\x0b\x32\x1f.google.protobuf.ServiceOptionsR\x07optionsJ\x04\x08\x04\x10\x05R\x06stream\"\x89\x02\n\x15MethodDescriptorProto\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\x12\x1d\n\ninput_type\x18\x02 \x01(\tR\tinputType\x12\x1f\n\x0boutput_type\x18\x03 \x01(\tR\noutputType\x12\x38\n\x07options\x18\x04 \x01(\x0b\x32\x1e.google.protobuf.MethodOptionsR\x07options\x12\x30\n\x10\x63lient_streaming\x18\x05 \x01(\x08:\x05\x66\x61lseR\x0f\x63lientStreaming\x12\x30\n\x10server_streaming\x18\x06 \x01(\x08:\x05\x66\x61lseR\x0fserverStreaming\"\xad\t\n\x0b\x46ileOptions\x12!\n\x0cjava_package\x18\x01 \x01(\tR\x0bjavaPackage\x12\x30\n\x14java_outer_classname\x18\x08 \x01(\tR\x12javaOuterClassname\x12\x35\n\x13java_multiple_files\x18\n \x01(\x08:\x05\x66\x61lseR\x11javaMultipleFiles\x12\x44\n\x1djava_generate_equals_and_hash\x18\x14 \x01(\x08\x42\x02\x18\x01R\x19javaGenerateEqualsAndHash\x12:\n\x16java_string_check_utf8\x18\x1b \x01(\x08:\x05\x66\x61lseR\x13javaStringCheckUtf8\x12S\n\x0coptimize_for\x18\t \x01(\x0e\x32).google.protobuf.FileOptions.OptimizeMode:\x05SPEEDR\x0boptimizeFor\x12\x1d\n\ngo_package\x18\x0b \x01(\tR\tgoPackage\x12\x35\n\x13\x63\x63_generic_services\x18\x10 \x01(\x08:\x05\x66\x61lseR\x11\x63\x63GenericServices\x12\x39\n\x15java_generic_services\x18\x11 \x01(\x08:\x05\x66\x61lseR\x13javaGenericServices\x12\x35\n\x13py_generic_services\x18\x12 \x01(\x08:\x05\x66\x61lseR\x11pyGenericServices\x12%\n\ndeprecated\x18\x17 \x01(\x08:\x05\x66\x61lseR\ndeprecated\x12.\n\x10\x63\x63_enable_arenas\x18\x1f \x01(\x08:\x04trueR\x0e\x63\x63\x45nableArenas\x12*\n\x11objc_class_prefix\x18$ \x01(\tR\x0fobjcClassPrefix\x12)\n\x10\x63sharp_namespace\x18% \x01(\tR\x0f\x63sharpNamespace\x12!\n\x0cswift_prefix\x18\' \x01(\tR\x0bswiftPrefix\x12(\n\x10php_class_prefix\x18( \x01(\tR\x0ephpClassPrefix\x12#\n\rphp_namespace\x18) \x01(\tR\x0cphpNamespace\x12\x34\n\x16php_metadata_namespace\x18, \x01(\tR\x14phpMetadataNamespace\x12!\n\x0cruby_package\x18- \x01(\tR\x0brubyPackage\x12\x37\n\x08\x66\x65\x61tures\x18\x32 \x01(\x0b\x32\x1b.google.protobuf.FeatureSetR\x08\x66\x65\x61tures\x12X\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOptionR\x13uninterpretedOption\":\n\x0cOptimizeMode\x12\t\n\x05SPEED\x10\x01\x12\r\n\tCODE_SIZE\x10\x02\x12\x10\n\x0cLITE_RUNTIME\x10\x03*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02J\x04\x08*\x10+J\x04\x08&\x10\'R\x14php_generic_services\"\xf4\x03\n\x0eMessageOptions\x12<\n\x17message_set_wire_format\x18\x01 \x01(\x08:\x05\x66\x61lseR\x14messageSetWireFormat\x12L\n\x1fno_standard_descriptor_accessor\x18\x02 \x01(\x08:\x05\x66\x61lseR\x1cnoStandardDescriptorAccessor\x12%\n\ndeprecated\x18\x03 \x01(\x08:\x05\x66\x61lseR\ndeprecated\x12\x1b\n\tmap_entry\x18\x07 \x01(\x08R\x08mapEntry\x12V\n&deprecated_legacy_json_field_conflicts\x18\x0b \x01(\x08\x42\x02\x18\x01R\"deprecatedLegacyJsonFieldConflicts\x12\x37\n\x08\x66\x65\x61tures\x18\x0c \x01(\x0b\x32\x1b.google.protobuf.FeatureSetR\x08\x66\x65\x61tures\x12X\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOptionR\x13uninterpretedOption*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02J\x04\x08\x04\x10\x05J\x04\x08\x05\x10\x06J\x04\x08\x06\x10\x07J\x04\x08\x08\x10\tJ\x04\x08\t\x10\n\"\xa1\r\n\x0c\x46ieldOptions\x12\x41\n\x05\x63type\x18\x01 \x01(\x0e\x32#.google.protobuf.FieldOptions.CType:\x06STRINGR\x05\x63type\x12\x16\n\x06packed\x18\x02 \x01(\x08R\x06packed\x12G\n\x06jstype\x18\x06 \x01(\x0e\x32$.google.protobuf.FieldOptions.JSType:\tJS_NORMALR\x06jstype\x12\x19\n\x04lazy\x18\x05 \x01(\x08:\x05\x66\x61lseR\x04lazy\x12.\n\x0funverified_lazy\x18\x0f \x01(\x08:\x05\x66\x61lseR\x0eunverifiedLazy\x12%\n\ndeprecated\x18\x03 \x01(\x08:\x05\x66\x61lseR\ndeprecated\x12\x1d\n\x04weak\x18\n \x01(\x08:\x05\x66\x61lseB\x02\x18\x01R\x04weak\x12(\n\x0c\x64\x65\x62ug_redact\x18\x10 \x01(\x08:\x05\x66\x61lseR\x0b\x64\x65\x62ugRedact\x12K\n\tretention\x18\x11 \x01(\x0e\x32-.google.protobuf.FieldOptions.OptionRetentionR\tretention\x12H\n\x07targets\x18\x13 \x03(\x0e\x32..google.protobuf.FieldOptions.OptionTargetTypeR\x07targets\x12W\n\x10\x65\x64ition_defaults\x18\x14 \x03(\x0b\x32,.google.protobuf.FieldOptions.EditionDefaultR\x0f\x65\x64itionDefaults\x12\x37\n\x08\x66\x65\x61tures\x18\x15 \x01(\x0b\x32\x1b.google.protobuf.FeatureSetR\x08\x66\x65\x61tures\x12U\n\x0f\x66\x65\x61ture_support\x18\x16 \x01(\x0b\x32,.google.protobuf.FieldOptions.FeatureSupportR\x0e\x66\x65\x61tureSupport\x12X\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOptionR\x13uninterpretedOption\x1aZ\n\x0e\x45\x64itionDefault\x12\x32\n\x07\x65\x64ition\x18\x03 \x01(\x0e\x32\x18.google.protobuf.EditionR\x07\x65\x64ition\x12\x14\n\x05value\x18\x02 \x01(\tR\x05value\x1a\x96\x02\n\x0e\x46\x65\x61tureSupport\x12G\n\x12\x65\x64ition_introduced\x18\x01 \x01(\x0e\x32\x18.google.protobuf.EditionR\x11\x65\x64itionIntroduced\x12G\n\x12\x65\x64ition_deprecated\x18\x02 \x01(\x0e\x32\x18.google.protobuf.EditionR\x11\x65\x64itionDeprecated\x12/\n\x13\x64\x65precation_warning\x18\x03 \x01(\tR\x12\x64\x65precationWarning\x12\x41\n\x0f\x65\x64ition_removed\x18\x04 \x01(\x0e\x32\x18.google.protobuf.EditionR\x0e\x65\x64itionRemoved\"/\n\x05\x43Type\x12\n\n\x06STRING\x10\x00\x12\x08\n\x04\x43ORD\x10\x01\x12\x10\n\x0cSTRING_PIECE\x10\x02\"5\n\x06JSType\x12\r\n\tJS_NORMAL\x10\x00\x12\r\n\tJS_STRING\x10\x01\x12\r\n\tJS_NUMBER\x10\x02\"U\n\x0fOptionRetention\x12\x15\n\x11RETENTION_UNKNOWN\x10\x00\x12\x15\n\x11RETENTION_RUNTIME\x10\x01\x12\x14\n\x10RETENTION_SOURCE\x10\x02\"\x8c\x02\n\x10OptionTargetType\x12\x17\n\x13TARGET_TYPE_UNKNOWN\x10\x00\x12\x14\n\x10TARGET_TYPE_FILE\x10\x01\x12\x1f\n\x1bTARGET_TYPE_EXTENSION_RANGE\x10\x02\x12\x17\n\x13TARGET_TYPE_MESSAGE\x10\x03\x12\x15\n\x11TARGET_TYPE_FIELD\x10\x04\x12\x15\n\x11TARGET_TYPE_ONEOF\x10\x05\x12\x14\n\x10TARGET_TYPE_ENUM\x10\x06\x12\x1a\n\x16TARGET_TYPE_ENUM_ENTRY\x10\x07\x12\x17\n\x13TARGET_TYPE_SERVICE\x10\x08\x12\x16\n\x12TARGET_TYPE_METHOD\x10\t*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02J\x04\x08\x04\x10\x05J\x04\x08\x12\x10\x13\"\xac\x01\n\x0cOneofOptions\x12\x37\n\x08\x66\x65\x61tures\x18\x01 \x01(\x0b\x32\x1b.google.protobuf.FeatureSetR\x08\x66\x65\x61tures\x12X\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOptionR\x13uninterpretedOption*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02\"\xd1\x02\n\x0b\x45numOptions\x12\x1f\n\x0b\x61llow_alias\x18\x02 \x01(\x08R\nallowAlias\x12%\n\ndeprecated\x18\x03 \x01(\x08:\x05\x66\x61lseR\ndeprecated\x12V\n&deprecated_legacy_json_field_conflicts\x18\x06 \x01(\x08\x42\x02\x18\x01R\"deprecatedLegacyJsonFieldConflicts\x12\x37\n\x08\x66\x65\x61tures\x18\x07 \x01(\x0b\x32\x1b.google.protobuf.FeatureSetR\x08\x66\x65\x61tures\x12X\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOptionR\x13uninterpretedOption*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02J\x04\x08\x05\x10\x06\"\xd8\x02\n\x10\x45numValueOptions\x12%\n\ndeprecated\x18\x01 \x01(\x08:\x05\x66\x61lseR\ndeprecated\x12\x37\n\x08\x66\x65\x61tures\x18\x02 \x01(\x0b\x32\x1b.google.protobuf.FeatureSetR\x08\x66\x65\x61tures\x12(\n\x0c\x64\x65\x62ug_redact\x18\x03 \x01(\x08:\x05\x66\x61lseR\x0b\x64\x65\x62ugRedact\x12U\n\x0f\x66\x65\x61ture_support\x18\x04 \x01(\x0b\x32,.google.protobuf.FieldOptions.FeatureSupportR\x0e\x66\x65\x61tureSupport\x12X\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOptionR\x13uninterpretedOption*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02\"\xd5\x01\n\x0eServiceOptions\x12\x37\n\x08\x66\x65\x61tures\x18\" \x01(\x0b\x32\x1b.google.protobuf.FeatureSetR\x08\x66\x65\x61tures\x12%\n\ndeprecated\x18! \x01(\x08:\x05\x66\x61lseR\ndeprecated\x12X\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOptionR\x13uninterpretedOption*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02\"\x99\x03\n\rMethodOptions\x12%\n\ndeprecated\x18! \x01(\x08:\x05\x66\x61lseR\ndeprecated\x12q\n\x11idempotency_level\x18\" \x01(\x0e\x32/.google.protobuf.MethodOptions.IdempotencyLevel:\x13IDEMPOTENCY_UNKNOWNR\x10idempotencyLevel\x12\x37\n\x08\x66\x65\x61tures\x18# \x01(\x0b\x32\x1b.google.protobuf.FeatureSetR\x08\x66\x65\x61tures\x12X\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOptionR\x13uninterpretedOption\"P\n\x10IdempotencyLevel\x12\x17\n\x13IDEMPOTENCY_UNKNOWN\x10\x00\x12\x13\n\x0fNO_SIDE_EFFECTS\x10\x01\x12\x0e\n\nIDEMPOTENT\x10\x02*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02\"\x9a\x03\n\x13UninterpretedOption\x12\x41\n\x04name\x18\x02 \x03(\x0b\x32-.google.protobuf.UninterpretedOption.NamePartR\x04name\x12)\n\x10identifier_value\x18\x03 \x01(\tR\x0fidentifierValue\x12,\n\x12positive_int_value\x18\x04 \x01(\x04R\x10positiveIntValue\x12,\n\x12negative_int_value\x18\x05 \x01(\x03R\x10negativeIntValue\x12!\n\x0c\x64ouble_value\x18\x06 \x01(\x01R\x0b\x64oubleValue\x12!\n\x0cstring_value\x18\x07 \x01(\x0cR\x0bstringValue\x12\'\n\x0f\x61ggregate_value\x18\x08 \x01(\tR\x0e\x61ggregateValue\x1aJ\n\x08NamePart\x12\x1b\n\tname_part\x18\x01 \x02(\tR\x08namePart\x12!\n\x0cis_extension\x18\x02 \x02(\x08R\x0bisExtension\"\x8e\x0f\n\nFeatureSet\x12\x91\x01\n\x0e\x66ield_presence\x18\x01 \x01(\x0e\x32).google.protobuf.FeatureSet.FieldPresenceB?\x88\x01\x01\x98\x01\x04\x98\x01\x01\xa2\x01\r\x12\x08\x45XPLICIT\x18\x84\x07\xa2\x01\r\x12\x08IMPLICIT\x18\xe7\x07\xa2\x01\r\x12\x08\x45XPLICIT\x18\xe8\x07\xb2\x01\x03\x08\xe8\x07R\rfieldPresence\x12l\n\tenum_type\x18\x02 \x01(\x0e\x32$.google.protobuf.FeatureSet.EnumTypeB)\x88\x01\x01\x98\x01\x06\x98\x01\x01\xa2\x01\x0b\x12\x06\x43LOSED\x18\x84\x07\xa2\x01\t\x12\x04OPEN\x18\xe7\x07\xb2\x01\x03\x08\xe8\x07R\x08\x65numType\x12\x98\x01\n\x17repeated_field_encoding\x18\x03 \x01(\x0e\x32\x31.google.protobuf.FeatureSet.RepeatedFieldEncodingB-\x88\x01\x01\x98\x01\x04\x98\x01\x01\xa2\x01\r\x12\x08\x45XPANDED\x18\x84\x07\xa2\x01\x0b\x12\x06PACKED\x18\xe7\x07\xb2\x01\x03\x08\xe8\x07R\x15repeatedFieldEncoding\x12~\n\x0futf8_validation\x18\x04 \x01(\x0e\x32*.google.protobuf.FeatureSet.Utf8ValidationB)\x88\x01\x01\x98\x01\x04\x98\x01\x01\xa2\x01\t\x12\x04NONE\x18\x84\x07\xa2\x01\x0b\x12\x06VERIFY\x18\xe7\x07\xb2\x01\x03\x08\xe8\x07R\x0eutf8Validation\x12~\n\x10message_encoding\x18\x05 \x01(\x0e\x32+.google.protobuf.FeatureSet.MessageEncodingB&\x88\x01\x01\x98\x01\x04\x98\x01\x01\xa2\x01\x14\x12\x0fLENGTH_PREFIXED\x18\x84\x07\xb2\x01\x03\x08\xe8\x07R\x0fmessageEncoding\x12\x82\x01\n\x0bjson_format\x18\x06 \x01(\x0e\x32&.google.protobuf.FeatureSet.JsonFormatB9\x88\x01\x01\x98\x01\x03\x98\x01\x06\x98\x01\x01\xa2\x01\x17\x12\x12LEGACY_BEST_EFFORT\x18\x84\x07\xa2\x01\n\x12\x05\x41LLOW\x18\xe7\x07\xb2\x01\x03\x08\xe8\x07R\njsonFormat\x12\xab\x01\n\x14\x65nforce_naming_style\x18\x07 \x01(\x0e\x32..google.protobuf.FeatureSet.EnforceNamingStyleBI\x88\x01\x02\x98\x01\x01\x98\x01\x02\x98\x01\x03\x98\x01\x04\x98\x01\x05\x98\x01\x06\x98\x01\x07\x98\x01\x08\x98\x01\t\xa2\x01\x11\x12\x0cSTYLE_LEGACY\x18\x84\x07\xa2\x01\x0e\x12\tSTYLE2024\x18\xe9\x07\xb2\x01\x03\x08\xe9\x07R\x12\x65nforceNamingStyle\x12\xb9\x01\n\x19\x64\x65\x66\x61ult_symbol_visibility\x18\x08 \x01(\x0e\x32\x45.google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibilityB6\x88\x01\x02\x98\x01\x01\xa2\x01\x0f\x12\nEXPORT_ALL\x18\x84\x07\xa2\x01\x15\x12\x10\x45XPORT_TOP_LEVEL\x18\xe9\x07\xb2\x01\x03\x08\xe9\x07R\x17\x64\x65\x66\x61ultSymbolVisibility\x1a\xa1\x01\n\x11VisibilityFeature\"\x81\x01\n\x17\x44\x65\x66\x61ultSymbolVisibility\x12%\n!DEFAULT_SYMBOL_VISIBILITY_UNKNOWN\x10\x00\x12\x0e\n\nEXPORT_ALL\x10\x01\x12\x14\n\x10\x45XPORT_TOP_LEVEL\x10\x02\x12\r\n\tLOCAL_ALL\x10\x03\x12\n\n\x06STRICT\x10\x04J\x08\x08\x01\x10\x80\x80\x80\x80\x02\"\\\n\rFieldPresence\x12\x1a\n\x16\x46IELD_PRESENCE_UNKNOWN\x10\x00\x12\x0c\n\x08\x45XPLICIT\x10\x01\x12\x0c\n\x08IMPLICIT\x10\x02\x12\x13\n\x0fLEGACY_REQUIRED\x10\x03\"7\n\x08\x45numType\x12\x15\n\x11\x45NUM_TYPE_UNKNOWN\x10\x00\x12\x08\n\x04OPEN\x10\x01\x12\n\n\x06\x43LOSED\x10\x02\"V\n\x15RepeatedFieldEncoding\x12#\n\x1fREPEATED_FIELD_ENCODING_UNKNOWN\x10\x00\x12\n\n\x06PACKED\x10\x01\x12\x0c\n\x08\x45XPANDED\x10\x02\"I\n\x0eUtf8Validation\x12\x1b\n\x17UTF8_VALIDATION_UNKNOWN\x10\x00\x12\n\n\x06VERIFY\x10\x02\x12\x08\n\x04NONE\x10\x03\"\x04\x08\x01\x10\x01\"S\n\x0fMessageEncoding\x12\x1c\n\x18MESSAGE_ENCODING_UNKNOWN\x10\x00\x12\x13\n\x0fLENGTH_PREFIXED\x10\x01\x12\r\n\tDELIMITED\x10\x02\"H\n\nJsonFormat\x12\x17\n\x13JSON_FORMAT_UNKNOWN\x10\x00\x12\t\n\x05\x41LLOW\x10\x01\x12\x16\n\x12LEGACY_BEST_EFFORT\x10\x02\"W\n\x12\x45nforceNamingStyle\x12 \n\x1c\x45NFORCE_NAMING_STYLE_UNKNOWN\x10\x00\x12\r\n\tSTYLE2024\x10\x01\x12\x10\n\x0cSTYLE_LEGACY\x10\x02*\x06\x08\xe8\x07\x10\x8bN*\x06\x08\x8bN\x10\x90N*\x06\x08\x90N\x10\x91NJ\x06\x08\xe7\x07\x10\xe8\x07\"\xef\x03\n\x12\x46\x65\x61tureSetDefaults\x12X\n\x08\x64\x65\x66\x61ults\x18\x01 \x03(\x0b\x32<.google.protobuf.FeatureSetDefaults.FeatureSetEditionDefaultR\x08\x64\x65\x66\x61ults\x12\x41\n\x0fminimum_edition\x18\x04 \x01(\x0e\x32\x18.google.protobuf.EditionR\x0eminimumEdition\x12\x41\n\x0fmaximum_edition\x18\x05 \x01(\x0e\x32\x18.google.protobuf.EditionR\x0emaximumEdition\x1a\xf8\x01\n\x18\x46\x65\x61tureSetEditionDefault\x12\x32\n\x07\x65\x64ition\x18\x03 \x01(\x0e\x32\x18.google.protobuf.EditionR\x07\x65\x64ition\x12N\n\x14overridable_features\x18\x04 \x01(\x0b\x32\x1b.google.protobuf.FeatureSetR\x13overridableFeatures\x12\x42\n\x0e\x66ixed_features\x18\x05 \x01(\x0b\x32\x1b.google.protobuf.FeatureSetR\rfixedFeaturesJ\x04\x08\x01\x10\x02J\x04\x08\x02\x10\x03R\x08\x66\x65\x61tures\"\xb5\x02\n\x0eSourceCodeInfo\x12\x44\n\x08location\x18\x01 \x03(\x0b\x32(.google.protobuf.SourceCodeInfo.LocationR\x08location\x1a\xce\x01\n\x08Location\x12\x16\n\x04path\x18\x01 \x03(\x05\x42\x02\x10\x01R\x04path\x12\x16\n\x04span\x18\x02 \x03(\x05\x42\x02\x10\x01R\x04span\x12)\n\x10leading_comments\x18\x03 \x01(\tR\x0fleadingComments\x12+\n\x11trailing_comments\x18\x04 \x01(\tR\x10trailingComments\x12:\n\x19leading_detached_comments\x18\x06 \x03(\tR\x17leadingDetachedComments*\x0c\x08\x80\xec\xca\xff\x01\x10\x81\xec\xca\xff\x01\"\xd0\x02\n\x11GeneratedCodeInfo\x12M\n\nannotation\x18\x01 \x03(\x0b\x32-.google.protobuf.GeneratedCodeInfo.AnnotationR\nannotation\x1a\xeb\x01\n\nAnnotation\x12\x16\n\x04path\x18\x01 \x03(\x05\x42\x02\x10\x01R\x04path\x12\x1f\n\x0bsource_file\x18\x02 \x01(\tR\nsourceFile\x12\x14\n\x05\x62\x65gin\x18\x03 \x01(\x05R\x05\x62\x65gin\x12\x10\n\x03\x65nd\x18\x04 \x01(\x05R\x03\x65nd\x12R\n\x08semantic\x18\x05 \x01(\x0e\x32\x36.google.protobuf.GeneratedCodeInfo.Annotation.SemanticR\x08semantic\"(\n\x08Semantic\x12\x08\n\x04NONE\x10\x00\x12\x07\n\x03SET\x10\x01\x12\t\n\x05\x41LIAS\x10\x02*\xbe\x02\n\x07\x45\x64ition\x12\x13\n\x0f\x45\x44ITION_UNKNOWN\x10\x00\x12\x13\n\x0e\x45\x44ITION_LEGACY\x10\x84\x07\x12\x13\n\x0e\x45\x44ITION_PROTO2\x10\xe6\x07\x12\x13\n\x0e\x45\x44ITION_PROTO3\x10\xe7\x07\x12\x11\n\x0c\x45\x44ITION_2023\x10\xe8\x07\x12\x11\n\x0c\x45\x44ITION_2024\x10\xe9\x07\x12\x15\n\x10\x45\x44ITION_UNSTABLE\x10\x8fN\x12\x17\n\x13\x45\x44ITION_1_TEST_ONLY\x10\x01\x12\x17\n\x13\x45\x44ITION_2_TEST_ONLY\x10\x02\x12\x1d\n\x17\x45\x44ITION_99997_TEST_ONLY\x10\x9d\x8d\x06\x12\x1d\n\x17\x45\x44ITION_99998_TEST_ONLY\x10\x9e\x8d\x06\x12\x1d\n\x17\x45\x44ITION_99999_TEST_ONLY\x10\x9f\x8d\x06\x12\x13\n\x0b\x45\x44ITION_MAX\x10\xff\xff\xff\xff\x07*U\n\x10SymbolVisibility\x12\x14\n\x10VISIBILITY_UNSET\x10\x00\x12\x14\n\x10VISIBILITY_LOCAL\x10\x01\x12\x15\n\x11VISIBILITY_EXPORT\x10\x02\x42~\n\x13\x63om.google.protobufB\x10\x44\x65scriptorProtosH\x01Z-google.golang.org/protobuf/types/descriptorpb\xf8\x01\x01\xa2\x02\x03GPB\xaa\x02\x1aGoogle.Protobuf.Reflection') + +_globals = globals() +if not _descriptor._USE_C_DESCRIPTORS: + _EDITION = _descriptor.EnumDescriptor( + name='Edition', + full_name='google.protobuf.Edition', + filename=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + values=[ + _descriptor.EnumValueDescriptor( + name='EDITION_UNKNOWN', index=0, number=0, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='EDITION_LEGACY', index=1, number=900, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='EDITION_PROTO2', index=2, number=998, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='EDITION_PROTO3', index=3, number=999, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='EDITION_2023', index=4, number=1000, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='EDITION_2024', index=5, number=1001, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='EDITION_UNSTABLE', index=6, number=9999, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='EDITION_1_TEST_ONLY', index=7, number=1, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='EDITION_2_TEST_ONLY', index=8, number=2, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='EDITION_99997_TEST_ONLY', index=9, number=99997, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='EDITION_99998_TEST_ONLY', index=10, number=99998, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='EDITION_99999_TEST_ONLY', index=11, number=99999, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='EDITION_MAX', index=12, number=2147483647, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + ], + containing_type=None, + serialized_options=None, + ) + _sym_db.RegisterEnumDescriptor(_EDITION) + + _SYMBOLVISIBILITY = _descriptor.EnumDescriptor( + name='SymbolVisibility', + full_name='google.protobuf.SymbolVisibility', + filename=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + values=[ + _descriptor.EnumValueDescriptor( + name='VISIBILITY_UNSET', index=0, number=0, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='VISIBILITY_LOCAL', index=1, number=1, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='VISIBILITY_EXPORT', index=2, number=2, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + ], + containing_type=None, + serialized_options=None, + ) + _sym_db.RegisterEnumDescriptor(_SYMBOLVISIBILITY) + + _EXTENSIONRANGEOPTIONS_VERIFICATIONSTATE = _descriptor.EnumDescriptor( + name='VerificationState', + full_name='google.protobuf.ExtensionRangeOptions.VerificationState', + filename=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + values=[ + _descriptor.EnumValueDescriptor( + name='DECLARATION', index=0, number=0, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='UNVERIFIED', index=1, number=1, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + ], + containing_type=None, + serialized_options=None, + ) + _sym_db.RegisterEnumDescriptor(_EXTENSIONRANGEOPTIONS_VERIFICATIONSTATE) + + _FIELDDESCRIPTORPROTO_TYPE = _descriptor.EnumDescriptor( + name='Type', + full_name='google.protobuf.FieldDescriptorProto.Type', + filename=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + values=[ + _descriptor.EnumValueDescriptor( + name='TYPE_DOUBLE', index=0, number=1, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TYPE_FLOAT', index=1, number=2, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TYPE_INT64', index=2, number=3, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TYPE_UINT64', index=3, number=4, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TYPE_INT32', index=4, number=5, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TYPE_FIXED64', index=5, number=6, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TYPE_FIXED32', index=6, number=7, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TYPE_BOOL', index=7, number=8, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TYPE_STRING', index=8, number=9, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TYPE_GROUP', index=9, number=10, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TYPE_MESSAGE', index=10, number=11, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TYPE_BYTES', index=11, number=12, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TYPE_UINT32', index=12, number=13, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TYPE_ENUM', index=13, number=14, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TYPE_SFIXED32', index=14, number=15, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TYPE_SFIXED64', index=15, number=16, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TYPE_SINT32', index=16, number=17, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TYPE_SINT64', index=17, number=18, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + ], + containing_type=None, + serialized_options=None, + ) + _sym_db.RegisterEnumDescriptor(_FIELDDESCRIPTORPROTO_TYPE) + + _FIELDDESCRIPTORPROTO_LABEL = _descriptor.EnumDescriptor( + name='Label', + full_name='google.protobuf.FieldDescriptorProto.Label', + filename=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + values=[ + _descriptor.EnumValueDescriptor( + name='LABEL_OPTIONAL', index=0, number=1, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='LABEL_REPEATED', index=1, number=3, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='LABEL_REQUIRED', index=2, number=2, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + ], + containing_type=None, + serialized_options=None, + ) + _sym_db.RegisterEnumDescriptor(_FIELDDESCRIPTORPROTO_LABEL) + + _FILEOPTIONS_OPTIMIZEMODE = _descriptor.EnumDescriptor( + name='OptimizeMode', + full_name='google.protobuf.FileOptions.OptimizeMode', + filename=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + values=[ + _descriptor.EnumValueDescriptor( + name='SPEED', index=0, number=1, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='CODE_SIZE', index=1, number=2, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='LITE_RUNTIME', index=2, number=3, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + ], + containing_type=None, + serialized_options=None, + ) + _sym_db.RegisterEnumDescriptor(_FILEOPTIONS_OPTIMIZEMODE) + + _FIELDOPTIONS_CTYPE = _descriptor.EnumDescriptor( + name='CType', + full_name='google.protobuf.FieldOptions.CType', + filename=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + values=[ + _descriptor.EnumValueDescriptor( + name='STRING', index=0, number=0, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='CORD', index=1, number=1, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='STRING_PIECE', index=2, number=2, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + ], + containing_type=None, + serialized_options=None, + ) + _sym_db.RegisterEnumDescriptor(_FIELDOPTIONS_CTYPE) + + _FIELDOPTIONS_JSTYPE = _descriptor.EnumDescriptor( + name='JSType', + full_name='google.protobuf.FieldOptions.JSType', + filename=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + values=[ + _descriptor.EnumValueDescriptor( + name='JS_NORMAL', index=0, number=0, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='JS_STRING', index=1, number=1, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='JS_NUMBER', index=2, number=2, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + ], + containing_type=None, + serialized_options=None, + ) + _sym_db.RegisterEnumDescriptor(_FIELDOPTIONS_JSTYPE) + + _FIELDOPTIONS_OPTIONRETENTION = _descriptor.EnumDescriptor( + name='OptionRetention', + full_name='google.protobuf.FieldOptions.OptionRetention', + filename=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + values=[ + _descriptor.EnumValueDescriptor( + name='RETENTION_UNKNOWN', index=0, number=0, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='RETENTION_RUNTIME', index=1, number=1, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='RETENTION_SOURCE', index=2, number=2, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + ], + containing_type=None, + serialized_options=None, + ) + _sym_db.RegisterEnumDescriptor(_FIELDOPTIONS_OPTIONRETENTION) + + _FIELDOPTIONS_OPTIONTARGETTYPE = _descriptor.EnumDescriptor( + name='OptionTargetType', + full_name='google.protobuf.FieldOptions.OptionTargetType', + filename=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + values=[ + _descriptor.EnumValueDescriptor( + name='TARGET_TYPE_UNKNOWN', index=0, number=0, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TARGET_TYPE_FILE', index=1, number=1, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TARGET_TYPE_EXTENSION_RANGE', index=2, number=2, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TARGET_TYPE_MESSAGE', index=3, number=3, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TARGET_TYPE_FIELD', index=4, number=4, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TARGET_TYPE_ONEOF', index=5, number=5, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TARGET_TYPE_ENUM', index=6, number=6, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TARGET_TYPE_ENUM_ENTRY', index=7, number=7, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TARGET_TYPE_SERVICE', index=8, number=8, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='TARGET_TYPE_METHOD', index=9, number=9, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + ], + containing_type=None, + serialized_options=None, + ) + _sym_db.RegisterEnumDescriptor(_FIELDOPTIONS_OPTIONTARGETTYPE) + + _METHODOPTIONS_IDEMPOTENCYLEVEL = _descriptor.EnumDescriptor( + name='IdempotencyLevel', + full_name='google.protobuf.MethodOptions.IdempotencyLevel', + filename=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + values=[ + _descriptor.EnumValueDescriptor( + name='IDEMPOTENCY_UNKNOWN', index=0, number=0, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='NO_SIDE_EFFECTS', index=1, number=1, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='IDEMPOTENT', index=2, number=2, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + ], + containing_type=None, + serialized_options=None, + ) + _sym_db.RegisterEnumDescriptor(_METHODOPTIONS_IDEMPOTENCYLEVEL) + + _FEATURESET_VISIBILITYFEATURE_DEFAULTSYMBOLVISIBILITY = _descriptor.EnumDescriptor( + name='DefaultSymbolVisibility', + full_name='google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility', + filename=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + values=[ + _descriptor.EnumValueDescriptor( + name='DEFAULT_SYMBOL_VISIBILITY_UNKNOWN', index=0, number=0, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='EXPORT_ALL', index=1, number=1, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='EXPORT_TOP_LEVEL', index=2, number=2, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='LOCAL_ALL', index=3, number=3, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='STRICT', index=4, number=4, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + ], + containing_type=None, + serialized_options=None, + ) + _sym_db.RegisterEnumDescriptor(_FEATURESET_VISIBILITYFEATURE_DEFAULTSYMBOLVISIBILITY) + + _FEATURESET_FIELDPRESENCE = _descriptor.EnumDescriptor( + name='FieldPresence', + full_name='google.protobuf.FeatureSet.FieldPresence', + filename=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + values=[ + _descriptor.EnumValueDescriptor( + name='FIELD_PRESENCE_UNKNOWN', index=0, number=0, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='EXPLICIT', index=1, number=1, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='IMPLICIT', index=2, number=2, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='LEGACY_REQUIRED', index=3, number=3, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + ], + containing_type=None, + serialized_options=None, + ) + _sym_db.RegisterEnumDescriptor(_FEATURESET_FIELDPRESENCE) + + _FEATURESET_ENUMTYPE = _descriptor.EnumDescriptor( + name='EnumType', + full_name='google.protobuf.FeatureSet.EnumType', + filename=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + values=[ + _descriptor.EnumValueDescriptor( + name='ENUM_TYPE_UNKNOWN', index=0, number=0, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='OPEN', index=1, number=1, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='CLOSED', index=2, number=2, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + ], + containing_type=None, + serialized_options=None, + ) + _sym_db.RegisterEnumDescriptor(_FEATURESET_ENUMTYPE) + + _FEATURESET_REPEATEDFIELDENCODING = _descriptor.EnumDescriptor( + name='RepeatedFieldEncoding', + full_name='google.protobuf.FeatureSet.RepeatedFieldEncoding', + filename=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + values=[ + _descriptor.EnumValueDescriptor( + name='REPEATED_FIELD_ENCODING_UNKNOWN', index=0, number=0, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='PACKED', index=1, number=1, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='EXPANDED', index=2, number=2, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + ], + containing_type=None, + serialized_options=None, + ) + _sym_db.RegisterEnumDescriptor(_FEATURESET_REPEATEDFIELDENCODING) + + _FEATURESET_UTF8VALIDATION = _descriptor.EnumDescriptor( + name='Utf8Validation', + full_name='google.protobuf.FeatureSet.Utf8Validation', + filename=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + values=[ + _descriptor.EnumValueDescriptor( + name='UTF8_VALIDATION_UNKNOWN', index=0, number=0, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='VERIFY', index=1, number=2, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='NONE', index=2, number=3, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + ], + containing_type=None, + serialized_options=None, + ) + _sym_db.RegisterEnumDescriptor(_FEATURESET_UTF8VALIDATION) + + _FEATURESET_MESSAGEENCODING = _descriptor.EnumDescriptor( + name='MessageEncoding', + full_name='google.protobuf.FeatureSet.MessageEncoding', + filename=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + values=[ + _descriptor.EnumValueDescriptor( + name='MESSAGE_ENCODING_UNKNOWN', index=0, number=0, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='LENGTH_PREFIXED', index=1, number=1, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='DELIMITED', index=2, number=2, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + ], + containing_type=None, + serialized_options=None, + ) + _sym_db.RegisterEnumDescriptor(_FEATURESET_MESSAGEENCODING) + + _FEATURESET_JSONFORMAT = _descriptor.EnumDescriptor( + name='JsonFormat', + full_name='google.protobuf.FeatureSet.JsonFormat', + filename=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + values=[ + _descriptor.EnumValueDescriptor( + name='JSON_FORMAT_UNKNOWN', index=0, number=0, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='ALLOW', index=1, number=1, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='LEGACY_BEST_EFFORT', index=2, number=2, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + ], + containing_type=None, + serialized_options=None, + ) + _sym_db.RegisterEnumDescriptor(_FEATURESET_JSONFORMAT) + + _FEATURESET_ENFORCENAMINGSTYLE = _descriptor.EnumDescriptor( + name='EnforceNamingStyle', + full_name='google.protobuf.FeatureSet.EnforceNamingStyle', + filename=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + values=[ + _descriptor.EnumValueDescriptor( + name='ENFORCE_NAMING_STYLE_UNKNOWN', index=0, number=0, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='STYLE2024', index=1, number=1, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='STYLE_LEGACY', index=2, number=2, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + ], + containing_type=None, + serialized_options=None, + ) + _sym_db.RegisterEnumDescriptor(_FEATURESET_ENFORCENAMINGSTYLE) + + _GENERATEDCODEINFO_ANNOTATION_SEMANTIC = _descriptor.EnumDescriptor( + name='Semantic', + full_name='google.protobuf.GeneratedCodeInfo.Annotation.Semantic', + filename=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + values=[ + _descriptor.EnumValueDescriptor( + name='NONE', index=0, number=0, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='SET', index=1, number=1, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + _descriptor.EnumValueDescriptor( + name='ALIAS', index=2, number=2, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key), + ], + containing_type=None, + serialized_options=None, + ) + _sym_db.RegisterEnumDescriptor(_GENERATEDCODEINFO_ANNOTATION_SEMANTIC) + + + _FILEDESCRIPTORSET = _descriptor.Descriptor( + name='FileDescriptorSet', + full_name='google.protobuf.FileDescriptorSet', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='file', full_name='google.protobuf.FileDescriptorSet.file', index=0, + number=1, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='file', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=True, + extension_ranges=[(536000000, 536000001), ], + oneofs=[ + ], + ) + + + _FILEDESCRIPTORPROTO = _descriptor.Descriptor( + name='FileDescriptorProto', + full_name='google.protobuf.FileDescriptorProto', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='google.protobuf.FileDescriptorProto.name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='name', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='package', full_name='google.protobuf.FileDescriptorProto.package', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='package', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='dependency', full_name='google.protobuf.FileDescriptorProto.dependency', index=2, + number=3, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='dependency', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='public_dependency', full_name='google.protobuf.FileDescriptorProto.public_dependency', index=3, + number=10, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='publicDependency', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='weak_dependency', full_name='google.protobuf.FileDescriptorProto.weak_dependency', index=4, + number=11, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='weakDependency', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='option_dependency', full_name='google.protobuf.FileDescriptorProto.option_dependency', index=5, + number=15, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='optionDependency', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='message_type', full_name='google.protobuf.FileDescriptorProto.message_type', index=6, + number=4, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='messageType', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='enum_type', full_name='google.protobuf.FileDescriptorProto.enum_type', index=7, + number=5, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='enumType', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='service', full_name='google.protobuf.FileDescriptorProto.service', index=8, + number=6, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='service', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='extension', full_name='google.protobuf.FileDescriptorProto.extension', index=9, + number=7, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='extension', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='options', full_name='google.protobuf.FileDescriptorProto.options', index=10, + number=8, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='options', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='source_code_info', full_name='google.protobuf.FileDescriptorProto.source_code_info', index=11, + number=9, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='sourceCodeInfo', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='syntax', full_name='google.protobuf.FileDescriptorProto.syntax', index=12, + number=12, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='syntax', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='edition', full_name='google.protobuf.FileDescriptorProto.edition', index=13, + number=14, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='edition', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + extension_ranges=[], + oneofs=[ + ], + ) + + + _DESCRIPTORPROTO_EXTENSIONRANGE = _descriptor.Descriptor( + name='ExtensionRange', + full_name='google.protobuf.DescriptorProto.ExtensionRange', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='start', full_name='google.protobuf.DescriptorProto.ExtensionRange.start', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='start', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='end', full_name='google.protobuf.DescriptorProto.ExtensionRange.end', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='end', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='options', full_name='google.protobuf.DescriptorProto.ExtensionRange.options', index=2, + number=3, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='options', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + extension_ranges=[], + oneofs=[ + ], + ) + + _DESCRIPTORPROTO_RESERVEDRANGE = _descriptor.Descriptor( + name='ReservedRange', + full_name='google.protobuf.DescriptorProto.ReservedRange', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='start', full_name='google.protobuf.DescriptorProto.ReservedRange.start', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='start', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='end', full_name='google.protobuf.DescriptorProto.ReservedRange.end', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='end', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + extension_ranges=[], + oneofs=[ + ], + ) + + _DESCRIPTORPROTO = _descriptor.Descriptor( + name='DescriptorProto', + full_name='google.protobuf.DescriptorProto', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='google.protobuf.DescriptorProto.name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='name', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='field', full_name='google.protobuf.DescriptorProto.field', index=1, + number=2, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='field', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='extension', full_name='google.protobuf.DescriptorProto.extension', index=2, + number=6, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='extension', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='nested_type', full_name='google.protobuf.DescriptorProto.nested_type', index=3, + number=3, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='nestedType', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='enum_type', full_name='google.protobuf.DescriptorProto.enum_type', index=4, + number=4, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='enumType', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='extension_range', full_name='google.protobuf.DescriptorProto.extension_range', index=5, + number=5, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='extensionRange', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='oneof_decl', full_name='google.protobuf.DescriptorProto.oneof_decl', index=6, + number=8, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='oneofDecl', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='options', full_name='google.protobuf.DescriptorProto.options', index=7, + number=7, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='options', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='reserved_range', full_name='google.protobuf.DescriptorProto.reserved_range', index=8, + number=9, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='reservedRange', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='reserved_name', full_name='google.protobuf.DescriptorProto.reserved_name', index=9, + number=10, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='reservedName', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='visibility', full_name='google.protobuf.DescriptorProto.visibility', index=10, + number=11, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='visibility', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[_DESCRIPTORPROTO_EXTENSIONRANGE, _DESCRIPTORPROTO_RESERVEDRANGE, ], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + extension_ranges=[], + oneofs=[ + ], + ) + + + _EXTENSIONRANGEOPTIONS_DECLARATION = _descriptor.Descriptor( + name='Declaration', + full_name='google.protobuf.ExtensionRangeOptions.Declaration', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='number', full_name='google.protobuf.ExtensionRangeOptions.Declaration.number', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='number', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='full_name', full_name='google.protobuf.ExtensionRangeOptions.Declaration.full_name', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='fullName', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='type', full_name='google.protobuf.ExtensionRangeOptions.Declaration.type', index=2, + number=3, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='type', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='reserved', full_name='google.protobuf.ExtensionRangeOptions.Declaration.reserved', index=3, + number=5, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='reserved', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='repeated', full_name='google.protobuf.ExtensionRangeOptions.Declaration.repeated', index=4, + number=6, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='repeated', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + extension_ranges=[], + oneofs=[ + ], + ) + + _EXTENSIONRANGEOPTIONS = _descriptor.Descriptor( + name='ExtensionRangeOptions', + full_name='google.protobuf.ExtensionRangeOptions', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='uninterpreted_option', full_name='google.protobuf.ExtensionRangeOptions.uninterpreted_option', index=0, + number=999, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='uninterpretedOption', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='declaration', full_name='google.protobuf.ExtensionRangeOptions.declaration', index=1, + number=2, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\210\001\002', json_name='declaration', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='features', full_name='google.protobuf.ExtensionRangeOptions.features', index=2, + number=50, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='features', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='verification', full_name='google.protobuf.ExtensionRangeOptions.verification', index=3, + number=3, type=14, cpp_type=8, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\210\001\002', json_name='verification', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[_EXTENSIONRANGEOPTIONS_DECLARATION, ], + enum_types=[ + _EXTENSIONRANGEOPTIONS_VERIFICATIONSTATE, + ], + serialized_options=None, + is_extendable=True, + extension_ranges=[(1000, 536870912), ], + oneofs=[ + ], + ) + + + _FIELDDESCRIPTORPROTO = _descriptor.Descriptor( + name='FieldDescriptorProto', + full_name='google.protobuf.FieldDescriptorProto', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='google.protobuf.FieldDescriptorProto.name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='name', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='number', full_name='google.protobuf.FieldDescriptorProto.number', index=1, + number=3, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='number', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='label', full_name='google.protobuf.FieldDescriptorProto.label', index=2, + number=4, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='label', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='type', full_name='google.protobuf.FieldDescriptorProto.type', index=3, + number=5, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='type', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='type_name', full_name='google.protobuf.FieldDescriptorProto.type_name', index=4, + number=6, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='typeName', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='extendee', full_name='google.protobuf.FieldDescriptorProto.extendee', index=5, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='extendee', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='default_value', full_name='google.protobuf.FieldDescriptorProto.default_value', index=6, + number=7, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='defaultValue', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='oneof_index', full_name='google.protobuf.FieldDescriptorProto.oneof_index', index=7, + number=9, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='oneofIndex', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='json_name', full_name='google.protobuf.FieldDescriptorProto.json_name', index=8, + number=10, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='jsonName', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='options', full_name='google.protobuf.FieldDescriptorProto.options', index=9, + number=8, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='options', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='proto3_optional', full_name='google.protobuf.FieldDescriptorProto.proto3_optional', index=10, + number=17, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='proto3Optional', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + _FIELDDESCRIPTORPROTO_TYPE, + _FIELDDESCRIPTORPROTO_LABEL, + ], + serialized_options=None, + is_extendable=False, + extension_ranges=[], + oneofs=[ + ], + ) + + + _ONEOFDESCRIPTORPROTO = _descriptor.Descriptor( + name='OneofDescriptorProto', + full_name='google.protobuf.OneofDescriptorProto', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='google.protobuf.OneofDescriptorProto.name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='name', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='options', full_name='google.protobuf.OneofDescriptorProto.options', index=1, + number=2, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='options', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + extension_ranges=[], + oneofs=[ + ], + ) + + + _ENUMDESCRIPTORPROTO_ENUMRESERVEDRANGE = _descriptor.Descriptor( + name='EnumReservedRange', + full_name='google.protobuf.EnumDescriptorProto.EnumReservedRange', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='start', full_name='google.protobuf.EnumDescriptorProto.EnumReservedRange.start', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='start', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='end', full_name='google.protobuf.EnumDescriptorProto.EnumReservedRange.end', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='end', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + extension_ranges=[], + oneofs=[ + ], + ) + + _ENUMDESCRIPTORPROTO = _descriptor.Descriptor( + name='EnumDescriptorProto', + full_name='google.protobuf.EnumDescriptorProto', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='google.protobuf.EnumDescriptorProto.name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='name', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='value', full_name='google.protobuf.EnumDescriptorProto.value', index=1, + number=2, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='value', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='options', full_name='google.protobuf.EnumDescriptorProto.options', index=2, + number=3, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='options', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='reserved_range', full_name='google.protobuf.EnumDescriptorProto.reserved_range', index=3, + number=4, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='reservedRange', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='reserved_name', full_name='google.protobuf.EnumDescriptorProto.reserved_name', index=4, + number=5, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='reservedName', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='visibility', full_name='google.protobuf.EnumDescriptorProto.visibility', index=5, + number=6, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='visibility', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[_ENUMDESCRIPTORPROTO_ENUMRESERVEDRANGE, ], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + extension_ranges=[], + oneofs=[ + ], + ) + + + _ENUMVALUEDESCRIPTORPROTO = _descriptor.Descriptor( + name='EnumValueDescriptorProto', + full_name='google.protobuf.EnumValueDescriptorProto', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='google.protobuf.EnumValueDescriptorProto.name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='name', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='number', full_name='google.protobuf.EnumValueDescriptorProto.number', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='number', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='options', full_name='google.protobuf.EnumValueDescriptorProto.options', index=2, + number=3, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='options', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + extension_ranges=[], + oneofs=[ + ], + ) + + + _SERVICEDESCRIPTORPROTO = _descriptor.Descriptor( + name='ServiceDescriptorProto', + full_name='google.protobuf.ServiceDescriptorProto', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='google.protobuf.ServiceDescriptorProto.name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='name', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='method', full_name='google.protobuf.ServiceDescriptorProto.method', index=1, + number=2, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='method', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='options', full_name='google.protobuf.ServiceDescriptorProto.options', index=2, + number=3, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='options', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + extension_ranges=[], + oneofs=[ + ], + ) + + + _METHODDESCRIPTORPROTO = _descriptor.Descriptor( + name='MethodDescriptorProto', + full_name='google.protobuf.MethodDescriptorProto', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='google.protobuf.MethodDescriptorProto.name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='name', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='input_type', full_name='google.protobuf.MethodDescriptorProto.input_type', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='inputType', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='output_type', full_name='google.protobuf.MethodDescriptorProto.output_type', index=2, + number=3, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='outputType', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='options', full_name='google.protobuf.MethodDescriptorProto.options', index=3, + number=4, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='options', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='client_streaming', full_name='google.protobuf.MethodDescriptorProto.client_streaming', index=4, + number=5, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='clientStreaming', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='server_streaming', full_name='google.protobuf.MethodDescriptorProto.server_streaming', index=5, + number=6, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='serverStreaming', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + extension_ranges=[], + oneofs=[ + ], + ) + + + _FILEOPTIONS = _descriptor.Descriptor( + name='FileOptions', + full_name='google.protobuf.FileOptions', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='java_package', full_name='google.protobuf.FileOptions.java_package', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='javaPackage', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='java_outer_classname', full_name='google.protobuf.FileOptions.java_outer_classname', index=1, + number=8, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='javaOuterClassname', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='java_multiple_files', full_name='google.protobuf.FileOptions.java_multiple_files', index=2, + number=10, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='javaMultipleFiles', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='java_generate_equals_and_hash', full_name='google.protobuf.FileOptions.java_generate_equals_and_hash', index=3, + number=20, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\030\001', json_name='javaGenerateEqualsAndHash', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='java_string_check_utf8', full_name='google.protobuf.FileOptions.java_string_check_utf8', index=4, + number=27, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='javaStringCheckUtf8', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='optimize_for', full_name='google.protobuf.FileOptions.optimize_for', index=5, + number=9, type=14, cpp_type=8, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='optimizeFor', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='go_package', full_name='google.protobuf.FileOptions.go_package', index=6, + number=11, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='goPackage', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='cc_generic_services', full_name='google.protobuf.FileOptions.cc_generic_services', index=7, + number=16, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='ccGenericServices', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='java_generic_services', full_name='google.protobuf.FileOptions.java_generic_services', index=8, + number=17, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='javaGenericServices', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='py_generic_services', full_name='google.protobuf.FileOptions.py_generic_services', index=9, + number=18, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='pyGenericServices', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='deprecated', full_name='google.protobuf.FileOptions.deprecated', index=10, + number=23, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='deprecated', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='cc_enable_arenas', full_name='google.protobuf.FileOptions.cc_enable_arenas', index=11, + number=31, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='ccEnableArenas', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='objc_class_prefix', full_name='google.protobuf.FileOptions.objc_class_prefix', index=12, + number=36, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='objcClassPrefix', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='csharp_namespace', full_name='google.protobuf.FileOptions.csharp_namespace', index=13, + number=37, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='csharpNamespace', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='swift_prefix', full_name='google.protobuf.FileOptions.swift_prefix', index=14, + number=39, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='swiftPrefix', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='php_class_prefix', full_name='google.protobuf.FileOptions.php_class_prefix', index=15, + number=40, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='phpClassPrefix', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='php_namespace', full_name='google.protobuf.FileOptions.php_namespace', index=16, + number=41, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='phpNamespace', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='php_metadata_namespace', full_name='google.protobuf.FileOptions.php_metadata_namespace', index=17, + number=44, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='phpMetadataNamespace', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='ruby_package', full_name='google.protobuf.FileOptions.ruby_package', index=18, + number=45, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='rubyPackage', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='features', full_name='google.protobuf.FileOptions.features', index=19, + number=50, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='features', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='uninterpreted_option', full_name='google.protobuf.FileOptions.uninterpreted_option', index=20, + number=999, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='uninterpretedOption', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + _FILEOPTIONS_OPTIMIZEMODE, + ], + serialized_options=None, + is_extendable=True, + extension_ranges=[(1000, 536870912), ], + oneofs=[ + ], + ) + + + _MESSAGEOPTIONS = _descriptor.Descriptor( + name='MessageOptions', + full_name='google.protobuf.MessageOptions', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='message_set_wire_format', full_name='google.protobuf.MessageOptions.message_set_wire_format', index=0, + number=1, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='messageSetWireFormat', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='no_standard_descriptor_accessor', full_name='google.protobuf.MessageOptions.no_standard_descriptor_accessor', index=1, + number=2, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='noStandardDescriptorAccessor', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='deprecated', full_name='google.protobuf.MessageOptions.deprecated', index=2, + number=3, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='deprecated', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='map_entry', full_name='google.protobuf.MessageOptions.map_entry', index=3, + number=7, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='mapEntry', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='deprecated_legacy_json_field_conflicts', full_name='google.protobuf.MessageOptions.deprecated_legacy_json_field_conflicts', index=4, + number=11, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\030\001', json_name='deprecatedLegacyJsonFieldConflicts', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='features', full_name='google.protobuf.MessageOptions.features', index=5, + number=12, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='features', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='uninterpreted_option', full_name='google.protobuf.MessageOptions.uninterpreted_option', index=6, + number=999, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='uninterpretedOption', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=True, + extension_ranges=[(1000, 536870912), ], + oneofs=[ + ], + ) + + + _FIELDOPTIONS_EDITIONDEFAULT = _descriptor.Descriptor( + name='EditionDefault', + full_name='google.protobuf.FieldOptions.EditionDefault', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='edition', full_name='google.protobuf.FieldOptions.EditionDefault.edition', index=0, + number=3, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='edition', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='value', full_name='google.protobuf.FieldOptions.EditionDefault.value', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='value', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + extension_ranges=[], + oneofs=[ + ], + ) + + _FIELDOPTIONS_FEATURESUPPORT = _descriptor.Descriptor( + name='FeatureSupport', + full_name='google.protobuf.FieldOptions.FeatureSupport', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='edition_introduced', full_name='google.protobuf.FieldOptions.FeatureSupport.edition_introduced', index=0, + number=1, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='editionIntroduced', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='edition_deprecated', full_name='google.protobuf.FieldOptions.FeatureSupport.edition_deprecated', index=1, + number=2, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='editionDeprecated', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='deprecation_warning', full_name='google.protobuf.FieldOptions.FeatureSupport.deprecation_warning', index=2, + number=3, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='deprecationWarning', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='edition_removed', full_name='google.protobuf.FieldOptions.FeatureSupport.edition_removed', index=3, + number=4, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='editionRemoved', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + extension_ranges=[], + oneofs=[ + ], + ) + + _FIELDOPTIONS = _descriptor.Descriptor( + name='FieldOptions', + full_name='google.protobuf.FieldOptions', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='ctype', full_name='google.protobuf.FieldOptions.ctype', index=0, + number=1, type=14, cpp_type=8, label=1, + has_default_value=True, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='ctype', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='packed', full_name='google.protobuf.FieldOptions.packed', index=1, + number=2, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='packed', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='jstype', full_name='google.protobuf.FieldOptions.jstype', index=2, + number=6, type=14, cpp_type=8, label=1, + has_default_value=True, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='jstype', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='lazy', full_name='google.protobuf.FieldOptions.lazy', index=3, + number=5, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='lazy', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='unverified_lazy', full_name='google.protobuf.FieldOptions.unverified_lazy', index=4, + number=15, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='unverifiedLazy', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='deprecated', full_name='google.protobuf.FieldOptions.deprecated', index=5, + number=3, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='deprecated', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='weak', full_name='google.protobuf.FieldOptions.weak', index=6, + number=10, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\030\001', json_name='weak', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='debug_redact', full_name='google.protobuf.FieldOptions.debug_redact', index=7, + number=16, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='debugRedact', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='retention', full_name='google.protobuf.FieldOptions.retention', index=8, + number=17, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='retention', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='targets', full_name='google.protobuf.FieldOptions.targets', index=9, + number=19, type=14, cpp_type=8, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='targets', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='edition_defaults', full_name='google.protobuf.FieldOptions.edition_defaults', index=10, + number=20, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='editionDefaults', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='features', full_name='google.protobuf.FieldOptions.features', index=11, + number=21, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='features', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='feature_support', full_name='google.protobuf.FieldOptions.feature_support', index=12, + number=22, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='featureSupport', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='uninterpreted_option', full_name='google.protobuf.FieldOptions.uninterpreted_option', index=13, + number=999, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='uninterpretedOption', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[_FIELDOPTIONS_EDITIONDEFAULT, _FIELDOPTIONS_FEATURESUPPORT, ], + enum_types=[ + _FIELDOPTIONS_CTYPE, + _FIELDOPTIONS_JSTYPE, + _FIELDOPTIONS_OPTIONRETENTION, + _FIELDOPTIONS_OPTIONTARGETTYPE, + ], + serialized_options=None, + is_extendable=True, + extension_ranges=[(1000, 536870912), ], + oneofs=[ + ], + ) + + + _ONEOFOPTIONS = _descriptor.Descriptor( + name='OneofOptions', + full_name='google.protobuf.OneofOptions', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='features', full_name='google.protobuf.OneofOptions.features', index=0, + number=1, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='features', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='uninterpreted_option', full_name='google.protobuf.OneofOptions.uninterpreted_option', index=1, + number=999, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='uninterpretedOption', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=True, + extension_ranges=[(1000, 536870912), ], + oneofs=[ + ], + ) + + + _ENUMOPTIONS = _descriptor.Descriptor( + name='EnumOptions', + full_name='google.protobuf.EnumOptions', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='allow_alias', full_name='google.protobuf.EnumOptions.allow_alias', index=0, + number=2, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='allowAlias', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='deprecated', full_name='google.protobuf.EnumOptions.deprecated', index=1, + number=3, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='deprecated', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='deprecated_legacy_json_field_conflicts', full_name='google.protobuf.EnumOptions.deprecated_legacy_json_field_conflicts', index=2, + number=6, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\030\001', json_name='deprecatedLegacyJsonFieldConflicts', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='features', full_name='google.protobuf.EnumOptions.features', index=3, + number=7, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='features', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='uninterpreted_option', full_name='google.protobuf.EnumOptions.uninterpreted_option', index=4, + number=999, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='uninterpretedOption', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=True, + extension_ranges=[(1000, 536870912), ], + oneofs=[ + ], + ) + + + _ENUMVALUEOPTIONS = _descriptor.Descriptor( + name='EnumValueOptions', + full_name='google.protobuf.EnumValueOptions', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='deprecated', full_name='google.protobuf.EnumValueOptions.deprecated', index=0, + number=1, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='deprecated', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='features', full_name='google.protobuf.EnumValueOptions.features', index=1, + number=2, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='features', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='debug_redact', full_name='google.protobuf.EnumValueOptions.debug_redact', index=2, + number=3, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='debugRedact', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='feature_support', full_name='google.protobuf.EnumValueOptions.feature_support', index=3, + number=4, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='featureSupport', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='uninterpreted_option', full_name='google.protobuf.EnumValueOptions.uninterpreted_option', index=4, + number=999, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='uninterpretedOption', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=True, + extension_ranges=[(1000, 536870912), ], + oneofs=[ + ], + ) + + + _SERVICEOPTIONS = _descriptor.Descriptor( + name='ServiceOptions', + full_name='google.protobuf.ServiceOptions', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='features', full_name='google.protobuf.ServiceOptions.features', index=0, + number=34, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='features', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='deprecated', full_name='google.protobuf.ServiceOptions.deprecated', index=1, + number=33, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='deprecated', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='uninterpreted_option', full_name='google.protobuf.ServiceOptions.uninterpreted_option', index=2, + number=999, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='uninterpretedOption', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=True, + extension_ranges=[(1000, 536870912), ], + oneofs=[ + ], + ) + + + _METHODOPTIONS = _descriptor.Descriptor( + name='MethodOptions', + full_name='google.protobuf.MethodOptions', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='deprecated', full_name='google.protobuf.MethodOptions.deprecated', index=0, + number=33, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='deprecated', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='idempotency_level', full_name='google.protobuf.MethodOptions.idempotency_level', index=1, + number=34, type=14, cpp_type=8, label=1, + has_default_value=True, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='idempotencyLevel', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='features', full_name='google.protobuf.MethodOptions.features', index=2, + number=35, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='features', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='uninterpreted_option', full_name='google.protobuf.MethodOptions.uninterpreted_option', index=3, + number=999, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='uninterpretedOption', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + _METHODOPTIONS_IDEMPOTENCYLEVEL, + ], + serialized_options=None, + is_extendable=True, + extension_ranges=[(1000, 536870912), ], + oneofs=[ + ], + ) + + + _UNINTERPRETEDOPTION_NAMEPART = _descriptor.Descriptor( + name='NamePart', + full_name='google.protobuf.UninterpretedOption.NamePart', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='name_part', full_name='google.protobuf.UninterpretedOption.NamePart.name_part', index=0, + number=1, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='namePart', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='is_extension', full_name='google.protobuf.UninterpretedOption.NamePart.is_extension', index=1, + number=2, type=8, cpp_type=7, label=2, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='isExtension', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + extension_ranges=[], + oneofs=[ + ], + ) + + _UNINTERPRETEDOPTION = _descriptor.Descriptor( + name='UninterpretedOption', + full_name='google.protobuf.UninterpretedOption', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='google.protobuf.UninterpretedOption.name', index=0, + number=2, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='name', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='identifier_value', full_name='google.protobuf.UninterpretedOption.identifier_value', index=1, + number=3, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='identifierValue', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='positive_int_value', full_name='google.protobuf.UninterpretedOption.positive_int_value', index=2, + number=4, type=4, cpp_type=4, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='positiveIntValue', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='negative_int_value', full_name='google.protobuf.UninterpretedOption.negative_int_value', index=3, + number=5, type=3, cpp_type=2, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='negativeIntValue', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='double_value', full_name='google.protobuf.UninterpretedOption.double_value', index=4, + number=6, type=1, cpp_type=5, label=1, + has_default_value=False, default_value=float(0), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='doubleValue', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='string_value', full_name='google.protobuf.UninterpretedOption.string_value', index=5, + number=7, type=12, cpp_type=9, label=1, + has_default_value=False, default_value=b"", + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='stringValue', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='aggregate_value', full_name='google.protobuf.UninterpretedOption.aggregate_value', index=6, + number=8, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='aggregateValue', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[_UNINTERPRETEDOPTION_NAMEPART, ], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + extension_ranges=[], + oneofs=[ + ], + ) + + + _FEATURESET_VISIBILITYFEATURE = _descriptor.Descriptor( + name='VisibilityFeature', + full_name='google.protobuf.FeatureSet.VisibilityFeature', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + _FEATURESET_VISIBILITYFEATURE_DEFAULTSYMBOLVISIBILITY, + ], + serialized_options=None, + is_extendable=False, + extension_ranges=[], + oneofs=[ + ], + ) + + _FEATURESET = _descriptor.Descriptor( + name='FeatureSet', + full_name='google.protobuf.FeatureSet', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='field_presence', full_name='google.protobuf.FeatureSet.field_presence', index=0, + number=1, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\210\001\001\230\001\004\230\001\001\242\001\r\022\010EXPLICIT\030\204\007\242\001\r\022\010IMPLICIT\030\347\007\242\001\r\022\010EXPLICIT\030\350\007\262\001\003\010\350\007', json_name='fieldPresence', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='enum_type', full_name='google.protobuf.FeatureSet.enum_type', index=1, + number=2, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\210\001\001\230\001\006\230\001\001\242\001\013\022\006CLOSED\030\204\007\242\001\t\022\004OPEN\030\347\007\262\001\003\010\350\007', json_name='enumType', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='repeated_field_encoding', full_name='google.protobuf.FeatureSet.repeated_field_encoding', index=2, + number=3, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\210\001\001\230\001\004\230\001\001\242\001\r\022\010EXPANDED\030\204\007\242\001\013\022\006PACKED\030\347\007\262\001\003\010\350\007', json_name='repeatedFieldEncoding', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='utf8_validation', full_name='google.protobuf.FeatureSet.utf8_validation', index=3, + number=4, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\210\001\001\230\001\004\230\001\001\242\001\t\022\004NONE\030\204\007\242\001\013\022\006VERIFY\030\347\007\262\001\003\010\350\007', json_name='utf8Validation', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='message_encoding', full_name='google.protobuf.FeatureSet.message_encoding', index=4, + number=5, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\210\001\001\230\001\004\230\001\001\242\001\024\022\017LENGTH_PREFIXED\030\204\007\262\001\003\010\350\007', json_name='messageEncoding', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='json_format', full_name='google.protobuf.FeatureSet.json_format', index=5, + number=6, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\210\001\001\230\001\003\230\001\006\230\001\001\242\001\027\022\022LEGACY_BEST_EFFORT\030\204\007\242\001\n\022\005ALLOW\030\347\007\262\001\003\010\350\007', json_name='jsonFormat', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='enforce_naming_style', full_name='google.protobuf.FeatureSet.enforce_naming_style', index=6, + number=7, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\210\001\002\230\001\001\230\001\002\230\001\003\230\001\004\230\001\005\230\001\006\230\001\007\230\001\010\230\001\t\242\001\021\022\014STYLE_LEGACY\030\204\007\242\001\016\022\tSTYLE2024\030\351\007\262\001\003\010\351\007', json_name='enforceNamingStyle', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='default_symbol_visibility', full_name='google.protobuf.FeatureSet.default_symbol_visibility', index=7, + number=8, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\210\001\002\230\001\001\242\001\017\022\nEXPORT_ALL\030\204\007\242\001\025\022\020EXPORT_TOP_LEVEL\030\351\007\262\001\003\010\351\007', json_name='defaultSymbolVisibility', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[_FEATURESET_VISIBILITYFEATURE, ], + enum_types=[ + _FEATURESET_FIELDPRESENCE, + _FEATURESET_ENUMTYPE, + _FEATURESET_REPEATEDFIELDENCODING, + _FEATURESET_UTF8VALIDATION, + _FEATURESET_MESSAGEENCODING, + _FEATURESET_JSONFORMAT, + _FEATURESET_ENFORCENAMINGSTYLE, + ], + serialized_options=None, + is_extendable=True, + extension_ranges=[(1000, 9995), (9995, 10000), (10000, 10001), ], + oneofs=[ + ], + ) + + + _FEATURESETDEFAULTS_FEATURESETEDITIONDEFAULT = _descriptor.Descriptor( + name='FeatureSetEditionDefault', + full_name='google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='edition', full_name='google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault.edition', index=0, + number=3, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='edition', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='overridable_features', full_name='google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault.overridable_features', index=1, + number=4, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='overridableFeatures', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='fixed_features', full_name='google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault.fixed_features', index=2, + number=5, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='fixedFeatures', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + extension_ranges=[], + oneofs=[ + ], + ) + + _FEATURESETDEFAULTS = _descriptor.Descriptor( + name='FeatureSetDefaults', + full_name='google.protobuf.FeatureSetDefaults', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='defaults', full_name='google.protobuf.FeatureSetDefaults.defaults', index=0, + number=1, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='defaults', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='minimum_edition', full_name='google.protobuf.FeatureSetDefaults.minimum_edition', index=1, + number=4, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='minimumEdition', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='maximum_edition', full_name='google.protobuf.FeatureSetDefaults.maximum_edition', index=2, + number=5, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='maximumEdition', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[_FEATURESETDEFAULTS_FEATURESETEDITIONDEFAULT, ], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + extension_ranges=[], + oneofs=[ + ], + ) + + + _SOURCECODEINFO_LOCATION = _descriptor.Descriptor( + name='Location', + full_name='google.protobuf.SourceCodeInfo.Location', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='path', full_name='google.protobuf.SourceCodeInfo.Location.path', index=0, + number=1, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\020\001', json_name='path', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='span', full_name='google.protobuf.SourceCodeInfo.Location.span', index=1, + number=2, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\020\001', json_name='span', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='leading_comments', full_name='google.protobuf.SourceCodeInfo.Location.leading_comments', index=2, + number=3, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='leadingComments', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='trailing_comments', full_name='google.protobuf.SourceCodeInfo.Location.trailing_comments', index=3, + number=4, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='trailingComments', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='leading_detached_comments', full_name='google.protobuf.SourceCodeInfo.Location.leading_detached_comments', index=4, + number=6, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='leadingDetachedComments', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + extension_ranges=[], + oneofs=[ + ], + ) + + _SOURCECODEINFO = _descriptor.Descriptor( + name='SourceCodeInfo', + full_name='google.protobuf.SourceCodeInfo', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='location', full_name='google.protobuf.SourceCodeInfo.location', index=0, + number=1, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='location', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[_SOURCECODEINFO_LOCATION, ], + enum_types=[ + ], + serialized_options=None, + is_extendable=True, + extension_ranges=[(536000000, 536000001), ], + oneofs=[ + ], + ) + + + _GENERATEDCODEINFO_ANNOTATION = _descriptor.Descriptor( + name='Annotation', + full_name='google.protobuf.GeneratedCodeInfo.Annotation', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='path', full_name='google.protobuf.GeneratedCodeInfo.Annotation.path', index=0, + number=1, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=b'\020\001', json_name='path', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='source_file', full_name='google.protobuf.GeneratedCodeInfo.Annotation.source_file', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=b"".decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='sourceFile', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='begin', full_name='google.protobuf.GeneratedCodeInfo.Annotation.begin', index=2, + number=3, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='begin', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='end', full_name='google.protobuf.GeneratedCodeInfo.Annotation.end', index=3, + number=4, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='end', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + _descriptor.FieldDescriptor( + name='semantic', full_name='google.protobuf.GeneratedCodeInfo.Annotation.semantic', index=4, + number=5, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='semantic', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + _GENERATEDCODEINFO_ANNOTATION_SEMANTIC, + ], + serialized_options=None, + is_extendable=False, + extension_ranges=[], + oneofs=[ + ], + ) + + _GENERATEDCODEINFO = _descriptor.Descriptor( + name='GeneratedCodeInfo', + full_name='google.protobuf.GeneratedCodeInfo', + filename=None, + file=DESCRIPTOR, + containing_type=None, + create_key=_descriptor._internal_create_key, + fields=[ + _descriptor.FieldDescriptor( + name='annotation', full_name='google.protobuf.GeneratedCodeInfo.annotation', index=0, + number=1, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + serialized_options=None, json_name='annotation', file=DESCRIPTOR, create_key=_descriptor._internal_create_key), + ], + extensions=[ + ], + nested_types=[_GENERATEDCODEINFO_ANNOTATION, ], + enum_types=[ + ], + serialized_options=None, + is_extendable=False, + extension_ranges=[], + oneofs=[ + ], + ) + + _FILEDESCRIPTORSET.fields_by_name['file'].message_type = _FILEDESCRIPTORPROTO + _FILEDESCRIPTORPROTO.fields_by_name['message_type'].message_type = _DESCRIPTORPROTO + _FILEDESCRIPTORPROTO.fields_by_name['enum_type'].message_type = _ENUMDESCRIPTORPROTO + _FILEDESCRIPTORPROTO.fields_by_name['service'].message_type = _SERVICEDESCRIPTORPROTO + _FILEDESCRIPTORPROTO.fields_by_name['extension'].message_type = _FIELDDESCRIPTORPROTO + _FILEDESCRIPTORPROTO.fields_by_name['options'].message_type = _FILEOPTIONS + _FILEDESCRIPTORPROTO.fields_by_name['source_code_info'].message_type = _SOURCECODEINFO + _FILEDESCRIPTORPROTO.fields_by_name['edition'].enum_type = _EDITION + _DESCRIPTORPROTO_EXTENSIONRANGE.fields_by_name['options'].message_type = _EXTENSIONRANGEOPTIONS + _DESCRIPTORPROTO_EXTENSIONRANGE.containing_type = _DESCRIPTORPROTO + _DESCRIPTORPROTO_RESERVEDRANGE.containing_type = _DESCRIPTORPROTO + _DESCRIPTORPROTO.fields_by_name['field'].message_type = _FIELDDESCRIPTORPROTO + _DESCRIPTORPROTO.fields_by_name['extension'].message_type = _FIELDDESCRIPTORPROTO + _DESCRIPTORPROTO.fields_by_name['nested_type'].message_type = _DESCRIPTORPROTO + _DESCRIPTORPROTO.fields_by_name['enum_type'].message_type = _ENUMDESCRIPTORPROTO + _DESCRIPTORPROTO.fields_by_name['extension_range'].message_type = _DESCRIPTORPROTO_EXTENSIONRANGE + _DESCRIPTORPROTO.fields_by_name['oneof_decl'].message_type = _ONEOFDESCRIPTORPROTO + _DESCRIPTORPROTO.fields_by_name['options'].message_type = _MESSAGEOPTIONS + _DESCRIPTORPROTO.fields_by_name['reserved_range'].message_type = _DESCRIPTORPROTO_RESERVEDRANGE + _DESCRIPTORPROTO.fields_by_name['visibility'].enum_type = _SYMBOLVISIBILITY + _EXTENSIONRANGEOPTIONS_DECLARATION.containing_type = _EXTENSIONRANGEOPTIONS + _EXTENSIONRANGEOPTIONS.fields_by_name['uninterpreted_option'].message_type = _UNINTERPRETEDOPTION + _EXTENSIONRANGEOPTIONS.fields_by_name['declaration'].message_type = _EXTENSIONRANGEOPTIONS_DECLARATION + _EXTENSIONRANGEOPTIONS.fields_by_name['features'].message_type = _FEATURESET + _EXTENSIONRANGEOPTIONS.fields_by_name['verification'].enum_type = _EXTENSIONRANGEOPTIONS_VERIFICATIONSTATE + _EXTENSIONRANGEOPTIONS_VERIFICATIONSTATE.containing_type = _EXTENSIONRANGEOPTIONS + _FIELDDESCRIPTORPROTO.fields_by_name['label'].enum_type = _FIELDDESCRIPTORPROTO_LABEL + _FIELDDESCRIPTORPROTO.fields_by_name['type'].enum_type = _FIELDDESCRIPTORPROTO_TYPE + _FIELDDESCRIPTORPROTO.fields_by_name['options'].message_type = _FIELDOPTIONS + _FIELDDESCRIPTORPROTO_TYPE.containing_type = _FIELDDESCRIPTORPROTO + _FIELDDESCRIPTORPROTO_LABEL.containing_type = _FIELDDESCRIPTORPROTO + _ONEOFDESCRIPTORPROTO.fields_by_name['options'].message_type = _ONEOFOPTIONS + _ENUMDESCRIPTORPROTO_ENUMRESERVEDRANGE.containing_type = _ENUMDESCRIPTORPROTO + _ENUMDESCRIPTORPROTO.fields_by_name['value'].message_type = _ENUMVALUEDESCRIPTORPROTO + _ENUMDESCRIPTORPROTO.fields_by_name['options'].message_type = _ENUMOPTIONS + _ENUMDESCRIPTORPROTO.fields_by_name['reserved_range'].message_type = _ENUMDESCRIPTORPROTO_ENUMRESERVEDRANGE + _ENUMDESCRIPTORPROTO.fields_by_name['visibility'].enum_type = _SYMBOLVISIBILITY + _ENUMVALUEDESCRIPTORPROTO.fields_by_name['options'].message_type = _ENUMVALUEOPTIONS + _SERVICEDESCRIPTORPROTO.fields_by_name['method'].message_type = _METHODDESCRIPTORPROTO + _SERVICEDESCRIPTORPROTO.fields_by_name['options'].message_type = _SERVICEOPTIONS + _METHODDESCRIPTORPROTO.fields_by_name['options'].message_type = _METHODOPTIONS + _FILEOPTIONS.fields_by_name['optimize_for'].enum_type = _FILEOPTIONS_OPTIMIZEMODE + _FILEOPTIONS.fields_by_name['features'].message_type = _FEATURESET + _FILEOPTIONS.fields_by_name['uninterpreted_option'].message_type = _UNINTERPRETEDOPTION + _FILEOPTIONS_OPTIMIZEMODE.containing_type = _FILEOPTIONS + _MESSAGEOPTIONS.fields_by_name['features'].message_type = _FEATURESET + _MESSAGEOPTIONS.fields_by_name['uninterpreted_option'].message_type = _UNINTERPRETEDOPTION + _FIELDOPTIONS_EDITIONDEFAULT.fields_by_name['edition'].enum_type = _EDITION + _FIELDOPTIONS_EDITIONDEFAULT.containing_type = _FIELDOPTIONS + _FIELDOPTIONS_FEATURESUPPORT.fields_by_name['edition_introduced'].enum_type = _EDITION + _FIELDOPTIONS_FEATURESUPPORT.fields_by_name['edition_deprecated'].enum_type = _EDITION + _FIELDOPTIONS_FEATURESUPPORT.fields_by_name['edition_removed'].enum_type = _EDITION + _FIELDOPTIONS_FEATURESUPPORT.containing_type = _FIELDOPTIONS + _FIELDOPTIONS.fields_by_name['ctype'].enum_type = _FIELDOPTIONS_CTYPE + _FIELDOPTIONS.fields_by_name['jstype'].enum_type = _FIELDOPTIONS_JSTYPE + _FIELDOPTIONS.fields_by_name['retention'].enum_type = _FIELDOPTIONS_OPTIONRETENTION + _FIELDOPTIONS.fields_by_name['targets'].enum_type = _FIELDOPTIONS_OPTIONTARGETTYPE + _FIELDOPTIONS.fields_by_name['edition_defaults'].message_type = _FIELDOPTIONS_EDITIONDEFAULT + _FIELDOPTIONS.fields_by_name['features'].message_type = _FEATURESET + _FIELDOPTIONS.fields_by_name['feature_support'].message_type = _FIELDOPTIONS_FEATURESUPPORT + _FIELDOPTIONS.fields_by_name['uninterpreted_option'].message_type = _UNINTERPRETEDOPTION + _FIELDOPTIONS_CTYPE.containing_type = _FIELDOPTIONS + _FIELDOPTIONS_JSTYPE.containing_type = _FIELDOPTIONS + _FIELDOPTIONS_OPTIONRETENTION.containing_type = _FIELDOPTIONS + _FIELDOPTIONS_OPTIONTARGETTYPE.containing_type = _FIELDOPTIONS + _ONEOFOPTIONS.fields_by_name['features'].message_type = _FEATURESET + _ONEOFOPTIONS.fields_by_name['uninterpreted_option'].message_type = _UNINTERPRETEDOPTION + _ENUMOPTIONS.fields_by_name['features'].message_type = _FEATURESET + _ENUMOPTIONS.fields_by_name['uninterpreted_option'].message_type = _UNINTERPRETEDOPTION + _ENUMVALUEOPTIONS.fields_by_name['features'].message_type = _FEATURESET + _ENUMVALUEOPTIONS.fields_by_name['feature_support'].message_type = _FIELDOPTIONS_FEATURESUPPORT + _ENUMVALUEOPTIONS.fields_by_name['uninterpreted_option'].message_type = _UNINTERPRETEDOPTION + _SERVICEOPTIONS.fields_by_name['features'].message_type = _FEATURESET + _SERVICEOPTIONS.fields_by_name['uninterpreted_option'].message_type = _UNINTERPRETEDOPTION + _METHODOPTIONS.fields_by_name['idempotency_level'].enum_type = _METHODOPTIONS_IDEMPOTENCYLEVEL + _METHODOPTIONS.fields_by_name['features'].message_type = _FEATURESET + _METHODOPTIONS.fields_by_name['uninterpreted_option'].message_type = _UNINTERPRETEDOPTION + _METHODOPTIONS_IDEMPOTENCYLEVEL.containing_type = _METHODOPTIONS + _UNINTERPRETEDOPTION_NAMEPART.containing_type = _UNINTERPRETEDOPTION + _UNINTERPRETEDOPTION.fields_by_name['name'].message_type = _UNINTERPRETEDOPTION_NAMEPART + _FEATURESET_VISIBILITYFEATURE.containing_type = _FEATURESET + _FEATURESET_VISIBILITYFEATURE_DEFAULTSYMBOLVISIBILITY.containing_type = _FEATURESET_VISIBILITYFEATURE + _FEATURESET.fields_by_name['field_presence'].enum_type = _FEATURESET_FIELDPRESENCE + _FEATURESET.fields_by_name['enum_type'].enum_type = _FEATURESET_ENUMTYPE + _FEATURESET.fields_by_name['repeated_field_encoding'].enum_type = _FEATURESET_REPEATEDFIELDENCODING + _FEATURESET.fields_by_name['utf8_validation'].enum_type = _FEATURESET_UTF8VALIDATION + _FEATURESET.fields_by_name['message_encoding'].enum_type = _FEATURESET_MESSAGEENCODING + _FEATURESET.fields_by_name['json_format'].enum_type = _FEATURESET_JSONFORMAT + _FEATURESET.fields_by_name['enforce_naming_style'].enum_type = _FEATURESET_ENFORCENAMINGSTYLE + _FEATURESET.fields_by_name['default_symbol_visibility'].enum_type = _FEATURESET_VISIBILITYFEATURE_DEFAULTSYMBOLVISIBILITY + _FEATURESET_FIELDPRESENCE.containing_type = _FEATURESET + _FEATURESET_ENUMTYPE.containing_type = _FEATURESET + _FEATURESET_REPEATEDFIELDENCODING.containing_type = _FEATURESET + _FEATURESET_UTF8VALIDATION.containing_type = _FEATURESET + _FEATURESET_MESSAGEENCODING.containing_type = _FEATURESET + _FEATURESET_JSONFORMAT.containing_type = _FEATURESET + _FEATURESET_ENFORCENAMINGSTYLE.containing_type = _FEATURESET + _FEATURESETDEFAULTS_FEATURESETEDITIONDEFAULT.fields_by_name['edition'].enum_type = _EDITION + _FEATURESETDEFAULTS_FEATURESETEDITIONDEFAULT.fields_by_name['overridable_features'].message_type = _FEATURESET + _FEATURESETDEFAULTS_FEATURESETEDITIONDEFAULT.fields_by_name['fixed_features'].message_type = _FEATURESET + _FEATURESETDEFAULTS_FEATURESETEDITIONDEFAULT.containing_type = _FEATURESETDEFAULTS + _FEATURESETDEFAULTS.fields_by_name['defaults'].message_type = _FEATURESETDEFAULTS_FEATURESETEDITIONDEFAULT + _FEATURESETDEFAULTS.fields_by_name['minimum_edition'].enum_type = _EDITION + _FEATURESETDEFAULTS.fields_by_name['maximum_edition'].enum_type = _EDITION + _SOURCECODEINFO_LOCATION.containing_type = _SOURCECODEINFO + _SOURCECODEINFO.fields_by_name['location'].message_type = _SOURCECODEINFO_LOCATION + _GENERATEDCODEINFO_ANNOTATION.fields_by_name['semantic'].enum_type = _GENERATEDCODEINFO_ANNOTATION_SEMANTIC + _GENERATEDCODEINFO_ANNOTATION.containing_type = _GENERATEDCODEINFO + _GENERATEDCODEINFO_ANNOTATION_SEMANTIC.containing_type = _GENERATEDCODEINFO_ANNOTATION + _GENERATEDCODEINFO.fields_by_name['annotation'].message_type = _GENERATEDCODEINFO_ANNOTATION + DESCRIPTOR.message_types_by_name['FileDescriptorSet'] = _FILEDESCRIPTORSET + DESCRIPTOR.message_types_by_name['FileDescriptorProto'] = _FILEDESCRIPTORPROTO + DESCRIPTOR.message_types_by_name['DescriptorProto'] = _DESCRIPTORPROTO + DESCRIPTOR.message_types_by_name['ExtensionRangeOptions'] = _EXTENSIONRANGEOPTIONS + DESCRIPTOR.message_types_by_name['FieldDescriptorProto'] = _FIELDDESCRIPTORPROTO + DESCRIPTOR.message_types_by_name['OneofDescriptorProto'] = _ONEOFDESCRIPTORPROTO + DESCRIPTOR.message_types_by_name['EnumDescriptorProto'] = _ENUMDESCRIPTORPROTO + DESCRIPTOR.message_types_by_name['EnumValueDescriptorProto'] = _ENUMVALUEDESCRIPTORPROTO + DESCRIPTOR.message_types_by_name['ServiceDescriptorProto'] = _SERVICEDESCRIPTORPROTO + DESCRIPTOR.message_types_by_name['MethodDescriptorProto'] = _METHODDESCRIPTORPROTO + DESCRIPTOR.message_types_by_name['FileOptions'] = _FILEOPTIONS + DESCRIPTOR.message_types_by_name['MessageOptions'] = _MESSAGEOPTIONS + DESCRIPTOR.message_types_by_name['FieldOptions'] = _FIELDOPTIONS + DESCRIPTOR.message_types_by_name['OneofOptions'] = _ONEOFOPTIONS + DESCRIPTOR.message_types_by_name['EnumOptions'] = _ENUMOPTIONS + DESCRIPTOR.message_types_by_name['EnumValueOptions'] = _ENUMVALUEOPTIONS + DESCRIPTOR.message_types_by_name['ServiceOptions'] = _SERVICEOPTIONS + DESCRIPTOR.message_types_by_name['MethodOptions'] = _METHODOPTIONS + DESCRIPTOR.message_types_by_name['UninterpretedOption'] = _UNINTERPRETEDOPTION + DESCRIPTOR.message_types_by_name['FeatureSet'] = _FEATURESET + DESCRIPTOR.message_types_by_name['FeatureSetDefaults'] = _FEATURESETDEFAULTS + DESCRIPTOR.message_types_by_name['SourceCodeInfo'] = _SOURCECODEINFO + DESCRIPTOR.message_types_by_name['GeneratedCodeInfo'] = _GENERATEDCODEINFO + DESCRIPTOR.enum_types_by_name['Edition'] = _EDITION + DESCRIPTOR.enum_types_by_name['SymbolVisibility'] = _SYMBOLVISIBILITY + _sym_db.RegisterFileDescriptor(DESCRIPTOR) + + class _ResolvedFeatures: + def __init__(self, features = None, **kwargs): + if features: + for k, v in features.FIELDS.items(): + setattr(self, k, getattr(features, k)) + else: + for k, v in kwargs.items(): + setattr(self, k, v) + DESCRIPTOR._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEDESCRIPTORSET._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEDESCRIPTORSET.fields[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEDESCRIPTORPROTO._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEDESCRIPTORPROTO.fields[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEDESCRIPTORPROTO.fields[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEDESCRIPTORPROTO.fields[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEDESCRIPTORPROTO.fields[3]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEDESCRIPTORPROTO.fields[4]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEDESCRIPTORPROTO.fields[5]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEDESCRIPTORPROTO.fields[6]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEDESCRIPTORPROTO.fields[7]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEDESCRIPTORPROTO.fields[8]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEDESCRIPTORPROTO.fields[9]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEDESCRIPTORPROTO.fields[10]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEDESCRIPTORPROTO.fields[11]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEDESCRIPTORPROTO.fields[12]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEDESCRIPTORPROTO.fields[13]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _DESCRIPTORPROTO._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _DESCRIPTORPROTO.fields[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _DESCRIPTORPROTO.fields[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _DESCRIPTORPROTO.fields[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _DESCRIPTORPROTO.fields[3]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _DESCRIPTORPROTO.fields[4]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _DESCRIPTORPROTO.fields[5]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _DESCRIPTORPROTO.fields[6]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _DESCRIPTORPROTO.fields[7]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _DESCRIPTORPROTO.fields[8]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _DESCRIPTORPROTO.fields[9]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _DESCRIPTORPROTO.fields[10]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _DESCRIPTORPROTO_EXTENSIONRANGE._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _DESCRIPTORPROTO_EXTENSIONRANGE.fields[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _DESCRIPTORPROTO_EXTENSIONRANGE.fields[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _DESCRIPTORPROTO_EXTENSIONRANGE.fields[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _DESCRIPTORPROTO_RESERVEDRANGE._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _DESCRIPTORPROTO_RESERVEDRANGE.fields[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _DESCRIPTORPROTO_RESERVEDRANGE.fields[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _EXTENSIONRANGEOPTIONS._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _EXTENSIONRANGEOPTIONS.fields[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _EXTENSIONRANGEOPTIONS.fields[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _EXTENSIONRANGEOPTIONS.fields[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _EXTENSIONRANGEOPTIONS.fields[3]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _EXTENSIONRANGEOPTIONS_DECLARATION._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _EXTENSIONRANGEOPTIONS_DECLARATION.fields[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _EXTENSIONRANGEOPTIONS_DECLARATION.fields[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _EXTENSIONRANGEOPTIONS_DECLARATION.fields[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _EXTENSIONRANGEOPTIONS_DECLARATION.fields[3]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _EXTENSIONRANGEOPTIONS_DECLARATION.fields[4]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDDESCRIPTORPROTO._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDDESCRIPTORPROTO.fields[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDDESCRIPTORPROTO.fields[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDDESCRIPTORPROTO.fields[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDDESCRIPTORPROTO.fields[3]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDDESCRIPTORPROTO.fields[4]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDDESCRIPTORPROTO.fields[5]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDDESCRIPTORPROTO.fields[6]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDDESCRIPTORPROTO.fields[7]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDDESCRIPTORPROTO.fields[8]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDDESCRIPTORPROTO.fields[9]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDDESCRIPTORPROTO.fields[10]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _ONEOFDESCRIPTORPROTO._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _ONEOFDESCRIPTORPROTO.fields[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _ONEOFDESCRIPTORPROTO.fields[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _ENUMDESCRIPTORPROTO._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _ENUMDESCRIPTORPROTO.fields[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _ENUMDESCRIPTORPROTO.fields[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _ENUMDESCRIPTORPROTO.fields[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _ENUMDESCRIPTORPROTO.fields[3]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _ENUMDESCRIPTORPROTO.fields[4]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _ENUMDESCRIPTORPROTO.fields[5]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _ENUMDESCRIPTORPROTO_ENUMRESERVEDRANGE._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _ENUMDESCRIPTORPROTO_ENUMRESERVEDRANGE.fields[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _ENUMDESCRIPTORPROTO_ENUMRESERVEDRANGE.fields[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _ENUMVALUEDESCRIPTORPROTO._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _ENUMVALUEDESCRIPTORPROTO.fields[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _ENUMVALUEDESCRIPTORPROTO.fields[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _ENUMVALUEDESCRIPTORPROTO.fields[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _SERVICEDESCRIPTORPROTO._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _SERVICEDESCRIPTORPROTO.fields[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _SERVICEDESCRIPTORPROTO.fields[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _SERVICEDESCRIPTORPROTO.fields[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _METHODDESCRIPTORPROTO._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _METHODDESCRIPTORPROTO.fields[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _METHODDESCRIPTORPROTO.fields[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _METHODDESCRIPTORPROTO.fields[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _METHODDESCRIPTORPROTO.fields[3]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _METHODDESCRIPTORPROTO.fields[4]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _METHODDESCRIPTORPROTO.fields[5]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEOPTIONS._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEOPTIONS.fields[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEOPTIONS.fields[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEOPTIONS.fields[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEOPTIONS.fields[3]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEOPTIONS.fields[4]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEOPTIONS.fields[5]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEOPTIONS.fields[6]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEOPTIONS.fields[7]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEOPTIONS.fields[8]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEOPTIONS.fields[9]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEOPTIONS.fields[10]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEOPTIONS.fields[11]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEOPTIONS.fields[12]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEOPTIONS.fields[13]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEOPTIONS.fields[14]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEOPTIONS.fields[15]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEOPTIONS.fields[16]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEOPTIONS.fields[17]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEOPTIONS.fields[18]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEOPTIONS.fields[19]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEOPTIONS.fields[20]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _MESSAGEOPTIONS._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _MESSAGEOPTIONS.fields[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _MESSAGEOPTIONS.fields[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _MESSAGEOPTIONS.fields[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _MESSAGEOPTIONS.fields[3]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _MESSAGEOPTIONS.fields[4]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _MESSAGEOPTIONS.fields[5]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _MESSAGEOPTIONS.fields[6]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS.fields[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS.fields[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS.fields[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS.fields[3]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS.fields[4]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS.fields[5]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS.fields[6]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS.fields[7]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS.fields[8]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS.fields[9]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS.fields[10]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS.fields[11]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS.fields[12]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS.fields[13]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS_EDITIONDEFAULT._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS_EDITIONDEFAULT.fields[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS_EDITIONDEFAULT.fields[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS_FEATURESUPPORT._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS_FEATURESUPPORT.fields[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS_FEATURESUPPORT.fields[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS_FEATURESUPPORT.fields[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS_FEATURESUPPORT.fields[3]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _ONEOFOPTIONS._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _ONEOFOPTIONS.fields[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _ONEOFOPTIONS.fields[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _ENUMOPTIONS._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _ENUMOPTIONS.fields[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _ENUMOPTIONS.fields[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _ENUMOPTIONS.fields[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _ENUMOPTIONS.fields[3]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _ENUMOPTIONS.fields[4]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _ENUMVALUEOPTIONS._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _ENUMVALUEOPTIONS.fields[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _ENUMVALUEOPTIONS.fields[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _ENUMVALUEOPTIONS.fields[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _ENUMVALUEOPTIONS.fields[3]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _ENUMVALUEOPTIONS.fields[4]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _SERVICEOPTIONS._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _SERVICEOPTIONS.fields[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _SERVICEOPTIONS.fields[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _SERVICEOPTIONS.fields[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _METHODOPTIONS._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _METHODOPTIONS.fields[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _METHODOPTIONS.fields[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _METHODOPTIONS.fields[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _METHODOPTIONS.fields[3]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _UNINTERPRETEDOPTION._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _UNINTERPRETEDOPTION.fields[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _UNINTERPRETEDOPTION.fields[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _UNINTERPRETEDOPTION.fields[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _UNINTERPRETEDOPTION.fields[3]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _UNINTERPRETEDOPTION.fields[4]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _UNINTERPRETEDOPTION.fields[5]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _UNINTERPRETEDOPTION.fields[6]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _UNINTERPRETEDOPTION_NAMEPART._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _UNINTERPRETEDOPTION_NAMEPART.fields[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["LEGACY_REQUIRED"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _UNINTERPRETEDOPTION_NAMEPART.fields[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["LEGACY_REQUIRED"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET.fields[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET.fields[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET.fields[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET.fields[3]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET.fields[4]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET.fields[5]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET.fields[6]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET.fields[7]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET_VISIBILITYFEATURE._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESETDEFAULTS._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESETDEFAULTS.fields[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESETDEFAULTS.fields[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESETDEFAULTS.fields[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESETDEFAULTS_FEATURESETEDITIONDEFAULT._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESETDEFAULTS_FEATURESETEDITIONDEFAULT.fields[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESETDEFAULTS_FEATURESETEDITIONDEFAULT.fields[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESETDEFAULTS_FEATURESETEDITIONDEFAULT.fields[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _SOURCECODEINFO._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _SOURCECODEINFO.fields[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _SOURCECODEINFO_LOCATION._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _SOURCECODEINFO_LOCATION.fields[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["PACKED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _SOURCECODEINFO_LOCATION.fields[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["PACKED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _SOURCECODEINFO_LOCATION.fields[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _SOURCECODEINFO_LOCATION.fields[3]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _SOURCECODEINFO_LOCATION.fields[4]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _GENERATEDCODEINFO._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _GENERATEDCODEINFO.fields[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _GENERATEDCODEINFO_ANNOTATION._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _GENERATEDCODEINFO_ANNOTATION.fields[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["PACKED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _GENERATEDCODEINFO_ANNOTATION.fields[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _GENERATEDCODEINFO_ANNOTATION.fields[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _GENERATEDCODEINFO_ANNOTATION.fields[3]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _GENERATEDCODEINFO_ANNOTATION.fields[4]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _EXTENSIONRANGEOPTIONS_VERIFICATIONSTATE._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _EXTENSIONRANGEOPTIONS_VERIFICATIONSTATE.values[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _EXTENSIONRANGEOPTIONS_VERIFICATIONSTATE.values[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDDESCRIPTORPROTO_TYPE._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDDESCRIPTORPROTO_TYPE.values[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDDESCRIPTORPROTO_TYPE.values[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDDESCRIPTORPROTO_TYPE.values[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDDESCRIPTORPROTO_TYPE.values[3]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDDESCRIPTORPROTO_TYPE.values[4]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDDESCRIPTORPROTO_TYPE.values[5]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDDESCRIPTORPROTO_TYPE.values[6]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDDESCRIPTORPROTO_TYPE.values[7]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDDESCRIPTORPROTO_TYPE.values[8]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDDESCRIPTORPROTO_TYPE.values[9]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDDESCRIPTORPROTO_TYPE.values[10]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDDESCRIPTORPROTO_TYPE.values[11]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDDESCRIPTORPROTO_TYPE.values[12]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDDESCRIPTORPROTO_TYPE.values[13]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDDESCRIPTORPROTO_TYPE.values[14]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDDESCRIPTORPROTO_TYPE.values[15]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDDESCRIPTORPROTO_TYPE.values[16]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDDESCRIPTORPROTO_TYPE.values[17]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDDESCRIPTORPROTO_LABEL._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDDESCRIPTORPROTO_LABEL.values[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDDESCRIPTORPROTO_LABEL.values[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDDESCRIPTORPROTO_LABEL.values[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEOPTIONS_OPTIMIZEMODE._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEOPTIONS_OPTIMIZEMODE.values[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEOPTIONS_OPTIMIZEMODE.values[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FILEOPTIONS_OPTIMIZEMODE.values[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS_CTYPE._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS_CTYPE.values[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS_CTYPE.values[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS_CTYPE.values[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS_JSTYPE._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS_JSTYPE.values[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS_JSTYPE.values[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS_JSTYPE.values[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS_OPTIONRETENTION._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS_OPTIONRETENTION.values[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS_OPTIONRETENTION.values[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS_OPTIONRETENTION.values[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS_OPTIONTARGETTYPE._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS_OPTIONTARGETTYPE.values[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS_OPTIONTARGETTYPE.values[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS_OPTIONTARGETTYPE.values[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS_OPTIONTARGETTYPE.values[3]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS_OPTIONTARGETTYPE.values[4]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS_OPTIONTARGETTYPE.values[5]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS_OPTIONTARGETTYPE.values[6]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS_OPTIONTARGETTYPE.values[7]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS_OPTIONTARGETTYPE.values[8]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FIELDOPTIONS_OPTIONTARGETTYPE.values[9]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _METHODOPTIONS_IDEMPOTENCYLEVEL._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _METHODOPTIONS_IDEMPOTENCYLEVEL.values[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _METHODOPTIONS_IDEMPOTENCYLEVEL.values[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _METHODOPTIONS_IDEMPOTENCYLEVEL.values[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET_FIELDPRESENCE._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET_FIELDPRESENCE.values[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET_FIELDPRESENCE.values[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET_FIELDPRESENCE.values[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET_FIELDPRESENCE.values[3]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET_ENUMTYPE._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET_ENUMTYPE.values[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET_ENUMTYPE.values[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET_ENUMTYPE.values[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET_REPEATEDFIELDENCODING._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET_REPEATEDFIELDENCODING.values[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET_REPEATEDFIELDENCODING.values[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET_REPEATEDFIELDENCODING.values[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET_UTF8VALIDATION._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET_UTF8VALIDATION.values[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET_UTF8VALIDATION.values[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET_UTF8VALIDATION.values[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET_MESSAGEENCODING._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET_MESSAGEENCODING.values[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET_MESSAGEENCODING.values[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET_MESSAGEENCODING.values[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET_JSONFORMAT._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET_JSONFORMAT.values[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET_JSONFORMAT.values[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET_JSONFORMAT.values[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET_ENFORCENAMINGSTYLE._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET_ENFORCENAMINGSTYLE.values[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET_ENFORCENAMINGSTYLE.values[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET_ENFORCENAMINGSTYLE.values[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET_VISIBILITYFEATURE_DEFAULTSYMBOLVISIBILITY._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET_VISIBILITYFEATURE_DEFAULTSYMBOLVISIBILITY.values[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET_VISIBILITYFEATURE_DEFAULTSYMBOLVISIBILITY.values[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET_VISIBILITYFEATURE_DEFAULTSYMBOLVISIBILITY.values[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET_VISIBILITYFEATURE_DEFAULTSYMBOLVISIBILITY.values[3]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _FEATURESET_VISIBILITYFEATURE_DEFAULTSYMBOLVISIBILITY.values[4]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _GENERATEDCODEINFO_ANNOTATION_SEMANTIC._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _GENERATEDCODEINFO_ANNOTATION_SEMANTIC.values[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _GENERATEDCODEINFO_ANNOTATION_SEMANTIC.values[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _GENERATEDCODEINFO_ANNOTATION_SEMANTIC.values[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _EDITION._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _EDITION.values[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _EDITION.values[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _EDITION.values[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _EDITION.values[3]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _EDITION.values[4]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _EDITION.values[5]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _EDITION.values[6]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _EDITION.values[7]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _EDITION.values[8]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _EDITION.values[9]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _EDITION.values[10]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _EDITION.values[11]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _EDITION.values[12]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _SYMBOLVISIBILITY._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _SYMBOLVISIBILITY.values[0]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _SYMBOLVISIBILITY.values[1]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) + _SYMBOLVISIBILITY.values[2]._features = _ResolvedFeatures(field_presence=_FEATURESET_FIELDPRESENCE.values_by_name["EXPLICIT"].number,enum_type=_FEATURESET_ENUMTYPE.values_by_name["CLOSED"].number,repeated_field_encoding=_FEATURESET_REPEATEDFIELDENCODING.values_by_name["EXPANDED"].number,utf8_validation=_FEATURESET_UTF8VALIDATION.values_by_name["NONE"].number,message_encoding=_FEATURESET_MESSAGEENCODING.values_by_name["LENGTH_PREFIXED"].number,json_format=_FEATURESET_JSONFORMAT.values_by_name["LEGACY_BEST_EFFORT"].number) +else: + _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.descriptor_pb2', _globals) +if not _descriptor._USE_C_DESCRIPTORS: + _globals['DESCRIPTOR']._loaded_options = None + _globals['DESCRIPTOR']._serialized_options = b'\n\023com.google.protobufB\020DescriptorProtosH\001Z-google.golang.org/protobuf/types/descriptorpb\370\001\001\242\002\003GPB\252\002\032Google.Protobuf.Reflection' + _globals['_EXTENSIONRANGEOPTIONS'].fields_by_name['declaration']._loaded_options = None + _globals['_EXTENSIONRANGEOPTIONS'].fields_by_name['declaration']._serialized_options = b'\210\001\002' + _globals['_EXTENSIONRANGEOPTIONS'].fields_by_name['verification']._loaded_options = None + _globals['_EXTENSIONRANGEOPTIONS'].fields_by_name['verification']._serialized_options = b'\210\001\002' + _globals['_FILEOPTIONS'].fields_by_name['java_generate_equals_and_hash']._loaded_options = None + _globals['_FILEOPTIONS'].fields_by_name['java_generate_equals_and_hash']._serialized_options = b'\030\001' + _globals['_MESSAGEOPTIONS'].fields_by_name['deprecated_legacy_json_field_conflicts']._loaded_options = None + _globals['_MESSAGEOPTIONS'].fields_by_name['deprecated_legacy_json_field_conflicts']._serialized_options = b'\030\001' + _globals['_FIELDOPTIONS'].fields_by_name['weak']._loaded_options = None + _globals['_FIELDOPTIONS'].fields_by_name['weak']._serialized_options = b'\030\001' + _globals['_ENUMOPTIONS'].fields_by_name['deprecated_legacy_json_field_conflicts']._loaded_options = None + _globals['_ENUMOPTIONS'].fields_by_name['deprecated_legacy_json_field_conflicts']._serialized_options = b'\030\001' + _globals['_FEATURESET'].fields_by_name['field_presence']._loaded_options = None + _globals['_FEATURESET'].fields_by_name['field_presence']._serialized_options = b'\210\001\001\230\001\004\230\001\001\242\001\r\022\010EXPLICIT\030\204\007\242\001\r\022\010IMPLICIT\030\347\007\242\001\r\022\010EXPLICIT\030\350\007\262\001\003\010\350\007' + _globals['_FEATURESET'].fields_by_name['enum_type']._loaded_options = None + _globals['_FEATURESET'].fields_by_name['enum_type']._serialized_options = b'\210\001\001\230\001\006\230\001\001\242\001\013\022\006CLOSED\030\204\007\242\001\t\022\004OPEN\030\347\007\262\001\003\010\350\007' + _globals['_FEATURESET'].fields_by_name['repeated_field_encoding']._loaded_options = None + _globals['_FEATURESET'].fields_by_name['repeated_field_encoding']._serialized_options = b'\210\001\001\230\001\004\230\001\001\242\001\r\022\010EXPANDED\030\204\007\242\001\013\022\006PACKED\030\347\007\262\001\003\010\350\007' + _globals['_FEATURESET'].fields_by_name['utf8_validation']._loaded_options = None + _globals['_FEATURESET'].fields_by_name['utf8_validation']._serialized_options = b'\210\001\001\230\001\004\230\001\001\242\001\t\022\004NONE\030\204\007\242\001\013\022\006VERIFY\030\347\007\262\001\003\010\350\007' + _globals['_FEATURESET'].fields_by_name['message_encoding']._loaded_options = None + _globals['_FEATURESET'].fields_by_name['message_encoding']._serialized_options = b'\210\001\001\230\001\004\230\001\001\242\001\024\022\017LENGTH_PREFIXED\030\204\007\262\001\003\010\350\007' + _globals['_FEATURESET'].fields_by_name['json_format']._loaded_options = None + _globals['_FEATURESET'].fields_by_name['json_format']._serialized_options = b'\210\001\001\230\001\003\230\001\006\230\001\001\242\001\027\022\022LEGACY_BEST_EFFORT\030\204\007\242\001\n\022\005ALLOW\030\347\007\262\001\003\010\350\007' + _globals['_FEATURESET'].fields_by_name['enforce_naming_style']._loaded_options = None + _globals['_FEATURESET'].fields_by_name['enforce_naming_style']._serialized_options = b'\210\001\002\230\001\001\230\001\002\230\001\003\230\001\004\230\001\005\230\001\006\230\001\007\230\001\010\230\001\t\242\001\021\022\014STYLE_LEGACY\030\204\007\242\001\016\022\tSTYLE2024\030\351\007\262\001\003\010\351\007' + _globals['_FEATURESET'].fields_by_name['default_symbol_visibility']._loaded_options = None + _globals['_FEATURESET'].fields_by_name['default_symbol_visibility']._serialized_options = b'\210\001\002\230\001\001\242\001\017\022\nEXPORT_ALL\030\204\007\242\001\025\022\020EXPORT_TOP_LEVEL\030\351\007\262\001\003\010\351\007' + _globals['_SOURCECODEINFO_LOCATION'].fields_by_name['path']._loaded_options = None + _globals['_SOURCECODEINFO_LOCATION'].fields_by_name['path']._serialized_options = b'\020\001' + _globals['_SOURCECODEINFO_LOCATION'].fields_by_name['span']._loaded_options = None + _globals['_SOURCECODEINFO_LOCATION'].fields_by_name['span']._serialized_options = b'\020\001' + _globals['_GENERATEDCODEINFO_ANNOTATION'].fields_by_name['path']._loaded_options = None + _globals['_GENERATEDCODEINFO_ANNOTATION'].fields_by_name['path']._serialized_options = b'\020\001' + _globals['_EDITION']._serialized_start=12685 + _globals['_EDITION']._serialized_end=13003 + _globals['_SYMBOLVISIBILITY']._serialized_start=13005 + _globals['_SYMBOLVISIBILITY']._serialized_end=13090 + _globals['_FILEDESCRIPTORSET']._serialized_start=53 + _globals['_FILEDESCRIPTORSET']._serialized_end=144 + _globals['_FILEDESCRIPTORPROTO']._serialized_start=147 + _globals['_FILEDESCRIPTORPROTO']._serialized_end=856 + _globals['_DESCRIPTORPROTO']._serialized_start=859 + _globals['_DESCRIPTORPROTO']._serialized_end=1751 + _globals['_DESCRIPTORPROTO_EXTENSIONRANGE']._serialized_start=1572 + _globals['_DESCRIPTORPROTO_EXTENSIONRANGE']._serialized_end=1694 + _globals['_DESCRIPTORPROTO_RESERVEDRANGE']._serialized_start=1696 + _globals['_DESCRIPTORPROTO_RESERVEDRANGE']._serialized_end=1751 + _globals['_EXTENSIONRANGEOPTIONS']._serialized_start=1754 + _globals['_EXTENSIONRANGEOPTIONS']._serialized_end=2342 + _globals['_EXTENSIONRANGEOPTIONS_DECLARATION']._serialized_start=2129 + _globals['_EXTENSIONRANGEOPTIONS_DECLARATION']._serialized_end=2277 + _globals['_EXTENSIONRANGEOPTIONS_VERIFICATIONSTATE']._serialized_start=2279 + _globals['_EXTENSIONRANGEOPTIONS_VERIFICATIONSTATE']._serialized_end=2331 + _globals['_FIELDDESCRIPTORPROTO']._serialized_start=2345 + _globals['_FIELDDESCRIPTORPROTO']._serialized_end=3178 + _globals['_FIELDDESCRIPTORPROTO_TYPE']._serialized_start=2799 + _globals['_FIELDDESCRIPTORPROTO_TYPE']._serialized_end=3109 + _globals['_FIELDDESCRIPTORPROTO_LABEL']._serialized_start=3111 + _globals['_FIELDDESCRIPTORPROTO_LABEL']._serialized_end=3178 + _globals['_ONEOFDESCRIPTORPROTO']._serialized_start=3180 + _globals['_ONEOFDESCRIPTORPROTO']._serialized_end=3279 + _globals['_ENUMDESCRIPTORPROTO']._serialized_start=3282 + _globals['_ENUMDESCRIPTORPROTO']._serialized_end=3704 + _globals['_ENUMDESCRIPTORPROTO_ENUMRESERVEDRANGE']._serialized_start=3645 + _globals['_ENUMDESCRIPTORPROTO_ENUMRESERVEDRANGE']._serialized_end=3704 + _globals['_ENUMVALUEDESCRIPTORPROTO']._serialized_start=3707 + _globals['_ENUMVALUEDESCRIPTORPROTO']._serialized_end=3838 + _globals['_SERVICEDESCRIPTORPROTO']._serialized_start=3841 + _globals['_SERVICEDESCRIPTORPROTO']._serialized_end=4022 + _globals['_METHODDESCRIPTORPROTO']._serialized_start=4025 + _globals['_METHODDESCRIPTORPROTO']._serialized_end=4290 + _globals['_FILEOPTIONS']._serialized_start=4293 + _globals['_FILEOPTIONS']._serialized_end=5490 + _globals['_FILEOPTIONS_OPTIMIZEMODE']._serialized_start=5387 + _globals['_FILEOPTIONS_OPTIMIZEMODE']._serialized_end=5445 + _globals['_MESSAGEOPTIONS']._serialized_start=5493 + _globals['_MESSAGEOPTIONS']._serialized_end=5993 + _globals['_FIELDOPTIONS']._serialized_start=5996 + _globals['_FIELDOPTIONS']._serialized_end=7693 + _globals['_FIELDOPTIONS_EDITIONDEFAULT']._serialized_start=6837 + _globals['_FIELDOPTIONS_EDITIONDEFAULT']._serialized_end=6927 + _globals['_FIELDOPTIONS_FEATURESUPPORT']._serialized_start=6930 + _globals['_FIELDOPTIONS_FEATURESUPPORT']._serialized_end=7208 + _globals['_FIELDOPTIONS_CTYPE']._serialized_start=7210 + _globals['_FIELDOPTIONS_CTYPE']._serialized_end=7257 + _globals['_FIELDOPTIONS_JSTYPE']._serialized_start=7259 + _globals['_FIELDOPTIONS_JSTYPE']._serialized_end=7312 + _globals['_FIELDOPTIONS_OPTIONRETENTION']._serialized_start=7314 + _globals['_FIELDOPTIONS_OPTIONRETENTION']._serialized_end=7399 + _globals['_FIELDOPTIONS_OPTIONTARGETTYPE']._serialized_start=7402 + _globals['_FIELDOPTIONS_OPTIONTARGETTYPE']._serialized_end=7670 + _globals['_ONEOFOPTIONS']._serialized_start=7696 + _globals['_ONEOFOPTIONS']._serialized_end=7868 + _globals['_ENUMOPTIONS']._serialized_start=7871 + _globals['_ENUMOPTIONS']._serialized_end=8208 + _globals['_ENUMVALUEOPTIONS']._serialized_start=8211 + _globals['_ENUMVALUEOPTIONS']._serialized_end=8555 + _globals['_SERVICEOPTIONS']._serialized_start=8558 + _globals['_SERVICEOPTIONS']._serialized_end=8771 + _globals['_METHODOPTIONS']._serialized_start=8774 + _globals['_METHODOPTIONS']._serialized_end=9183 + _globals['_METHODOPTIONS_IDEMPOTENCYLEVEL']._serialized_start=9092 + _globals['_METHODOPTIONS_IDEMPOTENCYLEVEL']._serialized_end=9172 + _globals['_UNINTERPRETEDOPTION']._serialized_start=9186 + _globals['_UNINTERPRETEDOPTION']._serialized_end=9596 + _globals['_UNINTERPRETEDOPTION_NAMEPART']._serialized_start=9522 + _globals['_UNINTERPRETEDOPTION_NAMEPART']._serialized_end=9596 + _globals['_FEATURESET']._serialized_start=9599 + _globals['_FEATURESET']._serialized_end=11533 + _globals['_FEATURESET_VISIBILITYFEATURE']._serialized_start=10778 + _globals['_FEATURESET_VISIBILITYFEATURE']._serialized_end=10939 + _globals['_FEATURESET_VISIBILITYFEATURE_DEFAULTSYMBOLVISIBILITY']._serialized_start=10800 + _globals['_FEATURESET_VISIBILITYFEATURE_DEFAULTSYMBOLVISIBILITY']._serialized_end=10929 + _globals['_FEATURESET_FIELDPRESENCE']._serialized_start=10941 + _globals['_FEATURESET_FIELDPRESENCE']._serialized_end=11033 + _globals['_FEATURESET_ENUMTYPE']._serialized_start=11035 + _globals['_FEATURESET_ENUMTYPE']._serialized_end=11090 + _globals['_FEATURESET_REPEATEDFIELDENCODING']._serialized_start=11092 + _globals['_FEATURESET_REPEATEDFIELDENCODING']._serialized_end=11178 + _globals['_FEATURESET_UTF8VALIDATION']._serialized_start=11180 + _globals['_FEATURESET_UTF8VALIDATION']._serialized_end=11253 + _globals['_FEATURESET_MESSAGEENCODING']._serialized_start=11255 + _globals['_FEATURESET_MESSAGEENCODING']._serialized_end=11338 + _globals['_FEATURESET_JSONFORMAT']._serialized_start=11340 + _globals['_FEATURESET_JSONFORMAT']._serialized_end=11412 + _globals['_FEATURESET_ENFORCENAMINGSTYLE']._serialized_start=11414 + _globals['_FEATURESET_ENFORCENAMINGSTYLE']._serialized_end=11501 + _globals['_FEATURESETDEFAULTS']._serialized_start=11536 + _globals['_FEATURESETDEFAULTS']._serialized_end=12031 + _globals['_FEATURESETDEFAULTS_FEATURESETEDITIONDEFAULT']._serialized_start=11783 + _globals['_FEATURESETDEFAULTS_FEATURESETEDITIONDEFAULT']._serialized_end=12031 + _globals['_SOURCECODEINFO']._serialized_start=12034 + _globals['_SOURCECODEINFO']._serialized_end=12343 + _globals['_SOURCECODEINFO_LOCATION']._serialized_start=12123 + _globals['_SOURCECODEINFO_LOCATION']._serialized_end=12329 + _globals['_GENERATEDCODEINFO']._serialized_start=12346 + _globals['_GENERATEDCODEINFO']._serialized_end=12682 + _globals['_GENERATEDCODEINFO_ANNOTATION']._serialized_start=12447 + _globals['_GENERATEDCODEINFO_ANNOTATION']._serialized_end=12682 + _globals['_GENERATEDCODEINFO_ANNOTATION_SEMANTIC']._serialized_start=12642 + _globals['_GENERATEDCODEINFO_ANNOTATION_SEMANTIC']._serialized_end=12682 +# @@protoc_insertion_point(module_scope) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/descriptor_pool.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/descriptor_pool.py new file mode 100644 index 0000000000000000000000000000000000000000..a838c508b58b2f3e06fb7cbf80e24ec2e464e215 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/descriptor_pool.py @@ -0,0 +1,1373 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""Provides DescriptorPool to use as a container for proto2 descriptors. + +The DescriptorPool is used in conjection with a DescriptorDatabase to maintain +a collection of protocol buffer descriptors for use when dynamically creating +message types at runtime. + +For most applications protocol buffers should be used via modules generated by +the protocol buffer compiler tool. This should only be used when the type of +protocol buffers used in an application or library cannot be predetermined. + +Below is a straightforward example on how to use this class:: + + pool = DescriptorPool() + file_descriptor_protos = [ ... ] + for file_descriptor_proto in file_descriptor_protos: + pool.Add(file_descriptor_proto) + my_message_descriptor = pool.FindMessageTypeByName('some.package.MessageType') + +The message descriptor can be used in conjunction with the message_factory +module in order to create a protocol buffer class that can be encoded and +decoded. + +If you want to get a Python class for the specified proto, use the +helper functions inside google.protobuf.message_factory +directly instead of this class. +""" + +__author__ = 'matthewtoia@google.com (Matt Toia)' + +import collections +import threading +import warnings + +from google.protobuf import descriptor +from google.protobuf import descriptor_database +from google.protobuf import text_encoding +from google.protobuf.internal import python_edition_defaults +from google.protobuf.internal import python_message + +_USE_C_DESCRIPTORS = descriptor._USE_C_DESCRIPTORS # pylint: disable=protected-access + + +def _NormalizeFullyQualifiedName(name): + """Remove leading period from fully-qualified type name. + + Due to b/13860351 in descriptor_database.py, types in the root namespace are + generated with a leading period. This function removes that prefix. + + Args: + name (str): The fully-qualified symbol name. + + Returns: + str: The normalized fully-qualified symbol name. + """ + return name.lstrip('.') + + +def _OptionsOrNone(descriptor_proto): + """Returns the value of the field `options`, or None if it is not set.""" + if descriptor_proto.HasField('options'): + return descriptor_proto.options + else: + return None + + +def _IsMessageSetExtension(field): + return (field.is_extension and + field.containing_type.has_options and + field.containing_type.GetOptions().message_set_wire_format and + field.type == descriptor.FieldDescriptor.TYPE_MESSAGE and + not field.is_required and + not field.is_repeated) + +_edition_defaults_lock = threading.Lock() + + +class DescriptorPool(object): + """A collection of protobufs dynamically constructed by descriptor protos.""" + + if _USE_C_DESCRIPTORS: + + def __new__(cls, descriptor_db=None): + # pylint: disable=protected-access + return descriptor._message.DescriptorPool(descriptor_db) + + def __init__( + self, descriptor_db=None, use_deprecated_legacy_json_field_conflicts=False + ): + """Initializes a Pool of proto buffs. + + The descriptor_db argument to the constructor is provided to allow + specialized file descriptor proto lookup code to be triggered on demand. An + example would be an implementation which will read and compile a file + specified in a call to FindFileByName() and not require the call to Add() + at all. Results from this database will be cached internally here as well. + + Args: + descriptor_db: A secondary source of file descriptors. + use_deprecated_legacy_json_field_conflicts: Unused, for compatibility with + C++. + """ + + self._internal_db = descriptor_database.DescriptorDatabase() + self._descriptor_db = descriptor_db + self._descriptors = {} + self._enum_descriptors = {} + self._service_descriptors = {} + self._file_descriptors = {} + self._toplevel_extensions = {} + self._top_enum_values = {} + # We store extensions in two two-level mappings: The first key is the + # descriptor of the message being extended, the second key is the extension + # full name or its tag number. + self._extensions_by_name = collections.defaultdict(dict) + self._extensions_by_number = collections.defaultdict(dict) + self._serialized_edition_defaults = ( + python_edition_defaults._PROTOBUF_INTERNAL_PYTHON_EDITION_DEFAULTS + ) + self._edition_defaults = None + self._feature_cache = dict() + + def _CheckConflictRegister(self, desc, desc_name, file_name): + """Check if the descriptor name conflicts with another of the same name. + + Args: + desc: Descriptor of a message, enum, service, extension or enum value. + desc_name (str): the full name of desc. + file_name (str): The file name of descriptor. + """ + for register, descriptor_type in [ + (self._descriptors, descriptor.Descriptor), + (self._enum_descriptors, descriptor.EnumDescriptor), + (self._service_descriptors, descriptor.ServiceDescriptor), + (self._toplevel_extensions, descriptor.FieldDescriptor), + (self._top_enum_values, descriptor.EnumValueDescriptor)]: + if desc_name in register: + old_desc = register[desc_name] + if isinstance(old_desc, descriptor.EnumValueDescriptor): + old_file = old_desc.type.file.name + else: + old_file = old_desc.file.name + + if not isinstance(desc, descriptor_type) or ( + old_file != file_name): + error_msg = ('Conflict register for file "' + file_name + + '": ' + desc_name + + ' is already defined in file "' + + old_file + '". Please fix the conflict by adding ' + 'package name on the proto file, or use different ' + 'name for the duplication.') + if isinstance(desc, descriptor.EnumValueDescriptor): + error_msg += ('\nNote: enum values appear as ' + 'siblings of the enum type instead of ' + 'children of it.') + + raise TypeError(error_msg) + + return + + def Add(self, file_desc_proto): + """Adds the FileDescriptorProto and its types to this pool. + + Args: + file_desc_proto (FileDescriptorProto): The file descriptor to add. + """ + + self._internal_db.Add(file_desc_proto) + + def AddSerializedFile(self, serialized_file_desc_proto): + """Adds the FileDescriptorProto and its types to this pool. + + Args: + serialized_file_desc_proto (bytes): A bytes string, serialization of the + :class:`FileDescriptorProto` to add. + + Returns: + FileDescriptor: Descriptor for the added file. + """ + + # pylint: disable=g-import-not-at-top + from google.protobuf import descriptor_pb2 + file_desc_proto = descriptor_pb2.FileDescriptorProto.FromString( + serialized_file_desc_proto) + file_desc = self._ConvertFileProtoToFileDescriptor(file_desc_proto) + file_desc.serialized_pb = serialized_file_desc_proto + return file_desc + + # Never call this method. It is for internal usage only. + def _AddDescriptor(self, desc): + """Adds a Descriptor to the pool, non-recursively. + + If the Descriptor contains nested messages or enums, the caller must + explicitly register them. This method also registers the FileDescriptor + associated with the message. + + Args: + desc: A Descriptor. + """ + if not isinstance(desc, descriptor.Descriptor): + raise TypeError('Expected instance of descriptor.Descriptor.') + + self._CheckConflictRegister(desc, desc.full_name, desc.file.name) + + self._descriptors[desc.full_name] = desc + self._AddFileDescriptor(desc.file) + + # Never call this method. It is for internal usage only. + def _AddEnumDescriptor(self, enum_desc): + """Adds an EnumDescriptor to the pool. + + This method also registers the FileDescriptor associated with the enum. + + Args: + enum_desc: An EnumDescriptor. + """ + + if not isinstance(enum_desc, descriptor.EnumDescriptor): + raise TypeError('Expected instance of descriptor.EnumDescriptor.') + + file_name = enum_desc.file.name + self._CheckConflictRegister(enum_desc, enum_desc.full_name, file_name) + self._enum_descriptors[enum_desc.full_name] = enum_desc + + # Top enum values need to be indexed. + # Count the number of dots to see whether the enum is toplevel or nested + # in a message. We cannot use enum_desc.containing_type at this stage. + if enum_desc.file.package: + top_level = (enum_desc.full_name.count('.') + - enum_desc.file.package.count('.') == 1) + else: + top_level = enum_desc.full_name.count('.') == 0 + if top_level: + file_name = enum_desc.file.name + package = enum_desc.file.package + for enum_value in enum_desc.values: + full_name = _NormalizeFullyQualifiedName( + '.'.join((package, enum_value.name))) + self._CheckConflictRegister(enum_value, full_name, file_name) + self._top_enum_values[full_name] = enum_value + self._AddFileDescriptor(enum_desc.file) + + # Never call this method. It is for internal usage only. + def _AddServiceDescriptor(self, service_desc): + """Adds a ServiceDescriptor to the pool. + + Args: + service_desc: A ServiceDescriptor. + """ + + if not isinstance(service_desc, descriptor.ServiceDescriptor): + raise TypeError('Expected instance of descriptor.ServiceDescriptor.') + + self._CheckConflictRegister(service_desc, service_desc.full_name, + service_desc.file.name) + self._service_descriptors[service_desc.full_name] = service_desc + + # Never call this method. It is for internal usage only. + def _AddExtensionDescriptor(self, extension): + """Adds a FieldDescriptor describing an extension to the pool. + + Args: + extension: A FieldDescriptor. + + Raises: + AssertionError: when another extension with the same number extends the + same message. + TypeError: when the specified extension is not a + descriptor.FieldDescriptor. + """ + if not (isinstance(extension, descriptor.FieldDescriptor) and + extension.is_extension): + raise TypeError('Expected an extension descriptor.') + + if extension.extension_scope is None: + self._CheckConflictRegister( + extension, extension.full_name, extension.file.name) + self._toplevel_extensions[extension.full_name] = extension + + try: + existing_desc = self._extensions_by_number[ + extension.containing_type][extension.number] + except KeyError: + pass + else: + if extension is not existing_desc: + raise AssertionError( + 'Extensions "%s" and "%s" both try to extend message type "%s" ' + 'with field number %d.' % + (extension.full_name, existing_desc.full_name, + extension.containing_type.full_name, extension.number)) + + self._extensions_by_number[extension.containing_type][ + extension.number] = extension + self._extensions_by_name[extension.containing_type][ + extension.full_name] = extension + + # Also register MessageSet extensions with the type name. + if _IsMessageSetExtension(extension): + self._extensions_by_name[extension.containing_type][ + extension.message_type.full_name] = extension + + if hasattr(extension.containing_type, '_concrete_class'): + python_message._AttachFieldHelpers( + extension.containing_type._concrete_class, extension) + + # Never call this method. It is for internal usage only. + def _InternalAddFileDescriptor(self, file_desc): + """Adds a FileDescriptor to the pool, non-recursively. + + If the FileDescriptor contains messages or enums, the caller must explicitly + register them. + + Args: + file_desc: A FileDescriptor. + """ + + self._AddFileDescriptor(file_desc) + + def _AddFileDescriptor(self, file_desc): + """Adds a FileDescriptor to the pool, non-recursively. + + If the FileDescriptor contains messages or enums, the caller must explicitly + register them. + + Args: + file_desc: A FileDescriptor. + """ + + if not isinstance(file_desc, descriptor.FileDescriptor): + raise TypeError('Expected instance of descriptor.FileDescriptor.') + self._file_descriptors[file_desc.name] = file_desc + + def FindFileByName(self, file_name): + """Gets a FileDescriptor by file name. + + Args: + file_name (str): The path to the file to get a descriptor for. + + Returns: + FileDescriptor: The descriptor for the named file. + + Raises: + KeyError: if the file cannot be found in the pool. + """ + + try: + return self._file_descriptors[file_name] + except KeyError: + pass + + try: + file_proto = self._internal_db.FindFileByName(file_name) + except KeyError as error: + if self._descriptor_db: + file_proto = self._descriptor_db.FindFileByName(file_name) + else: + raise error + if not file_proto: + raise KeyError('Cannot find a file named %s' % file_name) + return self._ConvertFileProtoToFileDescriptor(file_proto) + + def FindFileContainingSymbol(self, symbol): + """Gets the FileDescriptor for the file containing the specified symbol. + + Args: + symbol (str): The name of the symbol to search for. + + Returns: + FileDescriptor: Descriptor for the file that contains the specified + symbol. + + Raises: + KeyError: if the file cannot be found in the pool. + """ + + symbol = _NormalizeFullyQualifiedName(symbol) + try: + return self._InternalFindFileContainingSymbol(symbol) + except KeyError: + pass + + try: + # Try fallback database. Build and find again if possible. + self._FindFileContainingSymbolInDb(symbol) + return self._InternalFindFileContainingSymbol(symbol) + except KeyError: + raise KeyError('Cannot find a file containing %s' % symbol) + + def _InternalFindFileContainingSymbol(self, symbol): + """Gets the already built FileDescriptor containing the specified symbol. + + Args: + symbol (str): The name of the symbol to search for. + + Returns: + FileDescriptor: Descriptor for the file that contains the specified + symbol. + + Raises: + KeyError: if the file cannot be found in the pool. + """ + try: + return self._descriptors[symbol].file + except KeyError: + pass + + try: + return self._enum_descriptors[symbol].file + except KeyError: + pass + + try: + return self._service_descriptors[symbol].file + except KeyError: + pass + + try: + return self._top_enum_values[symbol].type.file + except KeyError: + pass + + try: + return self._toplevel_extensions[symbol].file + except KeyError: + pass + + # Try fields, enum values and nested extensions inside a message. + top_name, _, sub_name = symbol.rpartition('.') + try: + message = self.FindMessageTypeByName(top_name) + assert (sub_name in message.extensions_by_name or + sub_name in message.fields_by_name or + sub_name in message.enum_values_by_name) + return message.file + except (KeyError, AssertionError): + raise KeyError('Cannot find a file containing %s' % symbol) + + def FindMessageTypeByName(self, full_name): + """Loads the named descriptor from the pool. + + Args: + full_name (str): The full name of the descriptor to load. + + Returns: + Descriptor: The descriptor for the named type. + + Raises: + KeyError: if the message cannot be found in the pool. + """ + + full_name = _NormalizeFullyQualifiedName(full_name) + if full_name not in self._descriptors: + self._FindFileContainingSymbolInDb(full_name) + return self._descriptors[full_name] + + def FindEnumTypeByName(self, full_name): + """Loads the named enum descriptor from the pool. + + Args: + full_name (str): The full name of the enum descriptor to load. + + Returns: + EnumDescriptor: The enum descriptor for the named type. + + Raises: + KeyError: if the enum cannot be found in the pool. + """ + + full_name = _NormalizeFullyQualifiedName(full_name) + if full_name not in self._enum_descriptors: + self._FindFileContainingSymbolInDb(full_name) + return self._enum_descriptors[full_name] + + def FindFieldByName(self, full_name): + """Loads the named field descriptor from the pool. + + Args: + full_name (str): The full name of the field descriptor to load. + + Returns: + FieldDescriptor: The field descriptor for the named field. + + Raises: + KeyError: if the field cannot be found in the pool. + """ + full_name = _NormalizeFullyQualifiedName(full_name) + message_name, _, field_name = full_name.rpartition('.') + message_descriptor = self.FindMessageTypeByName(message_name) + return message_descriptor.fields_by_name[field_name] + + def FindOneofByName(self, full_name): + """Loads the named oneof descriptor from the pool. + + Args: + full_name (str): The full name of the oneof descriptor to load. + + Returns: + OneofDescriptor: The oneof descriptor for the named oneof. + + Raises: + KeyError: if the oneof cannot be found in the pool. + """ + full_name = _NormalizeFullyQualifiedName(full_name) + message_name, _, oneof_name = full_name.rpartition('.') + message_descriptor = self.FindMessageTypeByName(message_name) + return message_descriptor.oneofs_by_name[oneof_name] + + def FindExtensionByName(self, full_name): + """Loads the named extension descriptor from the pool. + + Args: + full_name (str): The full name of the extension descriptor to load. + + Returns: + FieldDescriptor: The field descriptor for the named extension. + + Raises: + KeyError: if the extension cannot be found in the pool. + """ + full_name = _NormalizeFullyQualifiedName(full_name) + try: + # The proto compiler does not give any link between the FileDescriptor + # and top-level extensions unless the FileDescriptorProto is added to + # the DescriptorDatabase, but this can impact memory usage. + # So we registered these extensions by name explicitly. + return self._toplevel_extensions[full_name] + except KeyError: + pass + message_name, _, extension_name = full_name.rpartition('.') + try: + # Most extensions are nested inside a message. + scope = self.FindMessageTypeByName(message_name) + except KeyError: + # Some extensions are defined at file scope. + scope = self._FindFileContainingSymbolInDb(full_name) + return scope.extensions_by_name[extension_name] + + def FindExtensionByNumber(self, message_descriptor, number): + """Gets the extension of the specified message with the specified number. + + Extensions have to be registered to this pool by calling :func:`Add` or + :func:`AddExtensionDescriptor`. + + Args: + message_descriptor (Descriptor): descriptor of the extended message. + number (int): Number of the extension field. + + Returns: + FieldDescriptor: The descriptor for the extension. + + Raises: + KeyError: when no extension with the given number is known for the + specified message. + """ + try: + return self._extensions_by_number[message_descriptor][number] + except KeyError: + self._TryLoadExtensionFromDB(message_descriptor, number) + return self._extensions_by_number[message_descriptor][number] + + def FindAllExtensions(self, message_descriptor): + """Gets all the known extensions of a given message. + + Extensions have to be registered to this pool by build related + :func:`Add` or :func:`AddExtensionDescriptor`. + + Args: + message_descriptor (Descriptor): Descriptor of the extended message. + + Returns: + list[FieldDescriptor]: Field descriptors describing the extensions. + """ + # Fallback to descriptor db if FindAllExtensionNumbers is provided. + if self._descriptor_db and hasattr( + self._descriptor_db, 'FindAllExtensionNumbers'): + full_name = message_descriptor.full_name + try: + all_numbers = self._descriptor_db.FindAllExtensionNumbers(full_name) + except: + pass + else: + if isinstance(all_numbers, list): + for number in all_numbers: + if number in self._extensions_by_number[message_descriptor]: + continue + self._TryLoadExtensionFromDB(message_descriptor, number) + else: + warnings.warn( + 'FindAllExtensionNumbers() on fall back DB must return a list,' + ' not {0}'.format(type(all_numbers)) + ) + + return list(self._extensions_by_number[message_descriptor].values()) + + def _TryLoadExtensionFromDB(self, message_descriptor, number): + """Try to Load extensions from descriptor db. + + Args: + message_descriptor: descriptor of the extended message. + number: the extension number that needs to be loaded. + """ + if not self._descriptor_db: + return + # Only supported when FindFileContainingExtension is provided. + if not hasattr( + self._descriptor_db, 'FindFileContainingExtension'): + return + + full_name = message_descriptor.full_name + file_proto = None + try: + file_proto = self._descriptor_db.FindFileContainingExtension( + full_name, number + ) + except: + return + + if file_proto is None: + return + + try: + self._ConvertFileProtoToFileDescriptor(file_proto) + except: + warn_msg = ('Unable to load proto file %s for extension number %d.' % + (file_proto.name, number)) + warnings.warn(warn_msg, RuntimeWarning) + + def FindServiceByName(self, full_name): + """Loads the named service descriptor from the pool. + + Args: + full_name (str): The full name of the service descriptor to load. + + Returns: + ServiceDescriptor: The service descriptor for the named service. + + Raises: + KeyError: if the service cannot be found in the pool. + """ + full_name = _NormalizeFullyQualifiedName(full_name) + if full_name not in self._service_descriptors: + self._FindFileContainingSymbolInDb(full_name) + return self._service_descriptors[full_name] + + def FindMethodByName(self, full_name): + """Loads the named service method descriptor from the pool. + + Args: + full_name (str): The full name of the method descriptor to load. + + Returns: + MethodDescriptor: The method descriptor for the service method. + + Raises: + KeyError: if the method cannot be found in the pool. + """ + full_name = _NormalizeFullyQualifiedName(full_name) + service_name, _, method_name = full_name.rpartition('.') + service_descriptor = self.FindServiceByName(service_name) + return service_descriptor.methods_by_name[method_name] + + def SetFeatureSetDefaults(self, defaults): + """Sets the default feature mappings used during the build. + + Args: + defaults: a FeatureSetDefaults message containing the new mappings. + """ + if self._edition_defaults is not None: + raise ValueError( + "Feature set defaults can't be changed once the pool has started" + ' building!' + ) + + # pylint: disable=g-import-not-at-top + from google.protobuf import descriptor_pb2 + + if not isinstance(defaults, descriptor_pb2.FeatureSetDefaults): + raise TypeError('SetFeatureSetDefaults called with invalid type') + + if defaults.minimum_edition > defaults.maximum_edition: + raise ValueError( + 'Invalid edition range %s to %s' + % ( + descriptor_pb2.Edition.Name(defaults.minimum_edition), + descriptor_pb2.Edition.Name(defaults.maximum_edition), + ) + ) + + prev_edition = descriptor_pb2.Edition.EDITION_UNKNOWN + for d in defaults.defaults: + if d.edition == descriptor_pb2.Edition.EDITION_UNKNOWN: + raise ValueError('Invalid edition EDITION_UNKNOWN specified') + if prev_edition >= d.edition: + raise ValueError( + 'Feature set defaults are not strictly increasing. %s is greater' + ' than or equal to %s' + % ( + descriptor_pb2.Edition.Name(prev_edition), + descriptor_pb2.Edition.Name(d.edition), + ) + ) + prev_edition = d.edition + self._edition_defaults = defaults + + def _CreateDefaultFeatures(self, edition): + """Creates a FeatureSet message with defaults for a specific edition. + + Args: + edition: the edition to generate defaults for. + + Returns: + A FeatureSet message with defaults for a specific edition. + """ + # pylint: disable=g-import-not-at-top + from google.protobuf import descriptor_pb2 + + with _edition_defaults_lock: + if not self._edition_defaults: + self._edition_defaults = descriptor_pb2.FeatureSetDefaults() + self._edition_defaults.ParseFromString( + self._serialized_edition_defaults + ) + + if edition < self._edition_defaults.minimum_edition: + raise TypeError( + 'Edition %s is earlier than the minimum supported edition %s!' + % ( + descriptor_pb2.Edition.Name(edition), + descriptor_pb2.Edition.Name( + self._edition_defaults.minimum_edition + ), + ) + ) + if ( + edition > self._edition_defaults.maximum_edition + and edition != descriptor_pb2.EDITION_UNSTABLE + ): + raise TypeError( + 'Edition %s is later than the maximum supported edition %s!' + % ( + descriptor_pb2.Edition.Name(edition), + descriptor_pb2.Edition.Name( + self._edition_defaults.maximum_edition + ), + ) + ) + found = None + for d in self._edition_defaults.defaults: + if d.edition > edition: + break + found = d + if found is None: + raise TypeError( + 'No valid default found for edition %s!' + % descriptor_pb2.Edition.Name(edition) + ) + + defaults = descriptor_pb2.FeatureSet() + defaults.CopyFrom(found.fixed_features) + defaults.MergeFrom(found.overridable_features) + return defaults + + def _InternFeatures(self, features): + serialized = features.SerializeToString() + with _edition_defaults_lock: + cached = self._feature_cache.get(serialized) + if cached is None: + self._feature_cache[serialized] = features + cached = features + return cached + + def _FindFileContainingSymbolInDb(self, symbol): + """Finds the file in descriptor DB containing the specified symbol. + + Args: + symbol (str): The name of the symbol to search for. + + Returns: + FileDescriptor: The file that contains the specified symbol. + + Raises: + KeyError: if the file cannot be found in the descriptor database. + """ + try: + file_proto = self._internal_db.FindFileContainingSymbol(symbol) + except KeyError as error: + if self._descriptor_db: + file_proto = self._descriptor_db.FindFileContainingSymbol(symbol) + else: + raise error + if not file_proto: + raise KeyError('Cannot find a file containing %s' % symbol) + return self._ConvertFileProtoToFileDescriptor(file_proto) + + def _ConvertFileProtoToFileDescriptor(self, file_proto): + """Creates a FileDescriptor from a proto or returns a cached copy. + + This method also has the side effect of loading all the symbols found in + the file into the appropriate dictionaries in the pool. + + Args: + file_proto: The proto to convert. + + Returns: + A FileDescriptor matching the passed in proto. + """ + if file_proto.name not in self._file_descriptors: + built_deps = list(self._GetDeps(file_proto.dependency)) + direct_deps = [self.FindFileByName(n) for n in file_proto.dependency] + public_deps = [direct_deps[i] for i in file_proto.public_dependency] + + # pylint: disable=g-import-not-at-top + from google.protobuf import descriptor_pb2 + + file_descriptor = descriptor.FileDescriptor( + pool=self, + name=file_proto.name, + package=file_proto.package, + syntax=file_proto.syntax, + edition=descriptor_pb2.Edition.Name(file_proto.edition), + options=_OptionsOrNone(file_proto), + serialized_pb=file_proto.SerializeToString(), + dependencies=direct_deps, + public_dependencies=public_deps, + # pylint: disable=protected-access + create_key=descriptor._internal_create_key, + ) + scope = {} + + # This loop extracts all the message and enum types from all the + # dependencies of the file_proto. This is necessary to create the + # scope of available message types when defining the passed in + # file proto. + for dependency in built_deps: + scope.update(self._ExtractSymbols( + dependency.message_types_by_name.values())) + scope.update((_PrefixWithDot(enum.full_name), enum) + for enum in dependency.enum_types_by_name.values()) + + for message_type in file_proto.message_type: + message_desc = self._ConvertMessageDescriptor( + message_type, file_proto.package, file_descriptor, scope, + file_proto.syntax) + file_descriptor.message_types_by_name[message_desc.name] = ( + message_desc) + + for enum_type in file_proto.enum_type: + file_descriptor.enum_types_by_name[enum_type.name] = ( + self._ConvertEnumDescriptor(enum_type, file_proto.package, + file_descriptor, None, scope, True)) + + for index, extension_proto in enumerate(file_proto.extension): + extension_desc = self._MakeFieldDescriptor( + extension_proto, file_proto.package, index, file_descriptor, + is_extension=True) + extension_desc.containing_type = self._GetTypeFromScope( + file_descriptor.package, extension_proto.extendee, scope) + self._SetFieldType(extension_proto, extension_desc, + file_descriptor.package, scope) + file_descriptor.extensions_by_name[extension_desc.name] = ( + extension_desc) + + for desc_proto in file_proto.message_type: + self._SetAllFieldTypes(file_proto.package, desc_proto, scope) + + if file_proto.package: + desc_proto_prefix = _PrefixWithDot(file_proto.package) + else: + desc_proto_prefix = '' + + for desc_proto in file_proto.message_type: + desc = self._GetTypeFromScope( + desc_proto_prefix, desc_proto.name, scope) + file_descriptor.message_types_by_name[desc_proto.name] = desc + + for index, service_proto in enumerate(file_proto.service): + file_descriptor.services_by_name[service_proto.name] = ( + self._MakeServiceDescriptor(service_proto, index, scope, + file_proto.package, file_descriptor)) + + self._file_descriptors[file_proto.name] = file_descriptor + + # Add extensions to the pool + def AddExtensionForNested(message_type): + for nested in message_type.nested_types: + AddExtensionForNested(nested) + for extension in message_type.extensions: + self._AddExtensionDescriptor(extension) + + file_desc = self._file_descriptors[file_proto.name] + for extension in file_desc.extensions_by_name.values(): + self._AddExtensionDescriptor(extension) + for message_type in file_desc.message_types_by_name.values(): + AddExtensionForNested(message_type) + + return file_desc + + def _ConvertMessageDescriptor(self, desc_proto, package=None, file_desc=None, + scope=None, syntax=None): + """Adds the proto to the pool in the specified package. + + Args: + desc_proto: The descriptor_pb2.DescriptorProto protobuf message. + package: The package the proto should be located in. + file_desc: The file containing this message. + scope: Dict mapping short and full symbols to message and enum types. + syntax: string indicating syntax of the file ("proto2" or "proto3") + + Returns: + The added descriptor. + """ + + if package: + desc_name = '.'.join((package, desc_proto.name)) + else: + desc_name = desc_proto.name + + if file_desc is None: + file_name = None + else: + file_name = file_desc.name + + if scope is None: + scope = {} + + nested = [ + self._ConvertMessageDescriptor( + nested, desc_name, file_desc, scope, syntax) + for nested in desc_proto.nested_type] + enums = [ + self._ConvertEnumDescriptor(enum, desc_name, file_desc, None, + scope, False) + for enum in desc_proto.enum_type] + fields = [self._MakeFieldDescriptor(field, desc_name, index, file_desc) + for index, field in enumerate(desc_proto.field)] + extensions = [ + self._MakeFieldDescriptor(extension, desc_name, index, file_desc, + is_extension=True) + for index, extension in enumerate(desc_proto.extension)] + oneofs = [ + # pylint: disable=g-complex-comprehension + descriptor.OneofDescriptor( + desc.name, + '.'.join((desc_name, desc.name)), + index, + None, + [], + _OptionsOrNone(desc), + # pylint: disable=protected-access + create_key=descriptor._internal_create_key) + for index, desc in enumerate(desc_proto.oneof_decl) + ] + extension_ranges = [(r.start, r.end) for r in desc_proto.extension_range] + if extension_ranges: + is_extendable = True + else: + is_extendable = False + desc = descriptor.Descriptor( + name=desc_proto.name, + full_name=desc_name, + filename=file_name, + containing_type=None, + fields=fields, + oneofs=oneofs, + nested_types=nested, + enum_types=enums, + extensions=extensions, + options=_OptionsOrNone(desc_proto), + is_extendable=is_extendable, + extension_ranges=extension_ranges, + file=file_desc, + serialized_start=None, + serialized_end=None, + is_map_entry=desc_proto.options.map_entry, + # pylint: disable=protected-access + create_key=descriptor._internal_create_key, + ) + for nested in desc.nested_types: + nested.containing_type = desc + for enum in desc.enum_types: + enum.containing_type = desc + for field_index, field_desc in enumerate(desc_proto.field): + if field_desc.HasField('oneof_index'): + oneof_index = field_desc.oneof_index + oneofs[oneof_index].fields.append(fields[field_index]) + fields[field_index].containing_oneof = oneofs[oneof_index] + + scope[_PrefixWithDot(desc_name)] = desc + self._CheckConflictRegister(desc, desc.full_name, desc.file.name) + self._descriptors[desc_name] = desc + return desc + + def _ConvertEnumDescriptor(self, enum_proto, package=None, file_desc=None, + containing_type=None, scope=None, top_level=False): + """Make a protobuf EnumDescriptor given an EnumDescriptorProto protobuf. + + Args: + enum_proto: The descriptor_pb2.EnumDescriptorProto protobuf message. + package: Optional package name for the new message EnumDescriptor. + file_desc: The file containing the enum descriptor. + containing_type: The type containing this enum. + scope: Scope containing available types. + top_level: If True, the enum is a top level symbol. If False, the enum + is defined inside a message. + + Returns: + The added descriptor + """ + + if package: + enum_name = '.'.join((package, enum_proto.name)) + else: + enum_name = enum_proto.name + + if file_desc is None: + file_name = None + else: + file_name = file_desc.name + + values = [self._MakeEnumValueDescriptor(value, index) + for index, value in enumerate(enum_proto.value)] + desc = descriptor.EnumDescriptor(name=enum_proto.name, + full_name=enum_name, + filename=file_name, + file=file_desc, + values=values, + containing_type=containing_type, + options=_OptionsOrNone(enum_proto), + # pylint: disable=protected-access + create_key=descriptor._internal_create_key) + scope['.%s' % enum_name] = desc + self._CheckConflictRegister(desc, desc.full_name, desc.file.name) + self._enum_descriptors[enum_name] = desc + + # Add top level enum values. + if top_level: + for value in values: + full_name = _NormalizeFullyQualifiedName( + '.'.join((package, value.name))) + self._CheckConflictRegister(value, full_name, file_name) + self._top_enum_values[full_name] = value + + return desc + + def _MakeFieldDescriptor(self, field_proto, message_name, index, + file_desc, is_extension=False): + """Creates a field descriptor from a FieldDescriptorProto. + + For message and enum type fields, this method will do a look up + in the pool for the appropriate descriptor for that type. If it + is unavailable, it will fall back to the _source function to + create it. If this type is still unavailable, construction will + fail. + + Args: + field_proto: The proto describing the field. + message_name: The name of the containing message. + index: Index of the field + file_desc: The file containing the field descriptor. + is_extension: Indication that this field is for an extension. + + Returns: + An initialized FieldDescriptor object + """ + + if message_name: + full_name = '.'.join((message_name, field_proto.name)) + else: + full_name = field_proto.name + + if field_proto.json_name: + json_name = field_proto.json_name + else: + json_name = None + + return descriptor.FieldDescriptor( + name=field_proto.name, + full_name=full_name, + index=index, + number=field_proto.number, + type=field_proto.type, + cpp_type=None, + message_type=None, + enum_type=None, + containing_type=None, + label=field_proto.label, + has_default_value=False, + default_value=None, + is_extension=is_extension, + extension_scope=None, + options=_OptionsOrNone(field_proto), + json_name=json_name, + file=file_desc, + # pylint: disable=protected-access + create_key=descriptor._internal_create_key) + + def _SetAllFieldTypes(self, package, desc_proto, scope): + """Sets all the descriptor's fields's types. + + This method also sets the containing types on any extensions. + + Args: + package: The current package of desc_proto. + desc_proto: The message descriptor to update. + scope: Enclosing scope of available types. + """ + + package = _PrefixWithDot(package) + + main_desc = self._GetTypeFromScope(package, desc_proto.name, scope) + + if package == '.': + nested_package = _PrefixWithDot(desc_proto.name) + else: + nested_package = '.'.join([package, desc_proto.name]) + + for field_proto, field_desc in zip(desc_proto.field, main_desc.fields): + self._SetFieldType(field_proto, field_desc, nested_package, scope) + + for extension_proto, extension_desc in ( + zip(desc_proto.extension, main_desc.extensions)): + extension_desc.containing_type = self._GetTypeFromScope( + nested_package, extension_proto.extendee, scope) + self._SetFieldType(extension_proto, extension_desc, nested_package, scope) + + for nested_type in desc_proto.nested_type: + self._SetAllFieldTypes(nested_package, nested_type, scope) + + def _SetFieldType(self, field_proto, field_desc, package, scope): + """Sets the field's type, cpp_type, message_type and enum_type. + + Args: + field_proto: Data about the field in proto format. + field_desc: The descriptor to modify. + package: The package the field's container is in. + scope: Enclosing scope of available types. + """ + if field_proto.type_name: + desc = self._GetTypeFromScope(package, field_proto.type_name, scope) + else: + desc = None + + if not field_proto.HasField('type'): + if isinstance(desc, descriptor.Descriptor): + field_proto.type = descriptor.FieldDescriptor.TYPE_MESSAGE + else: + field_proto.type = descriptor.FieldDescriptor.TYPE_ENUM + + field_desc.cpp_type = descriptor.FieldDescriptor.ProtoTypeToCppProtoType( + field_proto.type) + + if (field_proto.type == descriptor.FieldDescriptor.TYPE_MESSAGE + or field_proto.type == descriptor.FieldDescriptor.TYPE_GROUP): + field_desc.message_type = desc + + if field_proto.type == descriptor.FieldDescriptor.TYPE_ENUM: + field_desc.enum_type = desc + + if field_proto.label == descriptor.FieldDescriptor.LABEL_REPEATED: + field_desc.has_default_value = False + field_desc.default_value = [] + elif field_proto.HasField('default_value'): + field_desc.has_default_value = True + if (field_proto.type == descriptor.FieldDescriptor.TYPE_DOUBLE or + field_proto.type == descriptor.FieldDescriptor.TYPE_FLOAT): + field_desc.default_value = float(field_proto.default_value) + elif field_proto.type == descriptor.FieldDescriptor.TYPE_STRING: + field_desc.default_value = field_proto.default_value + elif field_proto.type == descriptor.FieldDescriptor.TYPE_BOOL: + field_desc.default_value = field_proto.default_value.lower() == 'true' + elif field_proto.type == descriptor.FieldDescriptor.TYPE_ENUM: + field_desc.default_value = field_desc.enum_type.values_by_name[ + field_proto.default_value].number + elif field_proto.type == descriptor.FieldDescriptor.TYPE_BYTES: + field_desc.default_value = text_encoding.CUnescape( + field_proto.default_value) + elif field_proto.type == descriptor.FieldDescriptor.TYPE_MESSAGE: + field_desc.default_value = None + else: + # All other types are of the "int" type. + field_desc.default_value = int(field_proto.default_value) + else: + field_desc.has_default_value = False + if (field_proto.type == descriptor.FieldDescriptor.TYPE_DOUBLE or + field_proto.type == descriptor.FieldDescriptor.TYPE_FLOAT): + field_desc.default_value = 0.0 + elif field_proto.type == descriptor.FieldDescriptor.TYPE_STRING: + field_desc.default_value = u'' + elif field_proto.type == descriptor.FieldDescriptor.TYPE_BOOL: + field_desc.default_value = False + elif field_proto.type == descriptor.FieldDescriptor.TYPE_ENUM: + field_desc.default_value = field_desc.enum_type.values[0].number + elif field_proto.type == descriptor.FieldDescriptor.TYPE_BYTES: + field_desc.default_value = b'' + elif field_proto.type == descriptor.FieldDescriptor.TYPE_MESSAGE: + field_desc.default_value = None + elif field_proto.type == descriptor.FieldDescriptor.TYPE_GROUP: + field_desc.default_value = None + else: + # All other types are of the "int" type. + field_desc.default_value = 0 + + field_desc.type = field_proto.type + + def _MakeEnumValueDescriptor(self, value_proto, index): + """Creates a enum value descriptor object from a enum value proto. + + Args: + value_proto: The proto describing the enum value. + index: The index of the enum value. + + Returns: + An initialized EnumValueDescriptor object. + """ + + return descriptor.EnumValueDescriptor( + name=value_proto.name, + index=index, + number=value_proto.number, + options=_OptionsOrNone(value_proto), + type=None, + # pylint: disable=protected-access + create_key=descriptor._internal_create_key) + + def _MakeServiceDescriptor(self, service_proto, service_index, scope, + package, file_desc): + """Make a protobuf ServiceDescriptor given a ServiceDescriptorProto. + + Args: + service_proto: The descriptor_pb2.ServiceDescriptorProto protobuf message. + service_index: The index of the service in the File. + scope: Dict mapping short and full symbols to message and enum types. + package: Optional package name for the new message EnumDescriptor. + file_desc: The file containing the service descriptor. + + Returns: + The added descriptor. + """ + + if package: + service_name = '.'.join((package, service_proto.name)) + else: + service_name = service_proto.name + + methods = [self._MakeMethodDescriptor(method_proto, service_name, package, + scope, index) + for index, method_proto in enumerate(service_proto.method)] + desc = descriptor.ServiceDescriptor( + name=service_proto.name, + full_name=service_name, + index=service_index, + methods=methods, + options=_OptionsOrNone(service_proto), + file=file_desc, + # pylint: disable=protected-access + create_key=descriptor._internal_create_key) + self._CheckConflictRegister(desc, desc.full_name, desc.file.name) + self._service_descriptors[service_name] = desc + return desc + + def _MakeMethodDescriptor(self, method_proto, service_name, package, scope, + index): + """Creates a method descriptor from a MethodDescriptorProto. + + Args: + method_proto: The proto describing the method. + service_name: The name of the containing service. + package: Optional package name to look up for types. + scope: Scope containing available types. + index: Index of the method in the service. + + Returns: + An initialized MethodDescriptor object. + """ + full_name = '.'.join((service_name, method_proto.name)) + input_type = self._GetTypeFromScope( + package, method_proto.input_type, scope) + output_type = self._GetTypeFromScope( + package, method_proto.output_type, scope) + return descriptor.MethodDescriptor( + name=method_proto.name, + full_name=full_name, + index=index, + containing_service=None, + input_type=input_type, + output_type=output_type, + client_streaming=method_proto.client_streaming, + server_streaming=method_proto.server_streaming, + options=_OptionsOrNone(method_proto), + # pylint: disable=protected-access + create_key=descriptor._internal_create_key) + + def _ExtractSymbols(self, descriptors): + """Pulls out all the symbols from descriptor protos. + + Args: + descriptors: The messages to extract descriptors from. + Yields: + A two element tuple of the type name and descriptor object. + """ + + for desc in descriptors: + yield (_PrefixWithDot(desc.full_name), desc) + for symbol in self._ExtractSymbols(desc.nested_types): + yield symbol + for enum in desc.enum_types: + yield (_PrefixWithDot(enum.full_name), enum) + + def _GetDeps(self, dependencies, visited=None): + """Recursively finds dependencies for file protos. + + Args: + dependencies: The names of the files being depended on. + visited: The names of files already found. + + Yields: + Each direct and indirect dependency. + """ + + visited = visited or set() + for dependency in dependencies: + if dependency not in visited: + visited.add(dependency) + dep_desc = self.FindFileByName(dependency) + yield dep_desc + public_files = [d.name for d in dep_desc.public_dependencies] + yield from self._GetDeps(public_files, visited) + + def _GetTypeFromScope(self, package, type_name, scope): + """Finds a given type name in the current scope. + + Args: + package: The package the proto should be located in. + type_name: The name of the type to be found in the scope. + scope: Dict mapping short and full symbols to message and enum types. + + Returns: + The descriptor for the requested type. + """ + if type_name not in scope: + components = _PrefixWithDot(package).split('.') + while components: + possible_match = '.'.join(components + [type_name]) + if possible_match in scope: + type_name = possible_match + break + else: + components.pop(-1) + return scope[type_name] + + +def _PrefixWithDot(name): + return name if name.startswith('.') else '.%s' % name + + +if _USE_C_DESCRIPTORS: + # TODO: This pool could be constructed from Python code, when we + # support a flag like 'use_cpp_generated_pool=True'. + # pylint: disable=protected-access + _DEFAULT = descriptor._message.default_pool +else: + _DEFAULT = DescriptorPool() + + +def Default(): + return _DEFAULT diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/duration.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/duration.py new file mode 100644 index 0000000000000000000000000000000000000000..21f17bf71a2f34f412849a24989a6b406df817d0 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/duration.py @@ -0,0 +1,100 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""Contains the Duration helper APIs.""" + +import datetime + +from google.protobuf.duration_pb2 import Duration + + +def from_json_string(value: str) -> Duration: + """Converts a string to Duration. + + Args: + value: A string to be converted. The string must end with 's'. Any + fractional digits (or none) are accepted as long as they fit into + precision. For example: "1s", "1.01s", "1.0000001s", "-3.100s" + + Raises: + ValueError: On parsing problems. + """ + duration = Duration() + duration.FromJsonString(value) + return duration + + +def from_microseconds(micros: float) -> Duration: + """Converts microseconds to Duration.""" + duration = Duration() + duration.FromMicroseconds(micros) + return duration + + +def from_milliseconds(millis: float) -> Duration: + """Converts milliseconds to Duration.""" + duration = Duration() + duration.FromMilliseconds(millis) + return duration + + +def from_nanoseconds(nanos: float) -> Duration: + """Converts nanoseconds to Duration.""" + duration = Duration() + duration.FromNanoseconds(nanos) + return duration + + +def from_seconds(seconds: float) -> Duration: + """Converts seconds to Duration.""" + duration = Duration() + duration.FromSeconds(seconds) + return duration + + +def from_timedelta(td: datetime.timedelta) -> Duration: + """Converts timedelta to Duration.""" + duration = Duration() + duration.FromTimedelta(td) + return duration + + +def to_json_string(duration: Duration) -> str: + """Converts Duration to string format. + + Returns: + A string converted from self. The string format will contains + 3, 6, or 9 fractional digits depending on the precision required to + represent the exact Duration value. For example: "1s", "1.010s", + "1.000000100s", "-3.100s" + """ + return duration.ToJsonString() + + +def to_microseconds(duration: Duration) -> int: + """Converts a Duration to microseconds.""" + return duration.ToMicroseconds() + + +def to_milliseconds(duration: Duration) -> int: + """Converts a Duration to milliseconds.""" + return duration.ToMilliseconds() + + +def to_nanoseconds(duration: Duration) -> int: + """Converts a Duration to nanoseconds.""" + return duration.ToNanoseconds() + + +def to_seconds(duration: Duration) -> int: + """Converts a Duration to seconds.""" + return duration.ToSeconds() + + +def to_timedelta(duration: Duration) -> datetime.timedelta: + """Converts Duration to timedelta.""" + return duration.ToTimedelta() diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/duration_pb2.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/duration_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..443ab4f5fc31143dc4e9296a7f728192fec932de --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/duration_pb2.py @@ -0,0 +1,37 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# NO CHECKED-IN PROTOBUF GENCODE +# source: google/protobuf/duration.proto +# Protobuf Python Version: 6.33.6 +"""Generated protocol buffer code.""" +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import runtime_version as _runtime_version +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder +_runtime_version.ValidateProtobufRuntimeVersion( + _runtime_version.Domain.PUBLIC, + 6, + 33, + 6, + '', + 'google/protobuf/duration.proto' +) +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1egoogle/protobuf/duration.proto\x12\x0fgoogle.protobuf\":\n\x08\x44uration\x12\x18\n\x07seconds\x18\x01 \x01(\x03R\x07seconds\x12\x14\n\x05nanos\x18\x02 \x01(\x05R\x05nanosB\x83\x01\n\x13\x63om.google.protobufB\rDurationProtoP\x01Z1google.golang.org/protobuf/types/known/durationpb\xf8\x01\x01\xa2\x02\x03GPB\xaa\x02\x1eGoogle.Protobuf.WellKnownTypesb\x06proto3') + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.duration_pb2', _globals) +if not _descriptor._USE_C_DESCRIPTORS: + _globals['DESCRIPTOR']._loaded_options = None + _globals['DESCRIPTOR']._serialized_options = b'\n\023com.google.protobufB\rDurationProtoP\001Z1google.golang.org/protobuf/types/known/durationpb\370\001\001\242\002\003GPB\252\002\036Google.Protobuf.WellKnownTypes' + _globals['_DURATION']._serialized_start=51 + _globals['_DURATION']._serialized_end=109 +# @@protoc_insertion_point(module_scope) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/empty_pb2.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/empty_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..1cca1ad126fbca1fc458094d1bad618c965aee4b --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/empty_pb2.py @@ -0,0 +1,37 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# NO CHECKED-IN PROTOBUF GENCODE +# source: google/protobuf/empty.proto +# Protobuf Python Version: 6.33.6 +"""Generated protocol buffer code.""" +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import runtime_version as _runtime_version +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder +_runtime_version.ValidateProtobufRuntimeVersion( + _runtime_version.Domain.PUBLIC, + 6, + 33, + 6, + '', + 'google/protobuf/empty.proto' +) +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1bgoogle/protobuf/empty.proto\x12\x0fgoogle.protobuf\"\x07\n\x05\x45mptyB}\n\x13\x63om.google.protobufB\nEmptyProtoP\x01Z.google.golang.org/protobuf/types/known/emptypb\xf8\x01\x01\xa2\x02\x03GPB\xaa\x02\x1eGoogle.Protobuf.WellKnownTypesb\x06proto3') + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.empty_pb2', _globals) +if not _descriptor._USE_C_DESCRIPTORS: + _globals['DESCRIPTOR']._loaded_options = None + _globals['DESCRIPTOR']._serialized_options = b'\n\023com.google.protobufB\nEmptyProtoP\001Z.google.golang.org/protobuf/types/known/emptypb\370\001\001\242\002\003GPB\252\002\036Google.Protobuf.WellKnownTypes' + _globals['_EMPTY']._serialized_start=48 + _globals['_EMPTY']._serialized_end=55 +# @@protoc_insertion_point(module_scope) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/field_mask_pb2.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/field_mask_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..1470ee3139204a79bd6324f7e7c9562ddec54f13 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/field_mask_pb2.py @@ -0,0 +1,37 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# NO CHECKED-IN PROTOBUF GENCODE +# source: google/protobuf/field_mask.proto +# Protobuf Python Version: 6.33.6 +"""Generated protocol buffer code.""" +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import runtime_version as _runtime_version +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder +_runtime_version.ValidateProtobufRuntimeVersion( + _runtime_version.Domain.PUBLIC, + 6, + 33, + 6, + '', + 'google/protobuf/field_mask.proto' +) +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n google/protobuf/field_mask.proto\x12\x0fgoogle.protobuf\"!\n\tFieldMask\x12\x14\n\x05paths\x18\x01 \x03(\tR\x05pathsB\x85\x01\n\x13\x63om.google.protobufB\x0e\x46ieldMaskProtoP\x01Z2google.golang.org/protobuf/types/known/fieldmaskpb\xf8\x01\x01\xa2\x02\x03GPB\xaa\x02\x1eGoogle.Protobuf.WellKnownTypesb\x06proto3') + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.field_mask_pb2', _globals) +if not _descriptor._USE_C_DESCRIPTORS: + _globals['DESCRIPTOR']._loaded_options = None + _globals['DESCRIPTOR']._serialized_options = b'\n\023com.google.protobufB\016FieldMaskProtoP\001Z2google.golang.org/protobuf/types/known/fieldmaskpb\370\001\001\242\002\003GPB\252\002\036Google.Protobuf.WellKnownTypes' + _globals['_FIELDMASK']._serialized_start=53 + _globals['_FIELDMASK']._serialized_end=86 +# @@protoc_insertion_point(module_scope) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e676e288161e00ae5c266d080ca5018336849a7d --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__init__.py @@ -0,0 +1,7 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/__init__.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c250505c942791f2e4070b3367a7a70d4e87d985 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/__init__.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/api_implementation.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/api_implementation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f9db6147e9dddf339c3cb7202b50375c9282fe5b Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/api_implementation.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/builder.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/builder.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7a288cad7b0e2f280442d7ae968fcf269420f31 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/builder.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/containers.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/containers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a5b4bc93b06ee2d6dc598882e5d9719749e7abf Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/containers.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/decoder.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/decoder.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf467316b4ff888c8589631a4a1e8648ee16b1e4 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/decoder.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/encoder.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/encoder.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb649ad76ee8dc40ce1fada3e747afb5d37d9d90 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/encoder.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/enum_type_wrapper.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/enum_type_wrapper.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1861620c94a3e0e1d9c4a28d0fcc58f795dda292 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/enum_type_wrapper.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/extension_dict.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/extension_dict.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8dd083652f84d895d39346e57f3dc43849e2e5b8 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/extension_dict.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/field_mask.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/field_mask.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f7617c6562974871f0a31b6a4a4b413c89b74c62 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/field_mask.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/message_listener.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/message_listener.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..899876680234075b16de425188e3da7f2250c45c Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/message_listener.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/python_edition_defaults.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/python_edition_defaults.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bdfb20436c488227ed770dd361c5827f75db783f Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/python_edition_defaults.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/python_message.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/python_message.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8fb3b02259e1a21ec6363a115f71075dfabe9b8c Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/python_message.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/type_checkers.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/type_checkers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71f9eeae1e4743f0c92ec1a7eca7f4ab8bc2a53f Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/type_checkers.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/well_known_types.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/well_known_types.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a0e9b35f2076b5958ada440e29697ead1bd64e2 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/well_known_types.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/wire_format.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/wire_format.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bd00aee07aa24d9f5ba6b23ca3968e913bb56ee0 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/__pycache__/wire_format.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/api_implementation.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/api_implementation.py new file mode 100644 index 0000000000000000000000000000000000000000..f4346bce945fc943d39394012e1817c49a57ed47 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/api_implementation.py @@ -0,0 +1,136 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""Determine which implementation of the protobuf API is used in this process. +""" + +import importlib +import os +import sys +import warnings + +_GOOGLE3_PYTHON_UPB_DEFAULT = True + + +def _ApiVersionToImplementationType(api_version): + if api_version == 2: + return 'cpp' + if api_version == 1: + raise ValueError('api_version=1 is no longer supported.') + if api_version == 0: + return 'python' + return None + + +_implementation_type = None +try: + # pylint: disable=g-import-not-at-top + from google.protobuf.internal import _api_implementation + # The compile-time constants in the _api_implementation module can be used to + # switch to a certain implementation of the Python API at build time. + _implementation_type = _ApiVersionToImplementationType( + _api_implementation.api_version) +except ImportError: + pass # Unspecified by compiler flags. + + +def _CanImport(mod_name): + try: + mod = importlib.import_module(mod_name) + # Work around a known issue in the classic bootstrap .par import hook. + if not mod: + raise ImportError(mod_name + ' import succeeded but was None') + return True + except ImportError: + return False + + +if _implementation_type is None: + if _CanImport('google._upb._message'): + _implementation_type = 'upb' + elif _CanImport('google.protobuf.pyext._message'): + _implementation_type = 'cpp' + else: + _implementation_type = 'python' + + +# This environment variable can be used to switch to a certain implementation +# of the Python API, overriding the compile-time constants in the +# _api_implementation module. Right now only 'python', 'cpp' and 'upb' are +# valid values. Any other value will raise error. +_implementation_type = os.getenv('PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION', + _implementation_type) + +if _implementation_type not in ('python', 'cpp', 'upb'): + raise ValueError('PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION {0} is not ' + 'supported. Please set to \'python\', \'cpp\' or ' + '\'upb\'.'.format(_implementation_type)) + +if 'PyPy' in sys.version and _implementation_type == 'cpp': + warnings.warn('PyPy does not work yet with cpp protocol buffers. ' + 'Falling back to the python implementation.') + _implementation_type = 'python' + +_c_module = None + +if _implementation_type == 'cpp': + try: + # pylint: disable=g-import-not-at-top + from google.protobuf.pyext import _message + sys.modules['google3.net.proto2.python.internal.cpp._message'] = _message + _c_module = _message + del _message + except ImportError: + # TODO: fail back to python + warnings.warn( + 'Selected implementation cpp is not available.') + pass + +if _implementation_type == 'upb': + try: + # pylint: disable=g-import-not-at-top + from google._upb import _message + _c_module = _message + del _message + except ImportError: + warnings.warn('Selected implementation upb is not available. ' + 'Falling back to the python implementation.') + _implementation_type = 'python' + pass + +# Detect if serialization should be deterministic by default +try: + # The presence of this module in a build allows the proto implementation to + # be upgraded merely via build deps. + # + # NOTE: Merely importing this automatically enables deterministic proto + # serialization for C++ code, but we still need to export it as a boolean so + # that we can do the same for `_implementation_type == 'python'`. + # + # NOTE2: It is possible for C++ code to enable deterministic serialization by + # default _without_ affecting Python code, if the C++ implementation is not in + # use by this module. That is intended behavior, so we don't actually expose + # this boolean outside of this module. + # + # pylint: disable=g-import-not-at-top,unused-import + from google.protobuf import enable_deterministic_proto_serialization + _python_deterministic_proto_serialization = True +except ImportError: + _python_deterministic_proto_serialization = False + + +# Usage of this function is discouraged. Clients shouldn't care which +# implementation of the API is in use. Note that there is no guarantee +# that differences between APIs will be maintained. +# Please don't use this function if possible. +def Type(): + return _implementation_type + + +# For internal use only +def IsPythonDefaultSerializationDeterministic(): + return _python_deterministic_proto_serialization diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/builder.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/builder.py new file mode 100644 index 0000000000000000000000000000000000000000..9859e490e6415c3d6222f131631062156d2a4890 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/builder.py @@ -0,0 +1,118 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""Builds descriptors, message classes and services for generated _pb2.py. + +This file is only called in python generated _pb2.py files. It builds +descriptors, message classes and services that users can directly use +in generated code. +""" + +__author__ = 'jieluo@google.com (Jie Luo)' + +from google.protobuf.internal import enum_type_wrapper +from google.protobuf.internal import python_message +from google.protobuf import message as _message +from google.protobuf import reflection as _reflection +from google.protobuf import symbol_database as _symbol_database + +_sym_db = _symbol_database.Default() + + +def BuildMessageAndEnumDescriptors(file_des, module): + """Builds message and enum descriptors. + + Args: + file_des: FileDescriptor of the .proto file + module: Generated _pb2 module + """ + + def BuildNestedDescriptors(msg_des, prefix): + for (name, nested_msg) in msg_des.nested_types_by_name.items(): + module_name = prefix + name.upper() + module[module_name] = nested_msg + BuildNestedDescriptors(nested_msg, module_name + '_') + for enum_des in msg_des.enum_types: + module[prefix + enum_des.name.upper()] = enum_des + + for (name, msg_des) in file_des.message_types_by_name.items(): + module_name = '_' + name.upper() + module[module_name] = msg_des + BuildNestedDescriptors(msg_des, module_name + '_') + + +def BuildTopDescriptorsAndMessages(file_des, module_name, module): + """Builds top level descriptors and message classes. + + Args: + file_des: FileDescriptor of the .proto file + module_name: str, the name of generated _pb2 module + module: Generated _pb2 module + """ + + def BuildMessage(msg_des, prefix): + create_dict = {} + for (name, nested_msg) in msg_des.nested_types_by_name.items(): + create_dict[name] = BuildMessage(nested_msg, prefix + msg_des.name + '.') + create_dict['DESCRIPTOR'] = msg_des + create_dict['__module__'] = module_name + create_dict['__qualname__'] = prefix + msg_des.name + message_class = _reflection.GeneratedProtocolMessageType( + msg_des.name, (_message.Message,), create_dict) + _sym_db.RegisterMessage(message_class) + return message_class + + # top level enums + for (name, enum_des) in file_des.enum_types_by_name.items(): + module['_' + name.upper()] = enum_des + module[name] = enum_type_wrapper.EnumTypeWrapper(enum_des) + for enum_value in enum_des.values: + module[enum_value.name] = enum_value.number + + # top level extensions + for (name, extension_des) in file_des.extensions_by_name.items(): + module[name.upper() + '_FIELD_NUMBER'] = extension_des.number + module[name] = extension_des + + # services + for (name, service) in file_des.services_by_name.items(): + module['_' + name.upper()] = service + + # Build messages. + for (name, msg_des) in file_des.message_types_by_name.items(): + module[name] = BuildMessage(msg_des, '') + + +def AddHelpersToExtensions(file_des): + """no-op to keep old generated code work with new runtime. + + Args: + file_des: FileDescriptor of the .proto file + """ + # TODO: Remove this on-op + return + + +def BuildServices(file_des, module_name, module): + """Builds services classes and services stub class. + + Args: + file_des: FileDescriptor of the .proto file + module_name: str, the name of generated _pb2 module + module: Generated _pb2 module + """ + # pylint: disable=g-import-not-at-top + from google.protobuf import service_reflection + # pylint: enable=g-import-not-at-top + for (name, service) in file_des.services_by_name.items(): + module[name] = service_reflection.GeneratedServiceType( + name, (), + dict(DESCRIPTOR=service, __module__=module_name)) + stub_name = name + '_Stub' + module[stub_name] = service_reflection.GeneratedServiceStubType( + stub_name, (module[name],), + dict(DESCRIPTOR=service, __module__=module_name)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/containers.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/containers.py new file mode 100644 index 0000000000000000000000000000000000000000..7298bc5c7a33dad27b1e933fc04c1435ae4b6986 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/containers.py @@ -0,0 +1,690 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""Contains container classes to represent different protocol buffer types. + +This file defines container classes which represent categories of protocol +buffer field types which need extra maintenance. Currently these categories +are: + +- Repeated scalar fields - These are all repeated fields which aren't + composite (e.g. they are of simple types like int32, string, etc). +- Repeated composite fields - Repeated fields which are composite. This + includes groups and nested messages. +""" + +import collections.abc +import copy +import pickle +from typing import ( + Any, + Iterable, + Iterator, + List, + MutableMapping, + MutableSequence, + NoReturn, + Optional, + Sequence, + TypeVar, + Union, + overload, +) + + +_T = TypeVar('_T') +_K = TypeVar('_K') +_V = TypeVar('_V') + + +class BaseContainer(Sequence[_T]): + """Base container class.""" + + # Minimizes memory usage and disallows assignment to other attributes. + __slots__ = ['_message_listener', '_values'] + + def __init__(self, message_listener: Any) -> None: + """ + Args: + message_listener: A MessageListener implementation. + The RepeatedScalarFieldContainer will call this object's + Modified() method when it is modified. + """ + self._message_listener = message_listener + self._values = [] + + @overload + def __getitem__(self, key: int) -> _T: + ... + + @overload + def __getitem__(self, key: slice) -> List[_T]: + ... + + def __getitem__(self, key): + """Retrieves item by the specified key.""" + return self._values[key] + + def __len__(self) -> int: + """Returns the number of elements in the container.""" + return len(self._values) + + def __ne__(self, other: Any) -> bool: + """Checks if another instance isn't equal to this one.""" + # The concrete classes should define __eq__. + return not self == other + + __hash__ = None + + def __repr__(self) -> str: + return repr(self._values) + + def sort(self, *args, **kwargs) -> None: + # Continue to support the old sort_function keyword argument. + # This is expected to be a rare occurrence, so use LBYL to avoid + # the overhead of actually catching KeyError. + if 'sort_function' in kwargs: + kwargs['cmp'] = kwargs.pop('sort_function') + self._values.sort(*args, **kwargs) + + def reverse(self) -> None: + self._values.reverse() + + +# TODO: Remove this. BaseContainer does *not* conform to +# MutableSequence, only its subclasses do. +collections.abc.MutableSequence.register(BaseContainer) + + +class RepeatedScalarFieldContainer(BaseContainer[_T], MutableSequence[_T]): + """Simple, type-checked, list-like container for holding repeated scalars.""" + + # Disallows assignment to other attributes. + __slots__ = ['_type_checker'] + + def __init__( + self, + message_listener: Any, + type_checker: Any, + ) -> None: + """Args: + + message_listener: A MessageListener implementation. The + RepeatedScalarFieldContainer will call this object's Modified() method + when it is modified. + type_checker: A type_checkers.ValueChecker instance to run on elements + inserted into this container. + """ + super().__init__(message_listener) + self._type_checker = type_checker + + def append(self, value: _T) -> None: + """Appends an item to the list. Similar to list.append().""" + self._values.append(self._type_checker.CheckValue(value)) + if not self._message_listener.dirty: + self._message_listener.Modified() + + def insert(self, key: int, value: _T) -> None: + """Inserts the item at the specified position. Similar to list.insert().""" + self._values.insert(key, self._type_checker.CheckValue(value)) + if not self._message_listener.dirty: + self._message_listener.Modified() + + def extend(self, elem_seq: Iterable[_T]) -> None: + """Extends by appending the given iterable. Similar to list.extend().""" + elem_seq_iter = iter(elem_seq) + new_values = [self._type_checker.CheckValue(elem) for elem in elem_seq_iter] + if new_values: + self._values.extend(new_values) + self._message_listener.Modified() + + def MergeFrom( + self, + other: Union['RepeatedScalarFieldContainer[_T]', Iterable[_T]], + ) -> None: + """Appends the contents of another repeated field of the same type to this + one. We do not check the types of the individual fields. + """ + self._values.extend(other) + self._message_listener.Modified() + + def remove(self, elem: _T): + """Removes an item from the list. Similar to list.remove().""" + self._values.remove(elem) + self._message_listener.Modified() + + def pop(self, key: Optional[int] = -1) -> _T: + """Removes and returns an item at a given index. Similar to list.pop().""" + value = self._values[key] + self.__delitem__(key) + return value + + @overload + def __setitem__(self, key: int, value: _T) -> None: + ... + + @overload + def __setitem__(self, key: slice, value: Iterable[_T]) -> None: + ... + + def __setitem__(self, key, value) -> None: + """Sets the item on the specified position.""" + if isinstance(key, slice): + if key.step is not None: + raise ValueError('Extended slices not supported') + self._values[key] = map(self._type_checker.CheckValue, value) + self._message_listener.Modified() + else: + self._values[key] = self._type_checker.CheckValue(value) + self._message_listener.Modified() + + def __delitem__(self, key: Union[int, slice]) -> None: + """Deletes the item at the specified position.""" + del self._values[key] + self._message_listener.Modified() + + def __eq__(self, other: Any) -> bool: + """Compares the current instance with another one.""" + if self is other: + return True + # Special case for the same type which should be common and fast. + if isinstance(other, self.__class__): + return other._values == self._values + # We are presumably comparing against some other sequence type. + return other == self._values + + def __deepcopy__( + self, + unused_memo: Any = None, + ) -> 'RepeatedScalarFieldContainer[_T]': + clone = RepeatedScalarFieldContainer( + copy.deepcopy(self._message_listener), self._type_checker) + clone.MergeFrom(self) + return clone + + def __reduce__(self, **kwargs) -> NoReturn: + raise pickle.PickleError( + "Can't pickle repeated scalar fields, convert to list first") + + +# TODO: Constrain T to be a subtype of Message. +class RepeatedCompositeFieldContainer(BaseContainer[_T], MutableSequence[_T]): + """Simple, list-like container for holding repeated composite fields.""" + + # Disallows assignment to other attributes. + __slots__ = ['_message_descriptor'] + + def __init__(self, message_listener: Any, message_descriptor: Any) -> None: + """ + Note that we pass in a descriptor instead of the generated directly, + since at the time we construct a _RepeatedCompositeFieldContainer we + haven't yet necessarily initialized the type that will be contained in the + container. + + Args: + message_listener: A MessageListener implementation. + The RepeatedCompositeFieldContainer will call this object's + Modified() method when it is modified. + message_descriptor: A Descriptor instance describing the protocol type + that should be present in this container. We'll use the + _concrete_class field of this descriptor when the client calls add(). + """ + super().__init__(message_listener) + self._message_descriptor = message_descriptor + + def add(self, **kwargs: Any) -> _T: + """Adds a new element at the end of the list and returns it. Keyword + arguments may be used to initialize the element. + """ + new_element = self._message_descriptor._concrete_class(**kwargs) + new_element._SetListener(self._message_listener) + self._values.append(new_element) + if not self._message_listener.dirty: + self._message_listener.Modified() + return new_element + + def append(self, value: _T) -> None: + """Appends one element by copying the message.""" + new_element = self._message_descriptor._concrete_class() + new_element._SetListener(self._message_listener) + new_element.CopyFrom(value) + self._values.append(new_element) + if not self._message_listener.dirty: + self._message_listener.Modified() + + def insert(self, key: int, value: _T) -> None: + """Inserts the item at the specified position by copying.""" + new_element = self._message_descriptor._concrete_class() + new_element._SetListener(self._message_listener) + new_element.CopyFrom(value) + self._values.insert(key, new_element) + if not self._message_listener.dirty: + self._message_listener.Modified() + + def extend(self, elem_seq: Iterable[_T]) -> None: + """Extends by appending the given sequence of elements of the same type + + as this one, copying each individual message. + """ + message_class = self._message_descriptor._concrete_class + listener = self._message_listener + values = self._values + for message in elem_seq: + new_element = message_class() + new_element._SetListener(listener) + new_element.MergeFrom(message) + values.append(new_element) + listener.Modified() + + def MergeFrom( + self, + other: Union['RepeatedCompositeFieldContainer[_T]', Iterable[_T]], + ) -> None: + """Appends the contents of another repeated field of the same type to this + one, copying each individual message. + """ + self.extend(other) + + def remove(self, elem: _T) -> None: + """Removes an item from the list. Similar to list.remove().""" + self._values.remove(elem) + self._message_listener.Modified() + + def pop(self, key: Optional[int] = -1) -> _T: + """Removes and returns an item at a given index. Similar to list.pop().""" + value = self._values[key] + self.__delitem__(key) + return value + + @overload + def __setitem__(self, key: int, value: _T) -> None: + ... + + @overload + def __setitem__(self, key: slice, value: Iterable[_T]) -> None: + ... + + def __setitem__(self, key, value): + # This method is implemented to make RepeatedCompositeFieldContainer + # structurally compatible with typing.MutableSequence. It is + # otherwise unsupported and will always raise an error. + raise TypeError( + f'{self.__class__.__name__} object does not support item assignment') + + def __delitem__(self, key: Union[int, slice]) -> None: + """Deletes the item at the specified position.""" + del self._values[key] + self._message_listener.Modified() + + def __eq__(self, other: Any) -> bool: + """Compares the current instance with another one.""" + if self is other: + return True + if not isinstance(other, self.__class__): + raise TypeError('Can only compare repeated composite fields against ' + 'other repeated composite fields.') + return self._values == other._values + + +class ScalarMap(MutableMapping[_K, _V]): + """Simple, type-checked, dict-like container for holding repeated scalars.""" + + # Disallows assignment to other attributes. + __slots__ = ['_key_checker', '_value_checker', '_values', '_message_listener', + '_entry_descriptor'] + + def __init__( + self, + message_listener: Any, + key_checker: Any, + value_checker: Any, + entry_descriptor: Any, + ) -> None: + """ + Args: + message_listener: A MessageListener implementation. + The ScalarMap will call this object's Modified() method when it + is modified. + key_checker: A type_checkers.ValueChecker instance to run on keys + inserted into this container. + value_checker: A type_checkers.ValueChecker instance to run on values + inserted into this container. + entry_descriptor: The MessageDescriptor of a map entry: key and value. + """ + self._message_listener = message_listener + self._key_checker = key_checker + self._value_checker = value_checker + self._entry_descriptor = entry_descriptor + self._values = {} + + def __getitem__(self, key: _K) -> _V: + try: + return self._values[key] + except KeyError: + key = self._key_checker.CheckValue(key) + val = self._value_checker.DefaultValue() + self._values[key] = val + return val + + def __contains__(self, item: _K) -> bool: + # We check the key's type to match the strong-typing flavor of the API. + # Also this makes it easier to match the behavior of the C++ implementation. + self._key_checker.CheckValue(item) + return item in self._values + + @overload + def get(self, key: _K) -> Optional[_V]: + ... + + @overload + def get(self, key: _K, default: _T) -> Union[_V, _T]: + ... + + # We need to override this explicitly, because our defaultdict-like behavior + # will make the default implementation (from our base class) always insert + # the key. + def get(self, key, default=None): + if key in self: + return self[key] + else: + return default + + def __setitem__(self, key: _K, value: _V) -> _T: + checked_key = self._key_checker.CheckValue(key) + checked_value = self._value_checker.CheckValue(value) + self._values[checked_key] = checked_value + self._message_listener.Modified() + + def __delitem__(self, key: _K) -> None: + del self._values[key] + self._message_listener.Modified() + + def __len__(self) -> int: + return len(self._values) + + def __iter__(self) -> Iterator[_K]: + return iter(self._values) + + def __repr__(self) -> str: + return repr(self._values) + + def setdefault(self, key: _K, value: Optional[_V] = None) -> _V: + if value == None: + raise ValueError('The value for scalar map setdefault must be set.') + if key not in self._values: + self.__setitem__(key, value) + return self[key] + + def MergeFrom(self, other: 'ScalarMap[_K, _V]') -> None: + self._values.update(other._values) + self._message_listener.Modified() + + def InvalidateIterators(self) -> None: + # It appears that the only way to reliably invalidate iterators to + # self._values is to ensure that its size changes. + original = self._values + self._values = original.copy() + original[None] = None + + # This is defined in the abstract base, but we can do it much more cheaply. + def clear(self) -> None: + self._values.clear() + self._message_listener.Modified() + + def GetEntryClass(self) -> Any: + return self._entry_descriptor._concrete_class + + +class MessageMap(MutableMapping[_K, _V]): + """Simple, type-checked, dict-like container for with submessage values.""" + + # Disallows assignment to other attributes. + __slots__ = ['_key_checker', '_values', '_message_listener', + '_message_descriptor', '_entry_descriptor'] + + def __init__( + self, + message_listener: Any, + message_descriptor: Any, + key_checker: Any, + entry_descriptor: Any, + ) -> None: + """ + Args: + message_listener: A MessageListener implementation. + The ScalarMap will call this object's Modified() method when it + is modified. + key_checker: A type_checkers.ValueChecker instance to run on keys + inserted into this container. + value_checker: A type_checkers.ValueChecker instance to run on values + inserted into this container. + entry_descriptor: The MessageDescriptor of a map entry: key and value. + """ + self._message_listener = message_listener + self._message_descriptor = message_descriptor + self._key_checker = key_checker + self._entry_descriptor = entry_descriptor + self._values = {} + + def __getitem__(self, key: _K) -> _V: + key = self._key_checker.CheckValue(key) + try: + return self._values[key] + except KeyError: + new_element = self._message_descriptor._concrete_class() + new_element._SetListener(self._message_listener) + self._values[key] = new_element + self._message_listener.Modified() + return new_element + + def get_or_create(self, key: _K) -> _V: + """get_or_create() is an alias for getitem (ie. map[key]). + + Args: + key: The key to get or create in the map. + + This is useful in cases where you want to be explicit that the call is + mutating the map. This can avoid lint errors for statements like this + that otherwise would appear to be pointless statements: + + msg.my_map[key] + """ + return self[key] + + @overload + def get(self, key: _K) -> Optional[_V]: + ... + + @overload + def get(self, key: _K, default: _T) -> Union[_V, _T]: + ... + + # We need to override this explicitly, because our defaultdict-like behavior + # will make the default implementation (from our base class) always insert + # the key. + def get(self, key, default=None): + if key in self: + return self[key] + else: + return default + + def __contains__(self, item: _K) -> bool: + item = self._key_checker.CheckValue(item) + return item in self._values + + def __setitem__(self, key: _K, value: _V) -> NoReturn: + raise ValueError('May not set values directly, call my_map[key].foo = 5') + + def __delitem__(self, key: _K) -> None: + key = self._key_checker.CheckValue(key) + del self._values[key] + self._message_listener.Modified() + + def __len__(self) -> int: + return len(self._values) + + def __iter__(self) -> Iterator[_K]: + return iter(self._values) + + def __repr__(self) -> str: + return repr(self._values) + + def setdefault(self, key: _K, value: Optional[_V] = None) -> _V: + raise NotImplementedError( + 'Set message map value directly is not supported, call' + ' my_map[key].foo = 5' + ) + + def MergeFrom(self, other: 'MessageMap[_K, _V]') -> None: + # pylint: disable=protected-access + for key in other._values: + # According to documentation: "When parsing from the wire or when merging, + # if there are duplicate map keys the last key seen is used". + if key in self: + del self[key] + self[key].CopyFrom(other[key]) + # self._message_listener.Modified() not required here, because + # mutations to submessages already propagate. + + def InvalidateIterators(self) -> None: + # It appears that the only way to reliably invalidate iterators to + # self._values is to ensure that its size changes. + original = self._values + self._values = original.copy() + original[None] = None + + # This is defined in the abstract base, but we can do it much more cheaply. + def clear(self) -> None: + self._values.clear() + self._message_listener.Modified() + + def GetEntryClass(self) -> Any: + return self._entry_descriptor._concrete_class + + +class _UnknownField: + """A parsed unknown field.""" + + # Disallows assignment to other attributes. + __slots__ = ['_field_number', '_wire_type', '_data'] + + def __init__(self, field_number, wire_type, data): + self._field_number = field_number + self._wire_type = wire_type + self._data = data + return + + def __lt__(self, other): + # pylint: disable=protected-access + return self._field_number < other._field_number + + def __eq__(self, other): + if self is other: + return True + # pylint: disable=protected-access + return (self._field_number == other._field_number and + self._wire_type == other._wire_type and + self._data == other._data) + + +class UnknownFieldRef: # pylint: disable=missing-class-docstring + + def __init__(self, parent, index): + self._parent = parent + self._index = index + + def _check_valid(self): + if not self._parent: + raise ValueError('UnknownField does not exist. ' + 'The parent message might be cleared.') + if self._index >= len(self._parent): + raise ValueError('UnknownField does not exist. ' + 'The parent message might be cleared.') + + @property + def field_number(self): + self._check_valid() + # pylint: disable=protected-access + return self._parent._internal_get(self._index)._field_number + + @property + def wire_type(self): + self._check_valid() + # pylint: disable=protected-access + return self._parent._internal_get(self._index)._wire_type + + @property + def data(self): + self._check_valid() + # pylint: disable=protected-access + return self._parent._internal_get(self._index)._data + + +class UnknownFieldSet: + """UnknownField container""" + + # Disallows assignment to other attributes. + __slots__ = ['_values'] + + def __init__(self): + self._values = [] + + def __getitem__(self, index): + if self._values is None: + raise ValueError('UnknownFields does not exist. ' + 'The parent message might be cleared.') + size = len(self._values) + if index < 0: + index += size + if index < 0 or index >= size: + raise IndexError('index %d out of range'.index) + + return UnknownFieldRef(self, index) + + def _internal_get(self, index): + return self._values[index] + + def __len__(self): + if self._values is None: + raise ValueError('UnknownFields does not exist. ' + 'The parent message might be cleared.') + return len(self._values) + + def _add(self, field_number, wire_type, data): + unknown_field = _UnknownField(field_number, wire_type, data) + self._values.append(unknown_field) + return unknown_field + + def __iter__(self): + for i in range(len(self)): + yield UnknownFieldRef(self, i) + + def _extend(self, other): + if other is None: + return + # pylint: disable=protected-access + self._values.extend(other._values) + + def __eq__(self, other): + if self is other: + return True + # Sort unknown fields because their order shouldn't + # affect equality test. + values = list(self._values) + if other is None: + return not values + values.sort() + # pylint: disable=protected-access + other_values = sorted(other._values) + return values == other_values + + def _clear(self): + for value in self._values: + # pylint: disable=protected-access + if isinstance(value._data, UnknownFieldSet): + value._data._clear() # pylint: disable=protected-access + self._values = None diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/decoder.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..dbf848bf31083d0c4dfbc32fed58e701049f6ede --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/decoder.py @@ -0,0 +1,1066 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""Code for decoding protocol buffer primitives. + +This code is very similar to encoder.py -- read the docs for that module first. + +A "decoder" is a function with the signature: + Decode(buffer, pos, end, message, field_dict) +The arguments are: + buffer: The string containing the encoded message. + pos: The current position in the string. + end: The position in the string where the current message ends. May be + less than len(buffer) if we're reading a sub-message. + message: The message object into which we're parsing. + field_dict: message._fields (avoids a hashtable lookup). +The decoder reads the field and stores it into field_dict, returning the new +buffer position. A decoder for a repeated field may proactively decode all of +the elements of that field, if they appear consecutively. + +Note that decoders may throw any of the following: + IndexError: Indicates a truncated message. + struct.error: Unpacking of a fixed-width field failed. + message.DecodeError: Other errors. + +Decoders are expected to raise an exception if they are called with pos > end. +This allows callers to be lax about bounds checking: it's fineto read past +"end" as long as you are sure that someone else will notice and throw an +exception later on. + +Something up the call stack is expected to catch IndexError and struct.error +and convert them to message.DecodeError. + +Decoders are constructed using decoder constructors with the signature: + MakeDecoder(field_number, is_repeated, is_packed, key, new_default) +The arguments are: + field_number: The field number of the field we want to decode. + is_repeated: Is the field a repeated field? (bool) + is_packed: Is the field a packed field? (bool) + key: The key to use when looking up the field within field_dict. + (This is actually the FieldDescriptor but nothing in this + file should depend on that.) + new_default: A function which takes a message object as a parameter and + returns a new instance of the default value for this field. + (This is called for repeated fields and sub-messages, when an + instance does not already exist.) + +As with encoders, we define a decoder constructor for every type of field. +Then, for every field of every message class we construct an actual decoder. +That decoder goes into a dict indexed by tag, so when we decode a message +we repeatedly read a tag, look up the corresponding decoder, and invoke it. +""" + +__author__ = 'kenton@google.com (Kenton Varda)' + +import math +import numbers +import struct + +from google.protobuf import message +from google.protobuf.internal import containers +from google.protobuf.internal import encoder +from google.protobuf.internal import wire_format + + +# This is not for optimization, but rather to avoid conflicts with local +# variables named "message". +_DecodeError = message.DecodeError + + +def IsDefaultScalarValue(value): + """Returns whether or not a scalar value is the default value of its type. + + Specifically, this should be used to determine presence of implicit-presence + fields, where we disallow custom defaults. + + Args: + value: A scalar value to check. + + Returns: + True if the value is equivalent to a default value, False otherwise. + """ + if isinstance(value, numbers.Number) and math.copysign(1.0, value) < 0: + # Special case for negative zero, where "truthiness" fails to give the right + # answer. + return False + + # Normally, we can just use Python's boolean conversion. + return not value + + +def _VarintDecoder(mask, result_type): + """Return an encoder for a basic varint value (does not include tag). + + Decoded values will be bitwise-anded with the given mask before being + returned, e.g. to limit them to 32 bits. The returned decoder does not + take the usual "end" parameter -- the caller is expected to do bounds checking + after the fact (often the caller can defer such checking until later). The + decoder returns a (value, new_pos) pair. + """ + + def DecodeVarint(buffer, pos: int=None): + result = 0 + shift = 0 + while 1: + if pos is None: + # Read from BytesIO + try: + b = buffer.read(1)[0] + except IndexError as e: + if shift == 0: + # End of BytesIO. + return None + else: + raise ValueError('Fail to read varint %s' % str(e)) + else: + b = buffer[pos] + pos += 1 + result |= ((b & 0x7f) << shift) + if not (b & 0x80): + result &= mask + result = result_type(result) + return result if pos is None else (result, pos) + shift += 7 + if shift >= 64: + raise _DecodeError('Too many bytes when decoding varint.') + + return DecodeVarint + + +def _SignedVarintDecoder(bits, result_type): + """Like _VarintDecoder() but decodes signed values.""" + + signbit = 1 << (bits - 1) + mask = (1 << bits) - 1 + + def DecodeVarint(buffer, pos): + result = 0 + shift = 0 + while 1: + b = buffer[pos] + result |= ((b & 0x7f) << shift) + pos += 1 + if not (b & 0x80): + result &= mask + result = (result ^ signbit) - signbit + result = result_type(result) + return (result, pos) + shift += 7 + if shift >= 64: + raise _DecodeError('Too many bytes when decoding varint.') + return DecodeVarint + +# All 32-bit and 64-bit values are represented as int. +_DecodeVarint = _VarintDecoder((1 << 64) - 1, int) +_DecodeSignedVarint = _SignedVarintDecoder(64, int) + +# Use these versions for values which must be limited to 32 bits. +_DecodeVarint32 = _VarintDecoder((1 << 32) - 1, int) +_DecodeSignedVarint32 = _SignedVarintDecoder(32, int) + + +def ReadTag(buffer, pos): + """Read a tag from the memoryview, and return a (tag_bytes, new_pos) tuple. + + We return the raw bytes of the tag rather than decoding them. The raw + bytes can then be used to look up the proper decoder. This effectively allows + us to trade some work that would be done in pure-python (decoding a varint) + for work that is done in C (searching for a byte string in a hash table). + In a low-level language it would be much cheaper to decode the varint and + use that, but not in Python. + + Args: + buffer: memoryview object of the encoded bytes + pos: int of the current position to start from + + Returns: + Tuple[bytes, int] of the tag data and new position. + """ + start = pos + while buffer[pos] & 0x80: + pos += 1 + pos += 1 + + tag_bytes = buffer[start:pos].tobytes() + return tag_bytes, pos + + +def DecodeTag(tag_bytes): + """Decode a tag from the bytes. + + Args: + tag_bytes: the bytes of the tag + + Returns: + Tuple[int, int] of the tag field number and wire type. + """ + (tag, _) = _DecodeVarint(tag_bytes, 0) + return wire_format.UnpackTag(tag) + + +# -------------------------------------------------------------------- + + +def _SimpleDecoder(wire_type, decode_value): + """Return a constructor for a decoder for fields of a particular type. + + Args: + wire_type: The field's wire type. + decode_value: A function which decodes an individual value, e.g. + _DecodeVarint() + """ + + def SpecificDecoder(field_number, is_repeated, is_packed, key, new_default, + clear_if_default=False): + if is_packed: + local_DecodeVarint = _DecodeVarint + def DecodePackedField( + buffer, pos, end, message, field_dict, current_depth=0 + ): + del current_depth # unused + value = field_dict.get(key) + if value is None: + value = field_dict.setdefault(key, new_default(message)) + (endpoint, pos) = local_DecodeVarint(buffer, pos) + endpoint += pos + if endpoint > end: + raise _DecodeError('Truncated message.') + while pos < endpoint: + (element, pos) = decode_value(buffer, pos) + value.append(element) + if pos > endpoint: + del value[-1] # Discard corrupt value. + raise _DecodeError('Packed element was truncated.') + return pos + + return DecodePackedField + elif is_repeated: + tag_bytes = encoder.TagBytes(field_number, wire_type) + tag_len = len(tag_bytes) + def DecodeRepeatedField( + buffer, pos, end, message, field_dict, current_depth=0 + ): + del current_depth # unused + value = field_dict.get(key) + if value is None: + value = field_dict.setdefault(key, new_default(message)) + while 1: + (element, new_pos) = decode_value(buffer, pos) + value.append(element) + # Predict that the next tag is another copy of the same repeated + # field. + pos = new_pos + tag_len + if buffer[new_pos:pos] != tag_bytes or new_pos >= end: + # Prediction failed. Return. + if new_pos > end: + raise _DecodeError('Truncated message.') + return new_pos + + return DecodeRepeatedField + else: + + def DecodeField(buffer, pos, end, message, field_dict, current_depth=0): + del current_depth # unused + (new_value, pos) = decode_value(buffer, pos) + if pos > end: + raise _DecodeError('Truncated message.') + if clear_if_default and IsDefaultScalarValue(new_value): + field_dict.pop(key, None) + else: + field_dict[key] = new_value + return pos + + return DecodeField + + return SpecificDecoder + + +def _ModifiedDecoder(wire_type, decode_value, modify_value): + """Like SimpleDecoder but additionally invokes modify_value on every value + before storing it. Usually modify_value is ZigZagDecode. + """ + + # Reusing _SimpleDecoder is slightly slower than copying a bunch of code, but + # not enough to make a significant difference. + + def InnerDecode(buffer, pos): + (result, new_pos) = decode_value(buffer, pos) + return (modify_value(result), new_pos) + return _SimpleDecoder(wire_type, InnerDecode) + + +def _StructPackDecoder(wire_type, format): + """Return a constructor for a decoder for a fixed-width field. + + Args: + wire_type: The field's wire type. + format: The format string to pass to struct.unpack(). + """ + + value_size = struct.calcsize(format) + local_unpack = struct.unpack + + # Reusing _SimpleDecoder is slightly slower than copying a bunch of code, but + # not enough to make a significant difference. + + # Note that we expect someone up-stack to catch struct.error and convert + # it to _DecodeError -- this way we don't have to set up exception- + # handling blocks every time we parse one value. + + def InnerDecode(buffer, pos): + new_pos = pos + value_size + result = local_unpack(format, buffer[pos:new_pos])[0] + return (result, new_pos) + return _SimpleDecoder(wire_type, InnerDecode) + + +def _FloatDecoder(): + """Returns a decoder for a float field. + + This code works around a bug in struct.unpack for non-finite 32-bit + floating-point values. + """ + + local_unpack = struct.unpack + + def InnerDecode(buffer, pos): + """Decode serialized float to a float and new position. + + Args: + buffer: memoryview of the serialized bytes + pos: int, position in the memory view to start at. + + Returns: + Tuple[float, int] of the deserialized float value and new position + in the serialized data. + """ + # We expect a 32-bit value in little-endian byte order. Bit 1 is the sign + # bit, bits 2-9 represent the exponent, and bits 10-32 are the significand. + new_pos = pos + 4 + float_bytes = buffer[pos:new_pos].tobytes() + + # If this value has all its exponent bits set, then it's non-finite. + # In Python 2.4, struct.unpack will convert it to a finite 64-bit value. + # To avoid that, we parse it specially. + if (float_bytes[3:4] in b'\x7F\xFF' and float_bytes[2:3] >= b'\x80'): + # If at least one significand bit is set... + if float_bytes[0:3] != b'\x00\x00\x80': + return (math.nan, new_pos) + # If sign bit is set... + if float_bytes[3:4] == b'\xFF': + return (-math.inf, new_pos) + return (math.inf, new_pos) + + # Note that we expect someone up-stack to catch struct.error and convert + # it to _DecodeError -- this way we don't have to set up exception- + # handling blocks every time we parse one value. + result = local_unpack('= b'\xF0') + and (double_bytes[0:7] != b'\x00\x00\x00\x00\x00\x00\xF0')): + return (math.nan, new_pos) + + # Note that we expect someone up-stack to catch struct.error and convert + # it to _DecodeError -- this way we don't have to set up exception- + # handling blocks every time we parse one value. + result = local_unpack(' end: + raise _DecodeError('Truncated message.') + while pos < endpoint: + value_start_pos = pos + (element, pos) = _DecodeSignedVarint32(buffer, pos) + # pylint: disable=protected-access + if element in enum_type.values_by_number: + value.append(element) + else: + if not message._unknown_fields: + message._unknown_fields = [] + tag_bytes = encoder.TagBytes(field_number, + wire_format.WIRETYPE_VARINT) + + message._unknown_fields.append( + (tag_bytes, buffer[value_start_pos:pos].tobytes())) + # pylint: enable=protected-access + if pos > endpoint: + if element in enum_type.values_by_number: + del value[-1] # Discard corrupt value. + else: + del message._unknown_fields[-1] + # pylint: enable=protected-access + raise _DecodeError('Packed element was truncated.') + return pos + + return DecodePackedField + elif is_repeated: + tag_bytes = encoder.TagBytes(field_number, wire_format.WIRETYPE_VARINT) + tag_len = len(tag_bytes) + def DecodeRepeatedField( + buffer, pos, end, message, field_dict, current_depth=0 + ): + """Decode serialized repeated enum to its value and a new position. + + Args: + buffer: memoryview of the serialized bytes. + pos: int, position in the memory view to start at. + end: int, end position of serialized data + message: Message object to store unknown fields in + field_dict: Map[Descriptor, Any] to store decoded values in. + + Returns: + int, new position in serialized data. + """ + del current_depth # unused + value = field_dict.get(key) + if value is None: + value = field_dict.setdefault(key, new_default(message)) + while 1: + (element, new_pos) = _DecodeSignedVarint32(buffer, pos) + # pylint: disable=protected-access + if element in enum_type.values_by_number: + value.append(element) + else: + if not message._unknown_fields: + message._unknown_fields = [] + message._unknown_fields.append( + (tag_bytes, buffer[pos:new_pos].tobytes())) + # pylint: enable=protected-access + # Predict that the next tag is another copy of the same repeated + # field. + pos = new_pos + tag_len + if buffer[new_pos:pos] != tag_bytes or new_pos >= end: + # Prediction failed. Return. + if new_pos > end: + raise _DecodeError('Truncated message.') + return new_pos + + return DecodeRepeatedField + else: + + def DecodeField(buffer, pos, end, message, field_dict, current_depth=0): + """Decode serialized repeated enum to its value and a new position. + + Args: + buffer: memoryview of the serialized bytes. + pos: int, position in the memory view to start at. + end: int, end position of serialized data + message: Message object to store unknown fields in + field_dict: Map[Descriptor, Any] to store decoded values in. + + Returns: + int, new position in serialized data. + """ + del current_depth # unused + value_start_pos = pos + (enum_value, pos) = _DecodeSignedVarint32(buffer, pos) + if pos > end: + raise _DecodeError('Truncated message.') + if clear_if_default and IsDefaultScalarValue(enum_value): + field_dict.pop(key, None) + return pos + # pylint: disable=protected-access + if enum_value in enum_type.values_by_number: + field_dict[key] = enum_value + else: + if not message._unknown_fields: + message._unknown_fields = [] + tag_bytes = encoder.TagBytes(field_number, + wire_format.WIRETYPE_VARINT) + message._unknown_fields.append( + (tag_bytes, buffer[value_start_pos:pos].tobytes())) + # pylint: enable=protected-access + return pos + + return DecodeField + + +# -------------------------------------------------------------------- + + +Int32Decoder = _SimpleDecoder( + wire_format.WIRETYPE_VARINT, _DecodeSignedVarint32) + +Int64Decoder = _SimpleDecoder( + wire_format.WIRETYPE_VARINT, _DecodeSignedVarint) + +UInt32Decoder = _SimpleDecoder(wire_format.WIRETYPE_VARINT, _DecodeVarint32) +UInt64Decoder = _SimpleDecoder(wire_format.WIRETYPE_VARINT, _DecodeVarint) + +SInt32Decoder = _ModifiedDecoder( + wire_format.WIRETYPE_VARINT, _DecodeVarint32, wire_format.ZigZagDecode) +SInt64Decoder = _ModifiedDecoder( + wire_format.WIRETYPE_VARINT, _DecodeVarint, wire_format.ZigZagDecode) + +# Note that Python conveniently guarantees that when using the '<' prefix on +# formats, they will also have the same size across all platforms (as opposed +# to without the prefix, where their sizes depend on the C compiler's basic +# type sizes). +Fixed32Decoder = _StructPackDecoder(wire_format.WIRETYPE_FIXED32, ' end: + raise _DecodeError('Truncated string.') + value.append(_ConvertToUnicode(buffer[pos:new_pos])) + # Predict that the next tag is another copy of the same repeated field. + pos = new_pos + tag_len + if buffer[new_pos:pos] != tag_bytes or new_pos == end: + # Prediction failed. Return. + return new_pos + + return DecodeRepeatedField + else: + + def DecodeField(buffer, pos, end, message, field_dict, current_depth=0): + del current_depth # unused + (size, pos) = local_DecodeVarint(buffer, pos) + new_pos = pos + size + if new_pos > end: + raise _DecodeError('Truncated string.') + if clear_if_default and IsDefaultScalarValue(size): + field_dict.pop(key, None) + else: + field_dict[key] = _ConvertToUnicode(buffer[pos:new_pos]) + return new_pos + + return DecodeField + + +def BytesDecoder(field_number, is_repeated, is_packed, key, new_default, + clear_if_default=False): + """Returns a decoder for a bytes field.""" + + local_DecodeVarint = _DecodeVarint + + assert not is_packed + if is_repeated: + tag_bytes = encoder.TagBytes(field_number, + wire_format.WIRETYPE_LENGTH_DELIMITED) + tag_len = len(tag_bytes) + def DecodeRepeatedField( + buffer, pos, end, message, field_dict, current_depth=0 + ): + del current_depth # unused + value = field_dict.get(key) + if value is None: + value = field_dict.setdefault(key, new_default(message)) + while 1: + (size, pos) = local_DecodeVarint(buffer, pos) + new_pos = pos + size + if new_pos > end: + raise _DecodeError('Truncated string.') + value.append(buffer[pos:new_pos].tobytes()) + # Predict that the next tag is another copy of the same repeated field. + pos = new_pos + tag_len + if buffer[new_pos:pos] != tag_bytes or new_pos == end: + # Prediction failed. Return. + return new_pos + + return DecodeRepeatedField + else: + + def DecodeField(buffer, pos, end, message, field_dict, current_depth=0): + del current_depth # unused + (size, pos) = local_DecodeVarint(buffer, pos) + new_pos = pos + size + if new_pos > end: + raise _DecodeError('Truncated string.') + if clear_if_default and IsDefaultScalarValue(size): + field_dict.pop(key, None) + else: + field_dict[key] = buffer[pos:new_pos].tobytes() + return new_pos + + return DecodeField + + +def GroupDecoder(field_number, is_repeated, is_packed, key, new_default): + """Returns a decoder for a group field.""" + + end_tag_bytes = encoder.TagBytes(field_number, + wire_format.WIRETYPE_END_GROUP) + end_tag_len = len(end_tag_bytes) + + assert not is_packed + if is_repeated: + tag_bytes = encoder.TagBytes(field_number, + wire_format.WIRETYPE_START_GROUP) + tag_len = len(tag_bytes) + def DecodeRepeatedField( + buffer, pos, end, message, field_dict, current_depth=0 + ): + value = field_dict.get(key) + if value is None: + value = field_dict.setdefault(key, new_default(message)) + while 1: + value = field_dict.get(key) + if value is None: + value = field_dict.setdefault(key, new_default(message)) + # Read sub-message. + current_depth += 1 + if current_depth > _recursion_limit: + raise _DecodeError( + 'Error parsing message: too many levels of nesting.' + ) + pos = value.add()._InternalParse(buffer, pos, end, current_depth) + current_depth -= 1 + # Read end tag. + new_pos = pos+end_tag_len + if buffer[pos:new_pos] != end_tag_bytes or new_pos > end: + raise _DecodeError('Missing group end tag.') + # Predict that the next tag is another copy of the same repeated field. + pos = new_pos + tag_len + if buffer[new_pos:pos] != tag_bytes or new_pos == end: + # Prediction failed. Return. + return new_pos + + return DecodeRepeatedField + else: + + def DecodeField(buffer, pos, end, message, field_dict, current_depth=0): + value = field_dict.get(key) + if value is None: + value = field_dict.setdefault(key, new_default(message)) + # Read sub-message. + current_depth += 1 + if current_depth > _recursion_limit: + raise _DecodeError('Error parsing message: too many levels of nesting.') + pos = value._InternalParse(buffer, pos, end, current_depth) + current_depth -= 1 + # Read end tag. + new_pos = pos+end_tag_len + if buffer[pos:new_pos] != end_tag_bytes or new_pos > end: + raise _DecodeError('Missing group end tag.') + return new_pos + + return DecodeField + + +def MessageDecoder(field_number, is_repeated, is_packed, key, new_default): + """Returns a decoder for a message field.""" + + local_DecodeVarint = _DecodeVarint + + assert not is_packed + if is_repeated: + tag_bytes = encoder.TagBytes(field_number, + wire_format.WIRETYPE_LENGTH_DELIMITED) + tag_len = len(tag_bytes) + def DecodeRepeatedField( + buffer, pos, end, message, field_dict, current_depth=0 + ): + value = field_dict.get(key) + if value is None: + value = field_dict.setdefault(key, new_default(message)) + while 1: + # Read length. + (size, pos) = local_DecodeVarint(buffer, pos) + new_pos = pos + size + if new_pos > end: + raise _DecodeError('Truncated message.') + # Read sub-message. + current_depth += 1 + if current_depth > _recursion_limit: + raise _DecodeError( + 'Error parsing message: too many levels of nesting.' + ) + if ( + value.add()._InternalParse(buffer, pos, new_pos, current_depth) + != new_pos + ): + # The only reason _InternalParse would return early is if it + # encountered an end-group tag. + raise _DecodeError('Unexpected end-group tag.') + current_depth -= 1 + # Predict that the next tag is another copy of the same repeated field. + pos = new_pos + tag_len + if buffer[new_pos:pos] != tag_bytes or new_pos == end: + # Prediction failed. Return. + return new_pos + + return DecodeRepeatedField + else: + + def DecodeField(buffer, pos, end, message, field_dict, current_depth=0): + value = field_dict.get(key) + if value is None: + value = field_dict.setdefault(key, new_default(message)) + # Read length. + (size, pos) = local_DecodeVarint(buffer, pos) + new_pos = pos + size + if new_pos > end: + raise _DecodeError('Truncated message.') + # Read sub-message. + current_depth += 1 + if current_depth > _recursion_limit: + raise _DecodeError('Error parsing message: too many levels of nesting.') + if value._InternalParse(buffer, pos, new_pos, current_depth) != new_pos: + # The only reason _InternalParse would return early is if it encountered + # an end-group tag. + raise _DecodeError('Unexpected end-group tag.') + current_depth -= 1 + return new_pos + + return DecodeField + + +# -------------------------------------------------------------------- + +MESSAGE_SET_ITEM_TAG = encoder.TagBytes(1, wire_format.WIRETYPE_START_GROUP) + +def MessageSetItemDecoder(descriptor): + """Returns a decoder for a MessageSet item. + + The parameter is the message Descriptor. + + The message set message looks like this: + message MessageSet { + repeated group Item = 1 { + required int32 type_id = 2; + required string message = 3; + } + } + """ + + type_id_tag_bytes = encoder.TagBytes(2, wire_format.WIRETYPE_VARINT) + message_tag_bytes = encoder.TagBytes(3, wire_format.WIRETYPE_LENGTH_DELIMITED) + item_end_tag_bytes = encoder.TagBytes(1, wire_format.WIRETYPE_END_GROUP) + + local_ReadTag = ReadTag + local_DecodeVarint = _DecodeVarint + + def DecodeItem(buffer, pos, end, message, field_dict): + """Decode serialized message set to its value and new position. + + Args: + buffer: memoryview of the serialized bytes. + pos: int, position in the memory view to start at. + end: int, end position of serialized data + message: Message object to store unknown fields in + field_dict: Map[Descriptor, Any] to store decoded values in. + + Returns: + int, new position in serialized data. + """ + message_set_item_start = pos + type_id = -1 + message_start = -1 + message_end = -1 + + # Technically, type_id and message can appear in any order, so we need + # a little loop here. + while 1: + (tag_bytes, pos) = local_ReadTag(buffer, pos) + if tag_bytes == type_id_tag_bytes: + (type_id, pos) = local_DecodeVarint(buffer, pos) + elif tag_bytes == message_tag_bytes: + (size, message_start) = local_DecodeVarint(buffer, pos) + pos = message_end = message_start + size + elif tag_bytes == item_end_tag_bytes: + break + else: + field_number, wire_type = DecodeTag(tag_bytes) + _, pos = _DecodeUnknownField(buffer, pos, end, field_number, wire_type) + if pos == -1: + raise _DecodeError('Unexpected end-group tag.') + + if pos > end: + raise _DecodeError('Truncated message.') + + if type_id == -1: + raise _DecodeError('MessageSet item missing type_id.') + if message_start == -1: + raise _DecodeError('MessageSet item missing message.') + + extension = message.Extensions._FindExtensionByNumber(type_id) + # pylint: disable=protected-access + if extension is not None: + value = field_dict.get(extension) + if value is None: + message_type = extension.message_type + if not hasattr(message_type, '_concrete_class'): + message_factory.GetMessageClass(message_type) + value = field_dict.setdefault( + extension, message_type._concrete_class()) + if value._InternalParse(buffer, message_start,message_end) != message_end: + # The only reason _InternalParse would return early is if it encountered + # an end-group tag. + raise _DecodeError('Unexpected end-group tag.') + else: + if not message._unknown_fields: + message._unknown_fields = [] + message._unknown_fields.append( + (MESSAGE_SET_ITEM_TAG, buffer[message_set_item_start:pos].tobytes())) + # pylint: enable=protected-access + + return pos + + return DecodeItem + + +def UnknownMessageSetItemDecoder(): + """Returns a decoder for a Unknown MessageSet item.""" + + type_id_tag_bytes = encoder.TagBytes(2, wire_format.WIRETYPE_VARINT) + message_tag_bytes = encoder.TagBytes(3, wire_format.WIRETYPE_LENGTH_DELIMITED) + item_end_tag_bytes = encoder.TagBytes(1, wire_format.WIRETYPE_END_GROUP) + + def DecodeUnknownItem(buffer): + pos = 0 + end = len(buffer) + message_start = -1 + message_end = -1 + while 1: + (tag_bytes, pos) = ReadTag(buffer, pos) + if tag_bytes == type_id_tag_bytes: + (type_id, pos) = _DecodeVarint(buffer, pos) + elif tag_bytes == message_tag_bytes: + (size, message_start) = _DecodeVarint(buffer, pos) + pos = message_end = message_start + size + elif tag_bytes == item_end_tag_bytes: + break + else: + field_number, wire_type = DecodeTag(tag_bytes) + _, pos = _DecodeUnknownField(buffer, pos, end, field_number, wire_type) + if pos == -1: + raise _DecodeError('Unexpected end-group tag.') + + if pos > end: + raise _DecodeError('Truncated message.') + + if type_id == -1: + raise _DecodeError('MessageSet item missing type_id.') + if message_start == -1: + raise _DecodeError('MessageSet item missing message.') + + return (type_id, buffer[message_start:message_end].tobytes()) + + return DecodeUnknownItem + +# -------------------------------------------------------------------- + +def MapDecoder(field_descriptor, new_default, is_message_map): + """Returns a decoder for a map field.""" + + key = field_descriptor + tag_bytes = encoder.TagBytes(field_descriptor.number, + wire_format.WIRETYPE_LENGTH_DELIMITED) + tag_len = len(tag_bytes) + local_DecodeVarint = _DecodeVarint + # Can't read _concrete_class yet; might not be initialized. + message_type = field_descriptor.message_type + + def DecodeMap(buffer, pos, end, message, field_dict, current_depth=0): + del current_depth # Unused. + submsg = message_type._concrete_class() + value = field_dict.get(key) + if value is None: + value = field_dict.setdefault(key, new_default(message)) + while 1: + # Read length. + (size, pos) = local_DecodeVarint(buffer, pos) + new_pos = pos + size + if new_pos > end: + raise _DecodeError('Truncated message.') + # Read sub-message. + submsg.Clear() + if submsg._InternalParse(buffer, pos, new_pos) != new_pos: + # The only reason _InternalParse would return early is if it + # encountered an end-group tag. + raise _DecodeError('Unexpected end-group tag.') + + if is_message_map: + value[submsg.key].CopyFrom(submsg.value) + else: + value[submsg.key] = submsg.value + + # Predict that the next tag is another copy of the same repeated field. + pos = new_pos + tag_len + if buffer[new_pos:pos] != tag_bytes or new_pos == end: + # Prediction failed. Return. + return new_pos + + return DecodeMap + + +def _DecodeFixed64(buffer, pos): + """Decode a fixed64.""" + new_pos = pos + 8 + return (struct.unpack('= _recursion_limit: + raise _DecodeError('Error parsing message: too many levels of nesting.') + data, pos = _DecodeUnknownFieldSet(buffer, pos, end_pos, current_depth) + current_depth -= 1 + # Check end tag. + if buffer[pos - len(end_tag_bytes) : pos] != end_tag_bytes: + raise _DecodeError('Missing group end tag.') + elif wire_type == wire_format.WIRETYPE_END_GROUP: + return (0, -1) + else: + raise _DecodeError('Wrong wire type in tag.') + + if pos > end_pos: + raise _DecodeError('Truncated message.') + + return (data, pos) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/encoder.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..df7bf1b537f6a3d5f1f4e10009f7e23be91382dd --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/encoder.py @@ -0,0 +1,806 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""Code for encoding protocol message primitives. + +Contains the logic for encoding every logical protocol field type +into one of the 5 physical wire types. + +This code is designed to push the Python interpreter's performance to the +limits. + +The basic idea is that at startup time, for every field (i.e. every +FieldDescriptor) we construct two functions: a "sizer" and an "encoder". The +sizer takes a value of this field's type and computes its byte size. The +encoder takes a writer function and a value. It encodes the value into byte +strings and invokes the writer function to write those strings. Typically the +writer function is the write() method of a BytesIO. + +We try to do as much work as possible when constructing the writer and the +sizer rather than when calling them. In particular: +* We copy any needed global functions to local variables, so that we do not need + to do costly global table lookups at runtime. +* Similarly, we try to do any attribute lookups at startup time if possible. +* Every field's tag is encoded to bytes at startup, since it can't change at + runtime. +* Whatever component of the field size we can compute at startup, we do. +* We *avoid* sharing code if doing so would make the code slower and not sharing + does not burden us too much. For example, encoders for repeated fields do + not just call the encoders for singular fields in a loop because this would + add an extra function call overhead for every loop iteration; instead, we + manually inline the single-value encoder into the loop. +* If a Python function lacks a return statement, Python actually generates + instructions to pop the result of the last statement off the stack, push + None onto the stack, and then return that. If we really don't care what + value is returned, then we can save two instructions by returning the + result of the last statement. It looks funny but it helps. +* We assume that type and bounds checking has happened at a higher level. +""" + +__author__ = 'kenton@google.com (Kenton Varda)' + +import struct + +from google.protobuf.internal import wire_format + + +# This will overflow and thus become IEEE-754 "infinity". We would use +# "float('inf')" but it doesn't work on Windows pre-Python-2.6. +_POS_INF = 1e10000 +_NEG_INF = -_POS_INF + + +def _VarintSize(value): + """Compute the size of a varint value.""" + if value <= 0x7f: return 1 + if value <= 0x3fff: return 2 + if value <= 0x1fffff: return 3 + if value <= 0xfffffff: return 4 + if value <= 0x7ffffffff: return 5 + if value <= 0x3ffffffffff: return 6 + if value <= 0x1ffffffffffff: return 7 + if value <= 0xffffffffffffff: return 8 + if value <= 0x7fffffffffffffff: return 9 + return 10 + + +def _SignedVarintSize(value): + """Compute the size of a signed varint value.""" + if value < 0: return 10 + if value <= 0x7f: return 1 + if value <= 0x3fff: return 2 + if value <= 0x1fffff: return 3 + if value <= 0xfffffff: return 4 + if value <= 0x7ffffffff: return 5 + if value <= 0x3ffffffffff: return 6 + if value <= 0x1ffffffffffff: return 7 + if value <= 0xffffffffffffff: return 8 + if value <= 0x7fffffffffffffff: return 9 + return 10 + + +def _TagSize(field_number): + """Returns the number of bytes required to serialize a tag with this field + number.""" + # Just pass in type 0, since the type won't affect the tag+type size. + return _VarintSize(wire_format.PackTag(field_number, 0)) + + +# -------------------------------------------------------------------- +# In this section we define some generic sizers. Each of these functions +# takes parameters specific to a particular field type, e.g. int32 or fixed64. +# It returns another function which in turn takes parameters specific to a +# particular field, e.g. the field number and whether it is repeated or packed. +# Look at the next section to see how these are used. + + +def _SimpleSizer(compute_value_size): + """A sizer which uses the function compute_value_size to compute the size of + each value. Typically compute_value_size is _VarintSize.""" + + def SpecificSizer(field_number, is_repeated, is_packed): + tag_size = _TagSize(field_number) + if is_packed: + local_VarintSize = _VarintSize + def PackedFieldSize(value): + result = 0 + for element in value: + result += compute_value_size(element) + return result + local_VarintSize(result) + tag_size + return PackedFieldSize + elif is_repeated: + def RepeatedFieldSize(value): + result = tag_size * len(value) + for element in value: + result += compute_value_size(element) + return result + return RepeatedFieldSize + else: + def FieldSize(value): + return tag_size + compute_value_size(value) + return FieldSize + + return SpecificSizer + + +def _ModifiedSizer(compute_value_size, modify_value): + """Like SimpleSizer, but modify_value is invoked on each value before it is + passed to compute_value_size. modify_value is typically ZigZagEncode.""" + + def SpecificSizer(field_number, is_repeated, is_packed): + tag_size = _TagSize(field_number) + if is_packed: + local_VarintSize = _VarintSize + def PackedFieldSize(value): + result = 0 + for element in value: + result += compute_value_size(modify_value(element)) + return result + local_VarintSize(result) + tag_size + return PackedFieldSize + elif is_repeated: + def RepeatedFieldSize(value): + result = tag_size * len(value) + for element in value: + result += compute_value_size(modify_value(element)) + return result + return RepeatedFieldSize + else: + def FieldSize(value): + return tag_size + compute_value_size(modify_value(value)) + return FieldSize + + return SpecificSizer + + +def _FixedSizer(value_size): + """Like _SimpleSizer except for a fixed-size field. The input is the size + of one value.""" + + def SpecificSizer(field_number, is_repeated, is_packed): + tag_size = _TagSize(field_number) + if is_packed: + local_VarintSize = _VarintSize + def PackedFieldSize(value): + result = len(value) * value_size + return result + local_VarintSize(result) + tag_size + return PackedFieldSize + elif is_repeated: + element_size = value_size + tag_size + def RepeatedFieldSize(value): + return len(value) * element_size + return RepeatedFieldSize + else: + field_size = value_size + tag_size + def FieldSize(value): + return field_size + return FieldSize + + return SpecificSizer + + +# ==================================================================== +# Here we declare a sizer constructor for each field type. Each "sizer +# constructor" is a function that takes (field_number, is_repeated, is_packed) +# as parameters and returns a sizer, which in turn takes a field value as +# a parameter and returns its encoded size. + + +Int32Sizer = Int64Sizer = EnumSizer = _SimpleSizer(_SignedVarintSize) + +UInt32Sizer = UInt64Sizer = _SimpleSizer(_VarintSize) + +SInt32Sizer = SInt64Sizer = _ModifiedSizer( + _SignedVarintSize, wire_format.ZigZagEncode) + +Fixed32Sizer = SFixed32Sizer = FloatSizer = _FixedSizer(4) +Fixed64Sizer = SFixed64Sizer = DoubleSizer = _FixedSizer(8) + +BoolSizer = _FixedSizer(1) + + +def StringSizer(field_number, is_repeated, is_packed): + """Returns a sizer for a string field.""" + + tag_size = _TagSize(field_number) + local_VarintSize = _VarintSize + local_len = len + assert not is_packed + if is_repeated: + def RepeatedFieldSize(value): + result = tag_size * len(value) + for element in value: + l = local_len(element.encode('utf-8')) + result += local_VarintSize(l) + l + return result + return RepeatedFieldSize + else: + def FieldSize(value): + l = local_len(value.encode('utf-8')) + return tag_size + local_VarintSize(l) + l + return FieldSize + + +def BytesSizer(field_number, is_repeated, is_packed): + """Returns a sizer for a bytes field.""" + + tag_size = _TagSize(field_number) + local_VarintSize = _VarintSize + local_len = len + assert not is_packed + if is_repeated: + def RepeatedFieldSize(value): + result = tag_size * len(value) + for element in value: + l = local_len(element) + result += local_VarintSize(l) + l + return result + return RepeatedFieldSize + else: + def FieldSize(value): + l = local_len(value) + return tag_size + local_VarintSize(l) + l + return FieldSize + + +def GroupSizer(field_number, is_repeated, is_packed): + """Returns a sizer for a group field.""" + + tag_size = _TagSize(field_number) * 2 + assert not is_packed + if is_repeated: + def RepeatedFieldSize(value): + result = tag_size * len(value) + for element in value: + result += element.ByteSize() + return result + return RepeatedFieldSize + else: + def FieldSize(value): + return tag_size + value.ByteSize() + return FieldSize + + +def MessageSizer(field_number, is_repeated, is_packed): + """Returns a sizer for a message field.""" + + tag_size = _TagSize(field_number) + local_VarintSize = _VarintSize + assert not is_packed + if is_repeated: + def RepeatedFieldSize(value): + result = tag_size * len(value) + for element in value: + l = element.ByteSize() + result += local_VarintSize(l) + l + return result + return RepeatedFieldSize + else: + def FieldSize(value): + l = value.ByteSize() + return tag_size + local_VarintSize(l) + l + return FieldSize + + +# -------------------------------------------------------------------- +# MessageSet is special: it needs custom logic to compute its size properly. + + +def MessageSetItemSizer(field_number): + """Returns a sizer for extensions of MessageSet. + + The message set message looks like this: + message MessageSet { + repeated group Item = 1 { + required int32 type_id = 2; + required string message = 3; + } + } + """ + static_size = (_TagSize(1) * 2 + _TagSize(2) + _VarintSize(field_number) + + _TagSize(3)) + local_VarintSize = _VarintSize + + def FieldSize(value): + l = value.ByteSize() + return static_size + local_VarintSize(l) + l + + return FieldSize + + +# -------------------------------------------------------------------- +# Map is special: it needs custom logic to compute its size properly. + + +def MapSizer(field_descriptor, is_message_map): + """Returns a sizer for a map field.""" + + # Can't look at field_descriptor.message_type._concrete_class because it may + # not have been initialized yet. + message_type = field_descriptor.message_type + message_sizer = MessageSizer(field_descriptor.number, False, False) + + def FieldSize(map_value): + total = 0 + for key in map_value: + value = map_value[key] + # It's wasteful to create the messages and throw them away one second + # later since we'll do the same for the actual encode. But there's not an + # obvious way to avoid this within the current design without tons of code + # duplication. For message map, value.ByteSize() should be called to + # update the status. + entry_msg = message_type._concrete_class(key=key, value=value) + total += message_sizer(entry_msg) + if is_message_map: + value.ByteSize() + return total + + return FieldSize + +# ==================================================================== +# Encoders! + + +def _VarintEncoder(): + """Return an encoder for a basic varint value (does not include tag).""" + + local_int2byte = struct.Struct('>B').pack + + def EncodeVarint(write, value, unused_deterministic=None): + bits = value & 0x7f + value >>= 7 + while value: + write(local_int2byte(0x80|bits)) + bits = value & 0x7f + value >>= 7 + return write(local_int2byte(bits)) + + return EncodeVarint + + +def _SignedVarintEncoder(): + """Return an encoder for a basic signed varint value (does not include + tag).""" + + local_int2byte = struct.Struct('>B').pack + + def EncodeSignedVarint(write, value, unused_deterministic=None): + if value < 0: + value += (1 << 64) + bits = value & 0x7f + value >>= 7 + while value: + write(local_int2byte(0x80|bits)) + bits = value & 0x7f + value >>= 7 + return write(local_int2byte(bits)) + + return EncodeSignedVarint + + +_EncodeVarint = _VarintEncoder() +_EncodeSignedVarint = _SignedVarintEncoder() + + +def _VarintBytes(value): + """Encode the given integer as a varint and return the bytes. This is only + called at startup time so it doesn't need to be fast.""" + + pieces = [] + _EncodeVarint(pieces.append, value, True) + return b"".join(pieces) + + +def TagBytes(field_number, wire_type): + """Encode the given tag and return the bytes. Only called at startup.""" + + return bytes(_VarintBytes(wire_format.PackTag(field_number, wire_type))) + +# -------------------------------------------------------------------- +# As with sizers (see above), we have a number of common encoder +# implementations. + + +def _SimpleEncoder(wire_type, encode_value, compute_value_size): + """Return a constructor for an encoder for fields of a particular type. + + Args: + wire_type: The field's wire type, for encoding tags. + encode_value: A function which encodes an individual value, e.g. + _EncodeVarint(). + compute_value_size: A function which computes the size of an individual + value, e.g. _VarintSize(). + """ + + def SpecificEncoder(field_number, is_repeated, is_packed): + if is_packed: + tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED) + local_EncodeVarint = _EncodeVarint + def EncodePackedField(write, value, deterministic): + write(tag_bytes) + size = 0 + for element in value: + size += compute_value_size(element) + local_EncodeVarint(write, size, deterministic) + for element in value: + encode_value(write, element, deterministic) + return EncodePackedField + elif is_repeated: + tag_bytes = TagBytes(field_number, wire_type) + def EncodeRepeatedField(write, value, deterministic): + for element in value: + write(tag_bytes) + encode_value(write, element, deterministic) + return EncodeRepeatedField + else: + tag_bytes = TagBytes(field_number, wire_type) + def EncodeField(write, value, deterministic): + write(tag_bytes) + return encode_value(write, value, deterministic) + return EncodeField + + return SpecificEncoder + + +def _ModifiedEncoder(wire_type, encode_value, compute_value_size, modify_value): + """Like SimpleEncoder but additionally invokes modify_value on every value + before passing it to encode_value. Usually modify_value is ZigZagEncode.""" + + def SpecificEncoder(field_number, is_repeated, is_packed): + if is_packed: + tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED) + local_EncodeVarint = _EncodeVarint + def EncodePackedField(write, value, deterministic): + write(tag_bytes) + size = 0 + for element in value: + size += compute_value_size(modify_value(element)) + local_EncodeVarint(write, size, deterministic) + for element in value: + encode_value(write, modify_value(element), deterministic) + return EncodePackedField + elif is_repeated: + tag_bytes = TagBytes(field_number, wire_type) + def EncodeRepeatedField(write, value, deterministic): + for element in value: + write(tag_bytes) + encode_value(write, modify_value(element), deterministic) + return EncodeRepeatedField + else: + tag_bytes = TagBytes(field_number, wire_type) + def EncodeField(write, value, deterministic): + write(tag_bytes) + return encode_value(write, modify_value(value), deterministic) + return EncodeField + + return SpecificEncoder + + +def _StructPackEncoder(wire_type, format): + """Return a constructor for an encoder for a fixed-width field. + + Args: + wire_type: The field's wire type, for encoding tags. + format: The format string to pass to struct.pack(). + """ + + value_size = struct.calcsize(format) + + def SpecificEncoder(field_number, is_repeated, is_packed): + local_struct_pack = struct.pack + if is_packed: + tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED) + local_EncodeVarint = _EncodeVarint + def EncodePackedField(write, value, deterministic): + write(tag_bytes) + local_EncodeVarint(write, len(value) * value_size, deterministic) + for element in value: + write(local_struct_pack(format, element)) + return EncodePackedField + elif is_repeated: + tag_bytes = TagBytes(field_number, wire_type) + def EncodeRepeatedField(write, value, unused_deterministic=None): + for element in value: + write(tag_bytes) + write(local_struct_pack(format, element)) + return EncodeRepeatedField + else: + tag_bytes = TagBytes(field_number, wire_type) + def EncodeField(write, value, unused_deterministic=None): + write(tag_bytes) + return write(local_struct_pack(format, value)) + return EncodeField + + return SpecificEncoder + + +def _FloatingPointEncoder(wire_type, format): + """Return a constructor for an encoder for float fields. + + This is like StructPackEncoder, but catches errors that may be due to + passing non-finite floating-point values to struct.pack, and makes a + second attempt to encode those values. + + Args: + wire_type: The field's wire type, for encoding tags. + format: The format string to pass to struct.pack(). + """ + + value_size = struct.calcsize(format) + if value_size == 4: + def EncodeNonFiniteOrRaise(write, value): + # Remember that the serialized form uses little-endian byte order. + if value == _POS_INF: + write(b'\x00\x00\x80\x7F') + elif value == _NEG_INF: + write(b'\x00\x00\x80\xFF') + elif value != value: # NaN + write(b'\x00\x00\xC0\x7F') + else: + raise + elif value_size == 8: + def EncodeNonFiniteOrRaise(write, value): + if value == _POS_INF: + write(b'\x00\x00\x00\x00\x00\x00\xF0\x7F') + elif value == _NEG_INF: + write(b'\x00\x00\x00\x00\x00\x00\xF0\xFF') + elif value != value: # NaN + write(b'\x00\x00\x00\x00\x00\x00\xF8\x7F') + else: + raise + else: + raise ValueError('Can\'t encode floating-point values that are ' + '%d bytes long (only 4 or 8)' % value_size) + + def SpecificEncoder(field_number, is_repeated, is_packed): + local_struct_pack = struct.pack + if is_packed: + tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED) + local_EncodeVarint = _EncodeVarint + def EncodePackedField(write, value, deterministic): + write(tag_bytes) + local_EncodeVarint(write, len(value) * value_size, deterministic) + for element in value: + # This try/except block is going to be faster than any code that + # we could write to check whether element is finite. + try: + write(local_struct_pack(format, element)) + except SystemError: + EncodeNonFiniteOrRaise(write, element) + return EncodePackedField + elif is_repeated: + tag_bytes = TagBytes(field_number, wire_type) + def EncodeRepeatedField(write, value, unused_deterministic=None): + for element in value: + write(tag_bytes) + try: + write(local_struct_pack(format, element)) + except SystemError: + EncodeNonFiniteOrRaise(write, element) + return EncodeRepeatedField + else: + tag_bytes = TagBytes(field_number, wire_type) + def EncodeField(write, value, unused_deterministic=None): + write(tag_bytes) + try: + write(local_struct_pack(format, value)) + except SystemError: + EncodeNonFiniteOrRaise(write, value) + return EncodeField + + return SpecificEncoder + + +# ==================================================================== +# Here we declare an encoder constructor for each field type. These work +# very similarly to sizer constructors, described earlier. + + +Int32Encoder = Int64Encoder = EnumEncoder = _SimpleEncoder( + wire_format.WIRETYPE_VARINT, _EncodeSignedVarint, _SignedVarintSize) + +UInt32Encoder = UInt64Encoder = _SimpleEncoder( + wire_format.WIRETYPE_VARINT, _EncodeVarint, _VarintSize) + +SInt32Encoder = SInt64Encoder = _ModifiedEncoder( + wire_format.WIRETYPE_VARINT, _EncodeVarint, _VarintSize, + wire_format.ZigZagEncode) + +# Note that Python conveniently guarantees that when using the '<' prefix on +# formats, they will also have the same size across all platforms (as opposed +# to without the prefix, where their sizes depend on the C compiler's basic +# type sizes). +Fixed32Encoder = _StructPackEncoder(wire_format.WIRETYPE_FIXED32, ' str + ValueType = int + + def __init__(self, enum_type): + """Inits EnumTypeWrapper with an EnumDescriptor.""" + self._enum_type = enum_type + self.DESCRIPTOR = enum_type # pylint: disable=invalid-name + + def Name(self, number): # pylint: disable=invalid-name + """Returns a string containing the name of an enum value.""" + try: + return self._enum_type.values_by_number[number].name + except KeyError: + pass # fall out to break exception chaining + + if not isinstance(number, int): + raise TypeError( + 'Enum value for {} must be an int, but got {} {!r}.'.format( + self._enum_type.name, type(number), number)) + else: + # repr here to handle the odd case when you pass in a boolean. + raise ValueError('Enum {} has no name defined for value {!r}'.format( + self._enum_type.name, number)) + + def Value(self, name): # pylint: disable=invalid-name + """Returns the value corresponding to the given enum name.""" + try: + return self._enum_type.values_by_name[name].number + except KeyError: + pass # fall out to break exception chaining + raise ValueError('Enum {} has no value defined for name {!r}'.format( + self._enum_type.name, name)) + + def keys(self): + """Return a list of the string names in the enum. + + Returns: + A list of strs, in the order they were defined in the .proto file. + """ + + return [value_descriptor.name + for value_descriptor in self._enum_type.values] + + def values(self): + """Return a list of the integer values in the enum. + + Returns: + A list of ints, in the order they were defined in the .proto file. + """ + + return [value_descriptor.number + for value_descriptor in self._enum_type.values] + + def items(self): + """Return a list of the (name, value) pairs of the enum. + + Returns: + A list of (str, int) pairs, in the order they were defined + in the .proto file. + """ + return [(value_descriptor.name, value_descriptor.number) + for value_descriptor in self._enum_type.values] + + def __getattr__(self, name): + """Returns the value corresponding to the given enum name.""" + try: + return super( + EnumTypeWrapper, + self).__getattribute__('_enum_type').values_by_name[name].number + except KeyError: + pass # fall out to break exception chaining + raise AttributeError('Enum {} has no value defined for name {!r}'.format( + self._enum_type.name, name)) + + def __or__(self, other): + """Returns the union type of self and other.""" + if sys.version_info >= (3, 10): + return type(self) | other + else: + raise NotImplementedError( + 'You may not use | on EnumTypes (or classes) below python 3.10' + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/extension_dict.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/extension_dict.py new file mode 100644 index 0000000000000000000000000000000000000000..8163ab94b1bd2a1e3a61ff3dc63e608cf315c105 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/extension_dict.py @@ -0,0 +1,194 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""Contains _ExtensionDict class to represent extensions. +""" + +from google.protobuf.internal import type_checkers +from google.protobuf.descriptor import FieldDescriptor + + +def _VerifyExtensionHandle(message, extension_handle): + """Verify that the given extension handle is valid.""" + + if not isinstance(extension_handle, FieldDescriptor): + raise KeyError('HasExtension() expects an extension handle, got: %s' % + extension_handle) + + if not extension_handle.is_extension: + raise KeyError('"%s" is not an extension.' % extension_handle.full_name) + + if not extension_handle.containing_type: + raise KeyError('"%s" is missing a containing_type.' + % extension_handle.full_name) + + if extension_handle.containing_type is not message.DESCRIPTOR: + raise KeyError('Extension "%s" extends message type "%s", but this ' + 'message is of type "%s".' % + (extension_handle.full_name, + extension_handle.containing_type.full_name, + message.DESCRIPTOR.full_name)) + + +# TODO: Unify error handling of "unknown extension" crap. +# TODO: Support iteritems()-style iteration over all +# extensions with the "has" bits turned on? +class _ExtensionDict(object): + + """Dict-like container for Extension fields on proto instances. + + Note that in all cases we expect extension handles to be + FieldDescriptors. + """ + + def __init__(self, extended_message): + """ + Args: + extended_message: Message instance for which we are the Extensions dict. + """ + self._extended_message = extended_message + + def __getitem__(self, extension_handle): + """Returns the current value of the given extension handle.""" + + _VerifyExtensionHandle(self._extended_message, extension_handle) + + result = self._extended_message._fields.get(extension_handle) + if result is not None: + return result + + if extension_handle.is_repeated: + result = extension_handle._default_constructor(self._extended_message) + elif extension_handle.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE: + message_type = extension_handle.message_type + if not hasattr(message_type, '_concrete_class'): + # pylint: disable=g-import-not-at-top + from google.protobuf import message_factory + message_factory.GetMessageClass(message_type) + if not hasattr(extension_handle.message_type, '_concrete_class'): + from google.protobuf import message_factory + message_factory.GetMessageClass(extension_handle.message_type) + result = extension_handle.message_type._concrete_class() + try: + result._SetListener(self._extended_message._listener_for_children) + except ReferenceError: + pass + else: + # Singular scalar -- just return the default without inserting into the + # dict. + return extension_handle.default_value + + # Atomically check if another thread has preempted us and, if not, swap + # in the new object we just created. If someone has preempted us, we + # take that object and discard ours. + # WARNING: We are relying on setdefault() being atomic. This is true + # in CPython but we haven't investigated others. This warning appears + # in several other locations in this file. + result = self._extended_message._fields.setdefault( + extension_handle, result) + + return result + + def __eq__(self, other): + if not isinstance(other, self.__class__): + return False + + my_fields = self._extended_message.ListFields() + other_fields = other._extended_message.ListFields() + + # Get rid of non-extension fields. + my_fields = [field for field in my_fields if field.is_extension] + other_fields = [field for field in other_fields if field.is_extension] + + return my_fields == other_fields + + def __ne__(self, other): + return not self == other + + def __len__(self): + fields = self._extended_message.ListFields() + # Get rid of non-extension fields. + extension_fields = [field for field in fields if field[0].is_extension] + return len(extension_fields) + + def __hash__(self): + raise TypeError('unhashable object') + + # Note that this is only meaningful for non-repeated, scalar extension + # fields. Note also that we may have to call _Modified() when we do + # successfully set a field this way, to set any necessary "has" bits in the + # ancestors of the extended message. + def __setitem__(self, extension_handle, value): + """If extension_handle specifies a non-repeated, scalar extension + field, sets the value of that field. + """ + + _VerifyExtensionHandle(self._extended_message, extension_handle) + + if (extension_handle.is_repeated or + extension_handle.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE): + raise TypeError( + 'Cannot assign to extension "%s" because it is a repeated or ' + 'composite type.' % extension_handle.full_name) + + # It's slightly wasteful to lookup the type checker each time, + # but we expect this to be a vanishingly uncommon case anyway. + type_checker = type_checkers.GetTypeChecker(extension_handle) + # pylint: disable=protected-access + self._extended_message._fields[extension_handle] = ( + type_checker.CheckValue(value)) + self._extended_message._Modified() + + def __delitem__(self, extension_handle): + self._extended_message.ClearExtension(extension_handle) + + def _FindExtensionByName(self, name): + """Tries to find a known extension with the specified name. + + Args: + name: Extension full name. + + Returns: + Extension field descriptor. + """ + descriptor = self._extended_message.DESCRIPTOR + extensions = descriptor.file.pool._extensions_by_name[descriptor] + return extensions.get(name, None) + + def _FindExtensionByNumber(self, number): + """Tries to find a known extension with the field number. + + Args: + number: Extension field number. + + Returns: + Extension field descriptor. + """ + descriptor = self._extended_message.DESCRIPTOR + extensions = descriptor.file.pool._extensions_by_number[descriptor] + return extensions.get(number, None) + + def __iter__(self): + # Return a generator over the populated extension fields + return (f[0] for f in self._extended_message.ListFields() + if f[0].is_extension) + + def __contains__(self, extension_handle): + _VerifyExtensionHandle(self._extended_message, extension_handle) + + if extension_handle not in self._extended_message._fields: + return False + + if extension_handle.is_repeated: + return bool(self._extended_message._fields.get(extension_handle)) + + if extension_handle.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE: + value = self._extended_message._fields.get(extension_handle) + # pylint: disable=protected-access + return value is not None and value._is_present_in_parent + + return True diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/field_mask.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/field_mask.py new file mode 100644 index 0000000000000000000000000000000000000000..0357486e9fd1b5e7dbdb79c59dda33eaa0a452dc --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/field_mask.py @@ -0,0 +1,312 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""Contains FieldMask class.""" + +from google.protobuf.descriptor import FieldDescriptor + + +class FieldMask(object): + """Class for FieldMask message type.""" + + __slots__ = () + + def ToJsonString(self): + """Converts FieldMask to string according to proto3 JSON spec.""" + camelcase_paths = [] + for path in self.paths: + camelcase_paths.append(_SnakeCaseToCamelCase(path)) + return ','.join(camelcase_paths) + + def FromJsonString(self, value): + """Converts string to FieldMask according to proto3 JSON spec.""" + if not isinstance(value, str): + raise ValueError('FieldMask JSON value not a string: {!r}'.format(value)) + self.Clear() + if value: + for path in value.split(','): + self.paths.append(_CamelCaseToSnakeCase(path)) + + def IsValidForDescriptor(self, message_descriptor): + """Checks whether the FieldMask is valid for Message Descriptor.""" + for path in self.paths: + if not _IsValidPath(message_descriptor, path): + return False + return True + + def AllFieldsFromDescriptor(self, message_descriptor): + """Gets all direct fields of Message Descriptor to FieldMask.""" + self.Clear() + for field in message_descriptor.fields: + self.paths.append(field.name) + + def CanonicalFormFromMask(self, mask): + """Converts a FieldMask to the canonical form. + + Removes paths that are covered by another path. For example, + "foo.bar" is covered by "foo" and will be removed if "foo" + is also in the FieldMask. Then sorts all paths in alphabetical order. + + Args: + mask: The original FieldMask to be converted. + """ + tree = _FieldMaskTree(mask) + tree.ToFieldMask(self) + + def Union(self, mask1, mask2): + """Merges mask1 and mask2 into this FieldMask.""" + _CheckFieldMaskMessage(mask1) + _CheckFieldMaskMessage(mask2) + tree = _FieldMaskTree(mask1) + tree.MergeFromFieldMask(mask2) + tree.ToFieldMask(self) + + def Intersect(self, mask1, mask2): + """Intersects mask1 and mask2 into this FieldMask.""" + _CheckFieldMaskMessage(mask1) + _CheckFieldMaskMessage(mask2) + tree = _FieldMaskTree(mask1) + intersection = _FieldMaskTree() + for path in mask2.paths: + tree.IntersectPath(path, intersection) + intersection.ToFieldMask(self) + + def MergeMessage( + self, source, destination, + replace_message_field=False, replace_repeated_field=False): + """Merges fields specified in FieldMask from source to destination. + + Args: + source: Source message. + destination: The destination message to be merged into. + replace_message_field: Replace message field if True. Merge message + field if False. + replace_repeated_field: Replace repeated field if True. Append + elements of repeated field if False. + """ + tree = _FieldMaskTree(self) + tree.MergeMessage( + source, destination, replace_message_field, replace_repeated_field) + + +def _IsValidPath(message_descriptor, path): + """Checks whether the path is valid for Message Descriptor.""" + parts = path.split('.') + last = parts.pop() + for name in parts: + field = message_descriptor.fields_by_name.get(name) + if (field is None or + field.is_repeated or + field.type != FieldDescriptor.TYPE_MESSAGE): + return False + message_descriptor = field.message_type + return last in message_descriptor.fields_by_name + + +def _CheckFieldMaskMessage(message): + """Raises ValueError if message is not a FieldMask.""" + message_descriptor = message.DESCRIPTOR + if (message_descriptor.name != 'FieldMask' or + message_descriptor.file.name != 'google/protobuf/field_mask.proto'): + raise ValueError('Message {0} is not a FieldMask.'.format( + message_descriptor.full_name)) + + +def _SnakeCaseToCamelCase(path_name): + """Converts a path name from snake_case to camelCase.""" + result = [] + after_underscore = False + for c in path_name: + if c.isupper(): + raise ValueError( + 'Fail to print FieldMask to Json string: Path name ' + '{0} must not contain uppercase letters.'.format(path_name)) + if after_underscore: + if c.islower(): + result.append(c.upper()) + after_underscore = False + else: + raise ValueError( + 'Fail to print FieldMask to Json string: The ' + 'character after a "_" must be a lowercase letter ' + 'in path name {0}.'.format(path_name)) + elif c == '_': + after_underscore = True + else: + result += c + + if after_underscore: + raise ValueError('Fail to print FieldMask to Json string: Trailing "_" ' + 'in path name {0}.'.format(path_name)) + return ''.join(result) + + +def _CamelCaseToSnakeCase(path_name): + """Converts a field name from camelCase to snake_case.""" + result = [] + for c in path_name: + if c == '_': + raise ValueError('Fail to parse FieldMask: Path name ' + '{0} must not contain "_"s.'.format(path_name)) + if c.isupper(): + result += '_' + result += c.lower() + else: + result += c + return ''.join(result) + + +class _FieldMaskTree(object): + """Represents a FieldMask in a tree structure. + + For example, given a FieldMask "foo.bar,foo.baz,bar.baz", + the FieldMaskTree will be: + [_root] -+- foo -+- bar + | | + | +- baz + | + +- bar --- baz + In the tree, each leaf node represents a field path. + """ + + __slots__ = ('_root',) + + def __init__(self, field_mask=None): + """Initializes the tree by FieldMask.""" + self._root = {} + if field_mask: + self.MergeFromFieldMask(field_mask) + + def MergeFromFieldMask(self, field_mask): + """Merges a FieldMask to the tree.""" + for path in field_mask.paths: + self.AddPath(path) + + def AddPath(self, path): + """Adds a field path into the tree. + + If the field path to add is a sub-path of an existing field path + in the tree (i.e., a leaf node), it means the tree already matches + the given path so nothing will be added to the tree. If the path + matches an existing non-leaf node in the tree, that non-leaf node + will be turned into a leaf node with all its children removed because + the path matches all the node's children. Otherwise, a new path will + be added. + + Args: + path: The field path to add. + """ + node = self._root + for name in path.split('.'): + if name not in node: + node[name] = {} + elif not node[name]: + # Pre-existing empty node implies we already have this entire tree. + return + node = node[name] + # Remove any sub-trees we might have had. + node.clear() + + def ToFieldMask(self, field_mask): + """Converts the tree to a FieldMask.""" + field_mask.Clear() + _AddFieldPaths(self._root, '', field_mask) + + def IntersectPath(self, path, intersection): + """Calculates the intersection part of a field path with this tree. + + Args: + path: The field path to calculates. + intersection: The out tree to record the intersection part. + """ + node = self._root + for name in path.split('.'): + if name not in node: + return + elif not node[name]: + intersection.AddPath(path) + return + node = node[name] + intersection.AddLeafNodes(path, node) + + def AddLeafNodes(self, prefix, node): + """Adds leaf nodes begin with prefix to this tree.""" + if not node: + self.AddPath(prefix) + for name in node: + child_path = prefix + '.' + name + self.AddLeafNodes(child_path, node[name]) + + def MergeMessage( + self, source, destination, + replace_message, replace_repeated): + """Merge all fields specified by this tree from source to destination.""" + _MergeMessage( + self._root, source, destination, replace_message, replace_repeated) + + +def _StrConvert(value): + """Converts value to str if it is not.""" + # This file is imported by c extension and some methods like ClearField + # requires string for the field name. py2/py3 has different text + # type and may use unicode. + if not isinstance(value, str): + return value.encode('utf-8') + return value + + +def _MergeMessage( + node, source, destination, replace_message, replace_repeated): + """Merge all fields specified by a sub-tree from source to destination.""" + source_descriptor = source.DESCRIPTOR + for name in node: + child = node[name] + field = source_descriptor.fields_by_name[name] + if field is None: + raise ValueError('Error: Can\'t find field {0} in message {1}.'.format( + name, source_descriptor.full_name)) + if child: + # Sub-paths are only allowed for singular message fields. + if (field.is_repeated or + field.cpp_type != FieldDescriptor.CPPTYPE_MESSAGE): + raise ValueError('Error: Field {0} in message {1} is not a singular ' + 'message field and cannot have sub-fields.'.format( + name, source_descriptor.full_name)) + if source.HasField(name): + _MergeMessage( + child, getattr(source, name), getattr(destination, name), + replace_message, replace_repeated) + continue + if field.is_repeated: + if replace_repeated: + destination.ClearField(_StrConvert(name)) + repeated_source = getattr(source, name) + repeated_destination = getattr(destination, name) + repeated_destination.MergeFrom(repeated_source) + else: + if field.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE: + if replace_message: + destination.ClearField(_StrConvert(name)) + if source.HasField(name): + getattr(destination, name).MergeFrom(getattr(source, name)) + elif not field.has_presence or source.HasField(name): + setattr(destination, name, getattr(source, name)) + else: + destination.ClearField(_StrConvert(name)) + + +def _AddFieldPaths(node, prefix, field_mask): + """Adds the field paths descended from node to field_mask.""" + if not node and prefix: + field_mask.paths.append(prefix) + return + for name in sorted(node): + if prefix: + child_path = prefix + '.' + name + else: + child_path = name + _AddFieldPaths(node[name], child_path, field_mask) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/message_listener.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/message_listener.py new file mode 100644 index 0000000000000000000000000000000000000000..ff1c127d549dcd8973fdbe67fda09b9ce3460abe --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/message_listener.py @@ -0,0 +1,55 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""Defines a listener interface for observing certain +state transitions on Message objects. + +Also defines a null implementation of this interface. +""" + +__author__ = 'robinson@google.com (Will Robinson)' + + +class MessageListener(object): + + """Listens for modifications made to a message. Meant to be registered via + Message._SetListener(). + + Attributes: + dirty: If True, then calling Modified() would be a no-op. This can be + used to avoid these calls entirely in the common case. + """ + + def Modified(self): + """Called every time the message is modified in such a way that the parent + message may need to be updated. This currently means either: + (a) The message was modified for the first time, so the parent message + should henceforth mark the message as present. + (b) The message's cached byte size became dirty -- i.e. the message was + modified for the first time after a previous call to ByteSize(). + Therefore the parent should also mark its byte size as dirty. + Note that (a) implies (b), since new objects start out with a client cached + size (zero). However, we document (a) explicitly because it is important. + + Modified() will *only* be called in response to one of these two events -- + not every time the sub-message is modified. + + Note that if the listener's |dirty| attribute is true, then calling + Modified at the moment would be a no-op, so it can be skipped. Performance- + sensitive callers should check this attribute directly before calling since + it will be true most of the time. + """ + + raise NotImplementedError + + +class NullMessageListener(object): + + """No-op MessageListener implementation.""" + + def Modified(self): + pass diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/python_edition_defaults.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/python_edition_defaults.py new file mode 100644 index 0000000000000000000000000000000000000000..97d2be08f3c15464c4b3ea90a080a90b3b25cf31 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/python_edition_defaults.py @@ -0,0 +1,5 @@ +""" +This file contains the serialized FeatureSetDefaults object corresponding to +the Pure Python runtime. This is used for feature resolution under Editions. +""" +_PROTOBUF_INTERNAL_PYTHON_EDITION_DEFAULTS = b"\n\027\030\204\007\"\000*\020\010\001\020\002\030\002 \003(\0010\0028\002@\001\n\027\030\347\007\"\000*\020\010\002\020\001\030\001 \002(\0010\0018\002@\001\n\027\030\350\007\"\014\010\001\020\001\030\001 \002(\0010\001*\0048\002@\001\n\027\030\351\007\"\020\010\001\020\001\030\001 \002(\0010\0018\001@\002*\000 \346\007(\351\007" diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/python_message.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/python_message.py new file mode 100644 index 0000000000000000000000000000000000000000..ba79963dd97d4413cfd735e42301bce98fca29bd --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/python_message.py @@ -0,0 +1,1599 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +# This code is meant to work on Python 2.4 and above only. +# +# TODO: Helpers for verbose, common checks like seeing if a +# descriptor's cpp_type is CPPTYPE_MESSAGE. + +"""Contains a metaclass and helper functions used to create +protocol message classes from Descriptor objects at runtime. + +Recall that a metaclass is the "type" of a class. +(A class is to a metaclass what an instance is to a class.) + +In this case, we use the GeneratedProtocolMessageType metaclass +to inject all the useful functionality into the classes +output by the protocol compiler at compile-time. + +The upshot of all this is that the real implementation +details for ALL pure-Python protocol buffers are *here in +this file*. +""" + +__author__ = 'robinson@google.com (Will Robinson)' + +import datetime +from io import BytesIO +import math +import struct +import sys +import warnings +import weakref + +from google.protobuf import descriptor as descriptor_mod +from google.protobuf import message as message_mod +from google.protobuf import text_format +# We use "as" to avoid name collisions with variables. +from google.protobuf.internal import api_implementation +from google.protobuf.internal import containers +from google.protobuf.internal import decoder +from google.protobuf.internal import encoder +from google.protobuf.internal import enum_type_wrapper +from google.protobuf.internal import extension_dict +from google.protobuf.internal import message_listener as message_listener_mod +from google.protobuf.internal import type_checkers +from google.protobuf.internal import well_known_types +from google.protobuf.internal import wire_format + +_FieldDescriptor = descriptor_mod.FieldDescriptor +_AnyFullTypeName = 'google.protobuf.Any' +_StructFullTypeName = 'google.protobuf.Struct' +_ListValueFullTypeName = 'google.protobuf.ListValue' +_ExtensionDict = extension_dict._ExtensionDict + +class GeneratedProtocolMessageType(type): + + """Metaclass for protocol message classes created at runtime from Descriptors. + + We add implementations for all methods described in the Message class. We + also create properties to allow getting/setting all fields in the protocol + message. Finally, we create slots to prevent users from accidentally + "setting" nonexistent fields in the protocol message, which then wouldn't get + serialized / deserialized properly. + + The protocol compiler currently uses this metaclass to create protocol + message classes at runtime. Clients can also manually create their own + classes at runtime, as in this example: + + mydescriptor = Descriptor(.....) + factory = symbol_database.Default() + factory.pool.AddDescriptor(mydescriptor) + MyProtoClass = message_factory.GetMessageClass(mydescriptor) + myproto_instance = MyProtoClass() + myproto.foo_field = 23 + ... + """ + + # Must be consistent with the protocol-compiler code in + # proto2/compiler/internal/generator.*. + _DESCRIPTOR_KEY = 'DESCRIPTOR' + + def __new__(cls, name, bases, dictionary): + """Custom allocation for runtime-generated class types. + + We override __new__ because this is apparently the only place + where we can meaningfully set __slots__ on the class we're creating(?). + (The interplay between metaclasses and slots is not very well-documented). + + Args: + name: Name of the class (ignored, but required by the + metaclass protocol). + bases: Base classes of the class we're constructing. + (Should be message.Message). We ignore this field, but + it's required by the metaclass protocol + dictionary: The class dictionary of the class we're + constructing. dictionary[_DESCRIPTOR_KEY] must contain + a Descriptor object describing this protocol message + type. + + Returns: + Newly-allocated class. + + Raises: + RuntimeError: Generated code only work with python cpp extension. + """ + descriptor = dictionary[GeneratedProtocolMessageType._DESCRIPTOR_KEY] + + if isinstance(descriptor, str): + raise RuntimeError('The generated code only work with python cpp ' + 'extension, but it is using pure python runtime.') + + # If a concrete class already exists for this descriptor, don't try to + # create another. Doing so will break any messages that already exist with + # the existing class. + # + # The C++ implementation appears to have its own internal `PyMessageFactory` + # to achieve similar results. + # + # This most commonly happens in `text_format.py` when using descriptors from + # a custom pool; it calls message_factory.GetMessageClass() on a + # descriptor which already has an existing concrete class. + new_class = getattr(descriptor, '_concrete_class', None) + if new_class: + return new_class + + if descriptor.full_name in well_known_types.WKTBASES: + bases += (well_known_types.WKTBASES[descriptor.full_name],) + _AddClassAttributesForNestedExtensions(descriptor, dictionary) + _AddSlots(descriptor, dictionary) + + superclass = super(GeneratedProtocolMessageType, cls) + new_class = superclass.__new__(cls, name, bases, dictionary) + return new_class + + def __init__(cls, name, bases, dictionary): + """Here we perform the majority of our work on the class. + We add enum getters, an __init__ method, implementations + of all Message methods, and properties for all fields + in the protocol type. + + Args: + name: Name of the class (ignored, but required by the + metaclass protocol). + bases: Base classes of the class we're constructing. + (Should be message.Message). We ignore this field, but + it's required by the metaclass protocol + dictionary: The class dictionary of the class we're + constructing. dictionary[_DESCRIPTOR_KEY] must contain + a Descriptor object describing this protocol message + type. + """ + descriptor = dictionary[GeneratedProtocolMessageType._DESCRIPTOR_KEY] + + # If this is an _existing_ class looked up via `_concrete_class` in the + # __new__ method above, then we don't need to re-initialize anything. + existing_class = getattr(descriptor, '_concrete_class', None) + if existing_class: + assert existing_class is cls, ( + 'Duplicate `GeneratedProtocolMessageType` created for descriptor %r' + % (descriptor.full_name)) + return + + cls._message_set_decoders_by_tag = {} + cls._fields_by_tag = {} + if (descriptor.has_options and + descriptor.GetOptions().message_set_wire_format): + cls._message_set_decoders_by_tag[decoder.MESSAGE_SET_ITEM_TAG] = ( + decoder.MessageSetItemDecoder(descriptor), + None, + ) + + # Attach stuff to each FieldDescriptor for quick lookup later on. + for field in descriptor.fields: + _AttachFieldHelpers(cls, field) + + if descriptor.is_extendable and hasattr(descriptor.file, 'pool'): + extensions = descriptor.file.pool.FindAllExtensions(descriptor) + for ext in extensions: + _AttachFieldHelpers(cls, ext) + + descriptor._concrete_class = cls # pylint: disable=protected-access + _AddEnumValues(descriptor, cls) + _AddInitMethod(descriptor, cls) + _AddPropertiesForFields(descriptor, cls) + _AddPropertiesForExtensions(descriptor, cls) + _AddStaticMethods(cls) + _AddMessageMethods(descriptor, cls) + _AddPrivateHelperMethods(descriptor, cls) + + superclass = super(GeneratedProtocolMessageType, cls) + superclass.__init__(name, bases, dictionary) + + +# Stateless helpers for GeneratedProtocolMessageType below. +# Outside clients should not access these directly. +# +# I opted not to make any of these methods on the metaclass, to make it more +# clear that I'm not really using any state there and to keep clients from +# thinking that they have direct access to these construction helpers. + + +def _PropertyName(proto_field_name): + """Returns the name of the public property attribute which + clients can use to get and (in some cases) set the value + of a protocol message field. + + Args: + proto_field_name: The protocol message field name, exactly + as it appears (or would appear) in a .proto file. + """ + # TODO: Escape Python keywords (e.g., yield), and test this support. + # nnorwitz makes my day by writing: + # """ + # FYI. See the keyword module in the stdlib. This could be as simple as: + # + # if keyword.iskeyword(proto_field_name): + # return proto_field_name + "_" + # return proto_field_name + # """ + # Kenton says: The above is a BAD IDEA. People rely on being able to use + # getattr() and setattr() to reflectively manipulate field values. If we + # rename the properties, then every such user has to also make sure to apply + # the same transformation. Note that currently if you name a field "yield", + # you can still access it just fine using getattr/setattr -- it's not even + # that cumbersome to do so. + # TODO: Remove this method entirely if/when everyone agrees with my + # position. + return proto_field_name + + +def _AddSlots(message_descriptor, dictionary): + """Adds a __slots__ entry to dictionary, containing the names of all valid + attributes for this message type. + + Args: + message_descriptor: A Descriptor instance describing this message type. + dictionary: Class dictionary to which we'll add a '__slots__' entry. + """ + dictionary['__slots__'] = ['_cached_byte_size', + '_cached_byte_size_dirty', + '_fields', + '_unknown_fields', + '_is_present_in_parent', + '_listener', + '_listener_for_children', + '__weakref__', + '_oneofs'] + + +def _IsMessageSetExtension(field): + return (field.is_extension and + field.containing_type.has_options and + field.containing_type.GetOptions().message_set_wire_format and + field.type == _FieldDescriptor.TYPE_MESSAGE and + not field.is_required and + not field.is_repeated) + + +def _IsMapField(field): + return (field.type == _FieldDescriptor.TYPE_MESSAGE and + field.message_type._is_map_entry) + + +def _IsMessageMapField(field): + value_type = field.message_type.fields_by_name['value'] + return value_type.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE + +def _AttachFieldHelpers(cls, field_descriptor): + field_descriptor._default_constructor = _DefaultValueConstructorForField( + field_descriptor + ) + + def AddFieldByTag(wiretype, is_packed): + tag_bytes = encoder.TagBytes(field_descriptor.number, wiretype) + cls._fields_by_tag[tag_bytes] = (field_descriptor, is_packed) + + AddFieldByTag( + type_checkers.FIELD_TYPE_TO_WIRE_TYPE[field_descriptor.type], False + ) + + if field_descriptor.is_repeated and wire_format.IsTypePackable( + field_descriptor.type + ): + # To support wire compatibility of adding packed = true, add a decoder for + # packed values regardless of the field's options. + AddFieldByTag(wire_format.WIRETYPE_LENGTH_DELIMITED, True) + + +def _MaybeAddEncoder(cls, field_descriptor): + if hasattr(field_descriptor, '_encoder'): + return + is_repeated = field_descriptor.is_repeated + is_map_entry = _IsMapField(field_descriptor) + is_packed = field_descriptor.is_packed + + if is_map_entry: + field_encoder = encoder.MapEncoder(field_descriptor) + sizer = encoder.MapSizer(field_descriptor, + _IsMessageMapField(field_descriptor)) + elif _IsMessageSetExtension(field_descriptor): + field_encoder = encoder.MessageSetItemEncoder(field_descriptor.number) + sizer = encoder.MessageSetItemSizer(field_descriptor.number) + else: + field_encoder = type_checkers.TYPE_TO_ENCODER[field_descriptor.type]( + field_descriptor.number, is_repeated, is_packed) + sizer = type_checkers.TYPE_TO_SIZER[field_descriptor.type]( + field_descriptor.number, is_repeated, is_packed) + + field_descriptor._sizer = sizer + field_descriptor._encoder = field_encoder + + +def _MaybeAddDecoder(cls, field_descriptor): + if hasattr(field_descriptor, '_decoders'): + return + + is_repeated = field_descriptor.is_repeated + is_map_entry = _IsMapField(field_descriptor) + helper_decoders = {} + + def AddDecoder(is_packed): + decode_type = field_descriptor.type + if (decode_type == _FieldDescriptor.TYPE_ENUM and + not field_descriptor.enum_type.is_closed): + decode_type = _FieldDescriptor.TYPE_INT32 + + oneof_descriptor = None + if field_descriptor.containing_oneof is not None: + oneof_descriptor = field_descriptor + + if is_map_entry: + is_message_map = _IsMessageMapField(field_descriptor) + + field_decoder = decoder.MapDecoder( + field_descriptor, _GetInitializeDefaultForMap(field_descriptor), + is_message_map) + elif decode_type == _FieldDescriptor.TYPE_STRING: + field_decoder = decoder.StringDecoder( + field_descriptor.number, is_repeated, is_packed, + field_descriptor, field_descriptor._default_constructor, + not field_descriptor.has_presence) + elif field_descriptor.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + field_decoder = type_checkers.TYPE_TO_DECODER[decode_type]( + field_descriptor.number, is_repeated, is_packed, + field_descriptor, field_descriptor._default_constructor) + else: + field_decoder = type_checkers.TYPE_TO_DECODER[decode_type]( + field_descriptor.number, is_repeated, is_packed, + # pylint: disable=protected-access + field_descriptor, field_descriptor._default_constructor, + not field_descriptor.has_presence) + + helper_decoders[is_packed] = field_decoder + + AddDecoder(False) + + if is_repeated and wire_format.IsTypePackable(field_descriptor.type): + # To support wire compatibility of adding packed = true, add a decoder for + # packed values regardless of the field's options. + AddDecoder(True) + + field_descriptor._decoders = helper_decoders + + +def _AddClassAttributesForNestedExtensions(descriptor, dictionary): + extensions = descriptor.extensions_by_name + for extension_name, extension_field in extensions.items(): + assert extension_name not in dictionary + dictionary[extension_name] = extension_field + + +def _AddEnumValues(descriptor, cls): + """Sets class-level attributes for all enum fields defined in this message. + + Also exporting a class-level object that can name enum values. + + Args: + descriptor: Descriptor object for this message type. + cls: Class we're constructing for this message type. + """ + for enum_type in descriptor.enum_types: + setattr(cls, enum_type.name, enum_type_wrapper.EnumTypeWrapper(enum_type)) + for enum_value in enum_type.values: + setattr(cls, enum_value.name, enum_value.number) + + +def _GetInitializeDefaultForMap(field): + if not field.is_repeated: + raise ValueError('map_entry set on non-repeated field %s' % ( + field.name)) + fields_by_name = field.message_type.fields_by_name + key_checker = type_checkers.GetTypeChecker(fields_by_name['key']) + + value_field = fields_by_name['value'] + if _IsMessageMapField(field): + def MakeMessageMapDefault(message): + return containers.MessageMap( + message._listener_for_children, value_field.message_type, key_checker, + field.message_type) + return MakeMessageMapDefault + else: + value_checker = type_checkers.GetTypeChecker(value_field) + def MakePrimitiveMapDefault(message): + return containers.ScalarMap( + message._listener_for_children, key_checker, value_checker, + field.message_type) + return MakePrimitiveMapDefault + +def _DefaultValueConstructorForField(field): + """Returns a function which returns a default value for a field. + + Args: + field: FieldDescriptor object for this field. + + The returned function has one argument: + message: Message instance containing this field, or a weakref proxy + of same. + + That function in turn returns a default value for this field. The default + value may refer back to |message| via a weak reference. + """ + + if _IsMapField(field): + return _GetInitializeDefaultForMap(field) + + if field.is_repeated: + if field.has_default_value and field.default_value != []: + raise ValueError('Repeated field default value not empty list: %s' % ( + field.default_value)) + if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + # We can't look at _concrete_class yet since it might not have + # been set. (Depends on order in which we initialize the classes). + message_type = field.message_type + def MakeRepeatedMessageDefault(message): + return containers.RepeatedCompositeFieldContainer( + message._listener_for_children, field.message_type) + return MakeRepeatedMessageDefault + else: + type_checker = type_checkers.GetTypeChecker(field) + def MakeRepeatedScalarDefault(message): + return containers.RepeatedScalarFieldContainer( + message._listener_for_children, type_checker) + return MakeRepeatedScalarDefault + + if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + message_type = field.message_type + def MakeSubMessageDefault(message): + # _concrete_class may not yet be initialized. + if not hasattr(message_type, '_concrete_class'): + from google.protobuf import message_factory + message_factory.GetMessageClass(message_type) + result = message_type._concrete_class() + result._SetListener( + _OneofListener(message, field) + if field.containing_oneof is not None + else message._listener_for_children) + return result + return MakeSubMessageDefault + + def MakeScalarDefault(message): + # TODO: This may be broken since there may not be + # default_value. Combine with has_default_value somehow. + return field.default_value + return MakeScalarDefault + + +def _ReraiseTypeErrorWithFieldName(message_name, field_name): + """Re-raise the currently-handled TypeError with the field name added.""" + exc = sys.exc_info()[1] + if len(exc.args) == 1 and type(exc) is TypeError: + # simple TypeError; add field name to exception message + exc = TypeError('%s for field %s.%s' % (str(exc), message_name, field_name)) + + # re-raise possibly-amended exception with original traceback: + raise exc.with_traceback(sys.exc_info()[2]) + + +def _AddInitMethod(message_descriptor, cls): + """Adds an __init__ method to cls.""" + + def _GetIntegerEnumValue(enum_type, value): + """Convert a string or integer enum value to an integer. + + If the value is a string, it is converted to the enum value in + enum_type with the same name. If the value is not a string, it's + returned as-is. (No conversion or bounds-checking is done.) + """ + if isinstance(value, str): + try: + return enum_type.values_by_name[value].number + except KeyError: + raise ValueError('Enum type %s: unknown label "%s"' % ( + enum_type.full_name, value)) + return value + + def init(self, **kwargs): + + def init_wkt_or_merge(field, msg, value): + if isinstance(value, message_mod.Message): + msg.MergeFrom(value) + elif ( + isinstance(value, dict) + and field.message_type.full_name == _StructFullTypeName + ): + msg.Clear() + if len(value) == 1 and 'fields' in value: + try: + msg.update(value) + except: + msg.Clear() + msg.__init__(**value) + else: + msg.update(value) + elif hasattr(msg, '_internal_assign'): + msg._internal_assign(value) + else: + raise TypeError( + 'Message field {0}.{1} must be initialized with a ' + 'dict or instance of same class, got {2}.'.format( + message_descriptor.name, + field.name, + type(value).__name__, + ) + ) + + self._cached_byte_size = 0 + self._cached_byte_size_dirty = len(kwargs) > 0 + self._fields = {} + # Contains a mapping from oneof field descriptors to the descriptor + # of the currently set field in that oneof field. + self._oneofs = {} + + # _unknown_fields is () when empty for efficiency, and will be turned into + # a list if fields are added. + self._unknown_fields = () + self._is_present_in_parent = False + self._listener = message_listener_mod.NullMessageListener() + self._listener_for_children = _Listener(self) + for field_name, field_value in kwargs.items(): + field = _GetFieldByName(message_descriptor, field_name) + if field is None: + raise TypeError('%s() got an unexpected keyword argument "%s"' % + (message_descriptor.name, field_name)) + if field_value is None: + # field=None is the same as no field at all. + continue + if field.is_repeated: + field_copy = field._default_constructor(self) + if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: # Composite + if _IsMapField(field): + if _IsMessageMapField(field): + for key in field_value: + item_value = field_value[key] + if isinstance(item_value, dict): + field_copy[key].__init__(**item_value) + else: + field_copy[key].MergeFrom(item_value) + else: + field_copy.update(field_value) + else: + for val in field_value: + if isinstance(val, dict) and ( + field.message_type.full_name != _StructFullTypeName + ): + field_copy.add(**val) + else: + new_msg = field_copy.add() + init_wkt_or_merge(field, new_msg, val) + else: # Scalar + if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM: + field_value = [_GetIntegerEnumValue(field.enum_type, val) + for val in field_value] + field_copy.extend(field_value) + self._fields[field] = field_copy + elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + field_copy = field._default_constructor(self) + if isinstance(field_value, dict) and ( + field.message_type.full_name != _StructFullTypeName + ): + new_val = field.message_type._concrete_class(**field_value) + field_copy.MergeFrom(new_val) + else: + try: + init_wkt_or_merge(field, field_copy, field_value) + except TypeError: + _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name) + self._fields[field] = field_copy + else: + if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM: + field_value = _GetIntegerEnumValue(field.enum_type, field_value) + try: + setattr(self, field_name, field_value) + except TypeError: + _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name) + + init.__module__ = None + init.__doc__ = None + cls.__init__ = init + + +def _GetFieldByName(message_descriptor, field_name): + """Returns a field descriptor by field name. + + Args: + message_descriptor: A Descriptor describing all fields in message. + field_name: The name of the field to retrieve. + Returns: + The field descriptor associated with the field name. + """ + try: + return message_descriptor.fields_by_name[field_name] + except KeyError: + raise ValueError('Protocol message %s has no "%s" field.' % + (message_descriptor.name, field_name)) + + +def _AddPropertiesForFields(descriptor, cls): + """Adds properties for all fields in this protocol message type.""" + for field in descriptor.fields: + _AddPropertiesForField(field, cls) + + if descriptor.is_extendable: + # _ExtensionDict is just an adaptor with no state so we allocate a new one + # every time it is accessed. + cls.Extensions = property(lambda self: _ExtensionDict(self)) + + +def _AddPropertiesForField(field, cls): + """Adds a public property for a protocol message field. + Clients can use this property to get and (in the case + of non-repeated scalar fields) directly set the value + of a protocol message field. + + Args: + field: A FieldDescriptor for this field. + cls: The class we're constructing. + """ + # Catch it if we add other types that we should + # handle specially here. + assert _FieldDescriptor.MAX_CPPTYPE == 10 + + constant_name = field.name.upper() + '_FIELD_NUMBER' + setattr(cls, constant_name, field.number) + + if field.is_repeated: + _AddPropertiesForRepeatedField(field, cls) + elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + _AddPropertiesForNonRepeatedCompositeField(field, cls) + else: + _AddPropertiesForNonRepeatedScalarField(field, cls) + + +class _FieldProperty(property): + __slots__ = ('DESCRIPTOR',) + + def __init__(self, descriptor, getter, setter, doc): + property.__init__(self, getter, setter, doc=doc) + self.DESCRIPTOR = descriptor + + +def _AddPropertiesForRepeatedField(field, cls): + """Adds a public property for a "repeated" protocol message field. Clients + can use this property to get the value of the field, which will be either a + RepeatedScalarFieldContainer or RepeatedCompositeFieldContainer (see + below). + + Note that when clients add values to these containers, we perform + type-checking in the case of repeated scalar fields, and we also set any + necessary "has" bits as a side-effect. + + Args: + field: A FieldDescriptor for this field. + cls: The class we're constructing. + """ + proto_field_name = field.name + property_name = _PropertyName(proto_field_name) + + def getter(self): + field_value = self._fields.get(field) + if field_value is None: + # Construct a new object to represent this field. + field_value = field._default_constructor(self) + + # Atomically check if another thread has preempted us and, if not, swap + # in the new object we just created. If someone has preempted us, we + # take that object and discard ours. + # WARNING: We are relying on setdefault() being atomic. This is true + # in CPython but we haven't investigated others. This warning appears + # in several other locations in this file. + field_value = self._fields.setdefault(field, field_value) + return field_value + getter.__module__ = None + getter.__doc__ = 'Getter for %s.' % proto_field_name + + # We define a setter just so we can throw an exception with a more + # helpful error message. + def setter(self, new_value): + raise AttributeError('Assignment not allowed to repeated field ' + '"%s" in protocol message object.' % proto_field_name) + + doc = 'Magic attribute generated for "%s" proto field.' % proto_field_name + setattr(cls, property_name, _FieldProperty(field, getter, setter, doc=doc)) + + +def _AddPropertiesForNonRepeatedScalarField(field, cls): + """Adds a public property for a nonrepeated, scalar protocol message field. + Clients can use this property to get and directly set the value of the field. + Note that when the client sets the value of a field by using this property, + all necessary "has" bits are set as a side-effect, and we also perform + type-checking. + + Args: + field: A FieldDescriptor for this field. + cls: The class we're constructing. + """ + proto_field_name = field.name + property_name = _PropertyName(proto_field_name) + type_checker = type_checkers.GetTypeChecker(field) + default_value = field.default_value + + def getter(self): + # TODO: This may be broken since there may not be + # default_value. Combine with has_default_value somehow. + return self._fields.get(field, default_value) + getter.__module__ = None + getter.__doc__ = 'Getter for %s.' % proto_field_name + + def field_setter(self, new_value): + # pylint: disable=protected-access + # Testing the value for truthiness captures all of the implicit presence + # defaults (0, 0.0, enum 0, and False), except for -0.0. + try: + new_value = type_checker.CheckValue(new_value) + except TypeError as e: + raise TypeError( + 'Cannot set %s to %.1024r: %s' % (field.full_name, new_value, e)) + if not field.has_presence and decoder.IsDefaultScalarValue(new_value): + self._fields.pop(field, None) + else: + self._fields[field] = new_value + # Check _cached_byte_size_dirty inline to improve performance, since scalar + # setters are called frequently. + if not self._cached_byte_size_dirty: + self._Modified() + + if field.containing_oneof: + def setter(self, new_value): + field_setter(self, new_value) + self._UpdateOneofState(field) + else: + setter = field_setter + + setter.__module__ = None + setter.__doc__ = 'Setter for %s.' % proto_field_name + + # Add a property to encapsulate the getter/setter. + doc = 'Magic attribute generated for "%s" proto field.' % proto_field_name + setattr(cls, property_name, _FieldProperty(field, getter, setter, doc=doc)) + + +def _AddPropertiesForNonRepeatedCompositeField(field, cls): + """Adds a public property for a nonrepeated, composite protocol message field. + A composite field is a "group" or "message" field. + + Clients can use this property to get the value of the field, but cannot + assign to the property directly. + + Args: + field: A FieldDescriptor for this field. + cls: The class we're constructing. + """ + # TODO: Remove duplication with similar method + # for non-repeated scalars. + proto_field_name = field.name + property_name = _PropertyName(proto_field_name) + + def getter(self): + field_value = self._fields.get(field) + if field_value is None: + # Construct a new object to represent this field. + field_value = field._default_constructor(self) + + # Atomically check if another thread has preempted us and, if not, swap + # in the new object we just created. If someone has preempted us, we + # take that object and discard ours. + # WARNING: We are relying on setdefault() being atomic. This is true + # in CPython but we haven't investigated others. This warning appears + # in several other locations in this file. + field_value = self._fields.setdefault(field, field_value) + return field_value + getter.__module__ = None + getter.__doc__ = 'Getter for %s.' % proto_field_name + + # We define a setter just so we can throw an exception with a more + # helpful error message. + def setter(self, new_value): + if field.message_type.full_name == 'google.protobuf.Timestamp': + getter(self) + self._fields[field].FromDatetime(new_value) + elif field.message_type.full_name == 'google.protobuf.Duration': + getter(self) + self._fields[field].FromTimedelta(new_value) + elif field.message_type.full_name == _StructFullTypeName: + getter(self) + self._fields[field].Clear() + self._fields[field].update(new_value) + elif field.message_type.full_name == _ListValueFullTypeName: + getter(self) + self._fields[field].Clear() + self._fields[field].extend(new_value) + else: + raise AttributeError( + 'Assignment not allowed to composite field ' + '"%s" in protocol message object.' % proto_field_name + ) + + # Add a property to encapsulate the getter. + doc = 'Magic attribute generated for "%s" proto field.' % proto_field_name + setattr(cls, property_name, _FieldProperty(field, getter, setter, doc=doc)) + + +def _AddPropertiesForExtensions(descriptor, cls): + """Adds properties for all fields in this protocol message type.""" + extensions = descriptor.extensions_by_name + for extension_name, extension_field in extensions.items(): + constant_name = extension_name.upper() + '_FIELD_NUMBER' + setattr(cls, constant_name, extension_field.number) + + # TODO: Migrate all users of these attributes to functions like + # pool.FindExtensionByNumber(descriptor). + if descriptor.file is not None: + # TODO: Use cls.MESSAGE_FACTORY.pool when available. + pool = descriptor.file.pool + +def _AddStaticMethods(cls): + + def RegisterExtension(_): + """no-op to keep generated code <=4.23 working with new runtimes.""" + # This was originally removed in 5.26 (cl/595989309). + pass + + cls.RegisterExtension = staticmethod(RegisterExtension) + def FromString(s): + message = cls() + message.MergeFromString(s) + return message + cls.FromString = staticmethod(FromString) + + +def _IsPresent(item): + """Given a (FieldDescriptor, value) tuple from _fields, return true if the + value should be included in the list returned by ListFields().""" + + if item[0].is_repeated: + return bool(item[1]) + elif item[0].cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + return item[1]._is_present_in_parent + else: + return True + + +def _AddListFieldsMethod(message_descriptor, cls): + """Helper for _AddMessageMethods().""" + + def ListFields(self): + all_fields = [item for item in self._fields.items() if _IsPresent(item)] + all_fields.sort(key = lambda item: item[0].number) + return all_fields + + cls.ListFields = ListFields + + +def _AddHasFieldMethod(message_descriptor, cls): + """Helper for _AddMessageMethods().""" + + hassable_fields = {} + for field in message_descriptor.fields: + if field.is_repeated: + continue + # For proto3, only submessages and fields inside a oneof have presence. + if not field.has_presence: + continue + hassable_fields[field.name] = field + + # Has methods are supported for oneof descriptors. + for oneof in message_descriptor.oneofs: + hassable_fields[oneof.name] = oneof + + def HasField(self, field_name): + try: + field = hassable_fields[field_name] + except KeyError as exc: + raise ValueError('Protocol message %s has no non-repeated field "%s" ' + 'nor has presence is not available for this field.' % ( + message_descriptor.full_name, field_name)) from exc + + if isinstance(field, descriptor_mod.OneofDescriptor): + try: + return HasField(self, self._oneofs[field].name) + except KeyError: + return False + else: + if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + value = self._fields.get(field) + return value is not None and value._is_present_in_parent + else: + return field in self._fields + + cls.HasField = HasField + + +def _AddClearFieldMethod(message_descriptor, cls): + """Helper for _AddMessageMethods().""" + def ClearField(self, field_name): + try: + field = message_descriptor.fields_by_name[field_name] + except KeyError: + try: + field = message_descriptor.oneofs_by_name[field_name] + if field in self._oneofs: + field = self._oneofs[field] + else: + return + except KeyError: + raise ValueError('Protocol message %s has no "%s" field.' % + (message_descriptor.name, field_name)) + + if field in self._fields: + # To match the C++ implementation, we need to invalidate iterators + # for map fields when ClearField() happens. + if hasattr(self._fields[field], 'InvalidateIterators'): + self._fields[field].InvalidateIterators() + + # Note: If the field is a sub-message, its listener will still point + # at us. That's fine, because the worst than can happen is that it + # will call _Modified() and invalidate our byte size. Big deal. + del self._fields[field] + + if self._oneofs.get(field.containing_oneof, None) is field: + del self._oneofs[field.containing_oneof] + + # Always call _Modified() -- even if nothing was changed, this is + # a mutating method, and thus calling it should cause the field to become + # present in the parent message. + self._Modified() + + cls.ClearField = ClearField + + +def _AddClearExtensionMethod(cls): + """Helper for _AddMessageMethods().""" + def ClearExtension(self, field_descriptor): + extension_dict._VerifyExtensionHandle(self, field_descriptor) + + # Similar to ClearField(), above. + if field_descriptor in self._fields: + del self._fields[field_descriptor] + self._Modified() + cls.ClearExtension = ClearExtension + + +def _AddHasExtensionMethod(cls): + """Helper for _AddMessageMethods().""" + def HasExtension(self, field_descriptor): + extension_dict._VerifyExtensionHandle(self, field_descriptor) + if field_descriptor.is_repeated: + raise KeyError('"%s" is repeated.' % field_descriptor.full_name) + + if field_descriptor.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + value = self._fields.get(field_descriptor) + return value is not None and value._is_present_in_parent + else: + return field_descriptor in self._fields + cls.HasExtension = HasExtension + +def _InternalUnpackAny(msg): + """Unpacks Any message and returns the unpacked message. + + This internal method is different from public Any Unpack method which takes + the target message as argument. _InternalUnpackAny method does not have + target message type and need to find the message type in descriptor pool. + + Args: + msg: An Any message to be unpacked. + + Returns: + The unpacked message. + """ + # TODO: Don't use the factory of generated messages. + # To make Any work with custom factories, use the message factory of the + # parent message. + # pylint: disable=g-import-not-at-top + from google.protobuf import symbol_database + factory = symbol_database.Default() + + type_url = msg.type_url + + if not type_url: + return None + + # TODO: For now we just strip the hostname. Better logic will be + # required. + type_name = type_url.split('/')[-1] + descriptor = factory.pool.FindMessageTypeByName(type_name) + + if descriptor is None: + return None + + # Unable to import message_factory at top because of circular import. + # pylint: disable=g-import-not-at-top + from google.protobuf import message_factory + message_class = message_factory.GetMessageClass(descriptor) + message = message_class() + + message.ParseFromString(msg.value) + return message + + +def _AddEqualsMethod(message_descriptor, cls): + """Helper for _AddMessageMethods().""" + def __eq__(self, other): + if self.DESCRIPTOR.full_name == _ListValueFullTypeName and isinstance( + other, list + ): + return self._internal_compare(other) + if self.DESCRIPTOR.full_name == _StructFullTypeName and isinstance( + other, dict + ): + return self._internal_compare(other) + + if (not isinstance(other, message_mod.Message) or + other.DESCRIPTOR != self.DESCRIPTOR): + return NotImplemented + + if self is other: + return True + + if self.DESCRIPTOR.full_name == _AnyFullTypeName: + any_a = _InternalUnpackAny(self) + any_b = _InternalUnpackAny(other) + if any_a and any_b: + return any_a == any_b + + if not self.ListFields() == other.ListFields(): + return False + + # TODO: Fix UnknownFieldSet to consider MessageSet extensions, + # then use it for the comparison. + unknown_fields = list(self._unknown_fields) + unknown_fields.sort() + other_unknown_fields = list(other._unknown_fields) + other_unknown_fields.sort() + return unknown_fields == other_unknown_fields + + cls.__eq__ = __eq__ + + +def _AddStrMethod(message_descriptor, cls): + """Helper for _AddMessageMethods().""" + def __str__(self): + return text_format.MessageToString(self) + cls.__str__ = __str__ + + +def _AddReprMethod(message_descriptor, cls): + """Helper for _AddMessageMethods().""" + def __repr__(self): + return text_format.MessageToString(self) + cls.__repr__ = __repr__ + + +def _AddUnicodeMethod(unused_message_descriptor, cls): + """Helper for _AddMessageMethods().""" + + def __unicode__(self): + return text_format.MessageToString(self, as_utf8=True).decode('utf-8') + cls.__unicode__ = __unicode__ + + +def _AddContainsMethod(message_descriptor, cls): + + if message_descriptor.full_name == 'google.protobuf.Struct': + def __contains__(self, key): + return key in self.fields + elif message_descriptor.full_name == 'google.protobuf.ListValue': + def __contains__(self, value): + return value in self.items() + else: + def __contains__(self, field): + return self.HasField(field) + + cls.__contains__ = __contains__ + + +def _BytesForNonRepeatedElement(value, field_number, field_type): + """Returns the number of bytes needed to serialize a non-repeated element. + The returned byte count includes space for tag information and any + other additional space associated with serializing value. + + Args: + value: Value we're serializing. + field_number: Field number of this value. (Since the field number + is stored as part of a varint-encoded tag, this has an impact + on the total bytes required to serialize the value). + field_type: The type of the field. One of the TYPE_* constants + within FieldDescriptor. + """ + try: + fn = type_checkers.TYPE_TO_BYTE_SIZE_FN[field_type] + return fn(field_number, value) + except KeyError: + raise message_mod.EncodeError('Unrecognized field type: %d' % field_type) + + +def _AddByteSizeMethod(message_descriptor, cls): + """Helper for _AddMessageMethods().""" + + def ByteSize(self): + if not self._cached_byte_size_dirty: + return self._cached_byte_size + + size = 0 + descriptor = self.DESCRIPTOR + if descriptor._is_map_entry: + # Fields of map entry should always be serialized. + key_field = descriptor.fields_by_name['key'] + _MaybeAddEncoder(cls, key_field) + size = key_field._sizer(self.key) + value_field = descriptor.fields_by_name['value'] + _MaybeAddEncoder(cls, value_field) + size += value_field._sizer(self.value) + else: + for field_descriptor, field_value in self.ListFields(): + _MaybeAddEncoder(cls, field_descriptor) + size += field_descriptor._sizer(field_value) + for tag_bytes, value_bytes in self._unknown_fields: + size += len(tag_bytes) + len(value_bytes) + + self._cached_byte_size = size + self._cached_byte_size_dirty = False + self._listener_for_children.dirty = False + return size + + cls.ByteSize = ByteSize + + +def _AddSerializeToStringMethod(message_descriptor, cls): + """Helper for _AddMessageMethods().""" + + def SerializeToString(self, **kwargs): + # Check if the message has all of its required fields set. + if not self.IsInitialized(): + raise message_mod.EncodeError( + 'Message %s is missing required fields: %s' % ( + self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors()))) + return self.SerializePartialToString(**kwargs) + cls.SerializeToString = SerializeToString + + +def _AddSerializePartialToStringMethod(message_descriptor, cls): + """Helper for _AddMessageMethods().""" + + def SerializePartialToString(self, **kwargs): + out = BytesIO() + self._InternalSerialize(out.write, **kwargs) + return out.getvalue() + cls.SerializePartialToString = SerializePartialToString + + def InternalSerialize(self, write_bytes, deterministic=None): + if deterministic is None: + deterministic = ( + api_implementation.IsPythonDefaultSerializationDeterministic()) + else: + deterministic = bool(deterministic) + + descriptor = self.DESCRIPTOR + if descriptor._is_map_entry: + # Fields of map entry should always be serialized. + key_field = descriptor.fields_by_name['key'] + _MaybeAddEncoder(cls, key_field) + key_field._encoder(write_bytes, self.key, deterministic) + value_field = descriptor.fields_by_name['value'] + _MaybeAddEncoder(cls, value_field) + value_field._encoder(write_bytes, self.value, deterministic) + else: + for field_descriptor, field_value in self.ListFields(): + _MaybeAddEncoder(cls, field_descriptor) + field_descriptor._encoder(write_bytes, field_value, deterministic) + for tag_bytes, value_bytes in self._unknown_fields: + write_bytes(tag_bytes) + write_bytes(value_bytes) + cls._InternalSerialize = InternalSerialize + + +def _AddMergeFromStringMethod(message_descriptor, cls): + """Helper for _AddMessageMethods().""" + def MergeFromString(self, serialized): + serialized = memoryview(serialized) + length = len(serialized) + try: + if self._InternalParse(serialized, 0, length) != length: + # The only reason _InternalParse would return early is if it + # encountered an end-group tag. + raise message_mod.DecodeError('Unexpected end-group tag.') + except (IndexError, TypeError): + # Now ord(buf[p:p+1]) == ord('') gets TypeError. + raise message_mod.DecodeError('Truncated message.') + except struct.error as e: + raise message_mod.DecodeError(e) + return length # Return this for legacy reasons. + cls.MergeFromString = MergeFromString + + fields_by_tag = cls._fields_by_tag + message_set_decoders_by_tag = cls._message_set_decoders_by_tag + + def InternalParse(self, buffer, pos, end, current_depth=0): + """Create a message from serialized bytes. + + Args: + self: Message, instance of the proto message object. + buffer: memoryview of the serialized data. + pos: int, position to start in the serialized data. + end: int, end position of the serialized data. + + Returns: + Message object. + """ + # Guard against internal misuse, since this function is called internally + # quite extensively, and its easy to accidentally pass bytes. + assert isinstance(buffer, memoryview) + self._Modified() + field_dict = self._fields + while pos != end: + (tag_bytes, new_pos) = decoder.ReadTag(buffer, pos) + field_decoder, field_des = message_set_decoders_by_tag.get( + tag_bytes, (None, None) + ) + if field_decoder: + pos = field_decoder(buffer, new_pos, end, self, field_dict) + continue + field_des, is_packed = fields_by_tag.get(tag_bytes, (None, None)) + if field_des is None: + if not self._unknown_fields: # pylint: disable=protected-access + self._unknown_fields = [] # pylint: disable=protected-access + field_number, wire_type = decoder.DecodeTag(tag_bytes) + if field_number == 0: + raise message_mod.DecodeError('Field number 0 is illegal.') + (data, new_pos) = decoder._DecodeUnknownField( + buffer, new_pos, end, field_number, wire_type + ) # pylint: disable=protected-access + if new_pos == -1: + return pos + self._unknown_fields.append( + (tag_bytes, buffer[pos + len(tag_bytes) : new_pos].tobytes()) + ) + pos = new_pos + else: + _MaybeAddDecoder(cls, field_des) + field_decoder = field_des._decoders[is_packed] + pos = field_decoder( + buffer, new_pos, end, self, field_dict, current_depth + ) + if field_des.containing_oneof: + self._UpdateOneofState(field_des) + return pos + + cls._InternalParse = InternalParse + + +def _AddIsInitializedMethod(message_descriptor, cls): + """Adds the IsInitialized and FindInitializationError methods to the + protocol message class.""" + + required_fields = [field for field in message_descriptor.fields + if field.is_required] + + def IsInitialized(self, errors=None): + """Checks if all required fields of a message are set. + + Args: + errors: A list which, if provided, will be populated with the field + paths of all missing required fields. + + Returns: + True iff the specified message has all required fields set. + """ + + # Performance is critical so we avoid HasField() and ListFields(). + + for field in required_fields: + if (field not in self._fields or + (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and + not self._fields[field]._is_present_in_parent)): + if errors is not None: + errors.extend(self.FindInitializationErrors()) + return False + + for field, value in list(self._fields.items()): # dict can change size! + if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + if field.is_repeated: + if (field.message_type._is_map_entry): + continue + for element in value: + if not element.IsInitialized(): + if errors is not None: + errors.extend(self.FindInitializationErrors()) + return False + elif value._is_present_in_parent and not value.IsInitialized(): + if errors is not None: + errors.extend(self.FindInitializationErrors()) + return False + + return True + + cls.IsInitialized = IsInitialized + + def FindInitializationErrors(self): + """Finds required fields which are not initialized. + + Returns: + A list of strings. Each string is a path to an uninitialized field from + the top-level message, e.g. "foo.bar[5].baz". + """ + + errors = [] # simplify things + + for field in required_fields: + if not self.HasField(field.name): + errors.append(field.name) + + for field, value in self.ListFields(): + if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + if field.is_extension: + name = '(%s)' % field.full_name + else: + name = field.name + + if _IsMapField(field): + if _IsMessageMapField(field): + for key in value: + element = value[key] + prefix = '%s[%s].' % (name, key) + sub_errors = element.FindInitializationErrors() + errors += [prefix + error for error in sub_errors] + else: + # ScalarMaps can't have any initialization errors. + pass + elif field.is_repeated: + for i in range(len(value)): + element = value[i] + prefix = '%s[%d].' % (name, i) + sub_errors = element.FindInitializationErrors() + errors += [prefix + error for error in sub_errors] + else: + prefix = name + '.' + sub_errors = value.FindInitializationErrors() + errors += [prefix + error for error in sub_errors] + + return errors + + cls.FindInitializationErrors = FindInitializationErrors + + +def _FullyQualifiedClassName(klass): + module = klass.__module__ + name = getattr(klass, '__qualname__', klass.__name__) + if module in (None, 'builtins', '__builtin__'): + return name + return module + '.' + name + + +def _AddMergeFromMethod(cls): + CPPTYPE_MESSAGE = _FieldDescriptor.CPPTYPE_MESSAGE + + def MergeFrom(self, msg): + if not isinstance(msg, cls): + raise TypeError( + 'Parameter to MergeFrom() must be instance of same class: ' + 'expected %s got %s.' % (_FullyQualifiedClassName(cls), + _FullyQualifiedClassName(msg.__class__))) + + assert msg is not self + self._Modified() + + fields = self._fields + + for field, value in msg._fields.items(): + if field.is_repeated: + field_value = fields.get(field) + if field_value is None: + # Construct a new object to represent this field. + field_value = field._default_constructor(self) + fields[field] = field_value + field_value.MergeFrom(value) + elif field.cpp_type == CPPTYPE_MESSAGE: + if value._is_present_in_parent: + field_value = fields.get(field) + if field_value is None: + # Construct a new object to represent this field. + field_value = field._default_constructor(self) + fields[field] = field_value + field_value.MergeFrom(value) + else: + self._fields[field] = value + if field.containing_oneof: + self._UpdateOneofState(field) + + if msg._unknown_fields: + if not self._unknown_fields: + self._unknown_fields = [] + self._unknown_fields.extend(msg._unknown_fields) + + cls.MergeFrom = MergeFrom + + +def _AddWhichOneofMethod(message_descriptor, cls): + def WhichOneof(self, oneof_name): + """Returns the name of the currently set field inside a oneof, or None.""" + try: + field = message_descriptor.oneofs_by_name[oneof_name] + except KeyError: + raise ValueError( + 'Protocol message has no oneof "%s" field.' % oneof_name) + + nested_field = self._oneofs.get(field, None) + if nested_field is not None and self.HasField(nested_field.name): + return nested_field.name + else: + return None + + cls.WhichOneof = WhichOneof + + +def _Clear(self): + # Clear fields. + self._fields = {} + self._unknown_fields = () + + self._oneofs = {} + self._Modified() + + +def _UnknownFields(self): + raise NotImplementedError('Please use the add-on feaure ' + 'unknown_fields.UnknownFieldSet(message) in ' + 'unknown_fields.py instead.') + + +def _DiscardUnknownFields(self): + self._unknown_fields = [] + for field, value in self.ListFields(): + if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + if _IsMapField(field): + if _IsMessageMapField(field): + for key in value: + value[key].DiscardUnknownFields() + elif field.is_repeated: + for sub_message in value: + sub_message.DiscardUnknownFields() + else: + value.DiscardUnknownFields() + + +def _SetListener(self, listener): + if listener is None: + self._listener = message_listener_mod.NullMessageListener() + else: + self._listener = listener + + +def _AddMessageMethods(message_descriptor, cls): + """Adds implementations of all Message methods to cls.""" + _AddListFieldsMethod(message_descriptor, cls) + _AddHasFieldMethod(message_descriptor, cls) + _AddClearFieldMethod(message_descriptor, cls) + if message_descriptor.is_extendable: + _AddClearExtensionMethod(cls) + _AddHasExtensionMethod(cls) + _AddEqualsMethod(message_descriptor, cls) + _AddStrMethod(message_descriptor, cls) + _AddReprMethod(message_descriptor, cls) + _AddUnicodeMethod(message_descriptor, cls) + _AddContainsMethod(message_descriptor, cls) + _AddByteSizeMethod(message_descriptor, cls) + _AddSerializeToStringMethod(message_descriptor, cls) + _AddSerializePartialToStringMethod(message_descriptor, cls) + _AddMergeFromStringMethod(message_descriptor, cls) + _AddIsInitializedMethod(message_descriptor, cls) + _AddMergeFromMethod(cls) + _AddWhichOneofMethod(message_descriptor, cls) + # Adds methods which do not depend on cls. + cls.Clear = _Clear + cls.DiscardUnknownFields = _DiscardUnknownFields + cls._SetListener = _SetListener + + +def _AddPrivateHelperMethods(message_descriptor, cls): + """Adds implementation of private helper methods to cls.""" + + def Modified(self): + """Sets the _cached_byte_size_dirty bit to true, + and propagates this to our listener iff this was a state change. + """ + + # Note: Some callers check _cached_byte_size_dirty before calling + # _Modified() as an extra optimization. So, if this method is ever + # changed such that it does stuff even when _cached_byte_size_dirty is + # already true, the callers need to be updated. + if not self._cached_byte_size_dirty: + self._cached_byte_size_dirty = True + self._listener_for_children.dirty = True + self._is_present_in_parent = True + self._listener.Modified() + + def _UpdateOneofState(self, field): + """Sets field as the active field in its containing oneof. + + Will also delete currently active field in the oneof, if it is different + from the argument. Does not mark the message as modified. + """ + other_field = self._oneofs.setdefault(field.containing_oneof, field) + if other_field is not field: + del self._fields[other_field] + self._oneofs[field.containing_oneof] = field + + cls._Modified = Modified + cls.SetInParent = Modified + cls._UpdateOneofState = _UpdateOneofState + + +class _Listener(object): + + """MessageListener implementation that a parent message registers with its + child message. + + In order to support semantics like: + + foo.bar.baz.moo = 23 + assert foo.HasField('bar') + + ...child objects must have back references to their parents. + This helper class is at the heart of this support. + """ + + def __init__(self, parent_message): + """Args: + parent_message: The message whose _Modified() method we should call when + we receive Modified() messages. + """ + # This listener establishes a back reference from a child (contained) object + # to its parent (containing) object. We make this a weak reference to avoid + # creating cyclic garbage when the client finishes with the 'parent' object + # in the tree. + if isinstance(parent_message, weakref.ProxyType): + self._parent_message_weakref = parent_message + else: + self._parent_message_weakref = weakref.proxy(parent_message) + + # As an optimization, we also indicate directly on the listener whether + # or not the parent message is dirty. This way we can avoid traversing + # up the tree in the common case. + self.dirty = False + + def Modified(self): + if self.dirty: + return + try: + # Propagate the signal to our parents iff this is the first field set. + self._parent_message_weakref._Modified() + except ReferenceError: + # We can get here if a client has kept a reference to a child object, + # and is now setting a field on it, but the child's parent has been + # garbage-collected. This is not an error. + pass + + +class _OneofListener(_Listener): + """Special listener implementation for setting composite oneof fields.""" + + def __init__(self, parent_message, field): + """Args: + parent_message: The message whose _Modified() method we should call when + we receive Modified() messages. + field: The descriptor of the field being set in the parent message. + """ + super(_OneofListener, self).__init__(parent_message) + self._field = field + + def Modified(self): + """Also updates the state of the containing oneof in the parent message.""" + try: + self._parent_message_weakref._UpdateOneofState(self._field) + super(_OneofListener, self).Modified() + except ReferenceError: + pass diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/testing_refleaks.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/testing_refleaks.py new file mode 100644 index 0000000000000000000000000000000000000000..f94ef2b9d6128b82cc832409843e7d8a57d935c8 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/testing_refleaks.py @@ -0,0 +1,128 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""A subclass of unittest.TestCase which checks for reference leaks. + +To use: +- Use testing_refleak.BaseTestCase instead of unittest.TestCase +- Configure and compile Python with --with-pydebug + +If sys.gettotalrefcount() is not available (because Python was built without +the Py_DEBUG option), then this module is a no-op and tests will run normally. +""" + +import copyreg +import gc +import sys +import unittest + + +class LocalTestResult(unittest.TestResult): + """A TestResult which forwards events to a parent object, except for Skips.""" + + def __init__(self, parent_result): + unittest.TestResult.__init__(self) + self.parent_result = parent_result + + def addError(self, test, error): + self.parent_result.addError(test, error) + + def addFailure(self, test, error): + self.parent_result.addFailure(test, error) + + def addSkip(self, test, reason): + pass + + def addDuration(self, test, duration): + pass + + +class ReferenceLeakCheckerMixin(object): + """A mixin class for TestCase, which checks reference counts.""" + + NB_RUNS = 3 + + def run(self, result=None): + testMethod = getattr(self, self._testMethodName) + expecting_failure_method = getattr(testMethod, "__unittest_expecting_failure__", False) + expecting_failure_class = getattr(self, "__unittest_expecting_failure__", False) + if expecting_failure_class or expecting_failure_method: + return + + # python_message.py registers all Message classes to some pickle global + # registry, which makes the classes immortal. + # We save a copy of this registry, and reset it before we could references. + self._saved_pickle_registry = copyreg.dispatch_table.copy() + + # Run the test twice, to warm up the instance attributes. + super(ReferenceLeakCheckerMixin, self).run(result=result) + super(ReferenceLeakCheckerMixin, self).run(result=result) + + local_result = LocalTestResult(result) + num_flakes = 0 + refcount_deltas = [] + + # Observe the refcount, then create oldrefcount which actually makes the + # refcount 1 higher than the recorded value immediately + oldrefcount = self._getRefcounts() + while len(refcount_deltas) < self.NB_RUNS: + oldrefcount = self._getRefcounts() + super(ReferenceLeakCheckerMixin, self).run(result=local_result) + newrefcount = self._getRefcounts() + # If the GC was able to collect some objects after the call to run() that + # it could not collect before the call, then the counts won't match. + if newrefcount < oldrefcount and num_flakes < 2: + # This result is (probably) a flake -- garbage collectors aren't very + # predictable, but a lower ending refcount is the opposite of the + # failure we are testing for. If the result is repeatable, then we will + # eventually report it, but not after trying to eliminate it. + num_flakes += 1 + continue + num_flakes = 0 + refcount_deltas.append(newrefcount - oldrefcount) + print(refcount_deltas, self) + + try: + self.assertEqual(refcount_deltas, [0] * self.NB_RUNS) + except Exception: # pylint: disable=broad-except + result.addError(self, sys.exc_info()) + + def _getRefcounts(self): + if hasattr(sys, "_clear_internal_caches"): # Since 3.13 + sys._clear_internal_caches() # pylint: disable=protected-access + else: + sys._clear_type_cache() # pylint: disable=protected-access + copyreg.dispatch_table.clear() + copyreg.dispatch_table.update(self._saved_pickle_registry) + # It is sometimes necessary to gc.collect() multiple times, to ensure + # that all objects can be collected. + gc.collect() + gc.collect() + gc.collect() + return sys.gettotalrefcount() + + +if hasattr(sys, 'gettotalrefcount'): + + def TestCase(test_class): + new_bases = (ReferenceLeakCheckerMixin,) + test_class.__bases__ + new_class = type(test_class)( + test_class.__name__, new_bases, dict(test_class.__dict__)) + return new_class + SkipReferenceLeakChecker = unittest.skip + +else: + # When PyDEBUG is not enabled, run the tests normally. + + def TestCase(test_class): + return test_class + + def SkipReferenceLeakChecker(reason): + del reason # Don't skip, so don't need a reason. + def Same(func): + return func + return Same diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/type_checkers.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/type_checkers.py new file mode 100644 index 0000000000000000000000000000000000000000..17e814ed9738123af4ece0676b44696479d4833b --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/type_checkers.py @@ -0,0 +1,455 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""Provides type checking routines. + +This module defines type checking utilities in the forms of dictionaries: + +VALUE_CHECKERS: A dictionary of field types and a value validation object. +TYPE_TO_BYTE_SIZE_FN: A dictionary with field types and a size computing + function. +TYPE_TO_SERIALIZE_METHOD: A dictionary with field types and serialization + function. +FIELD_TYPE_TO_WIRE_TYPE: A dictionary with field typed and their + corresponding wire types. +TYPE_TO_DESERIALIZE_METHOD: A dictionary with field types and deserialization + function. +""" + +__author__ = 'robinson@google.com (Will Robinson)' + +import numbers +import struct +import warnings + +from google.protobuf import descriptor +from google.protobuf.internal import decoder +from google.protobuf.internal import encoder +from google.protobuf.internal import wire_format + +_FieldDescriptor = descriptor.FieldDescriptor +# TODO: Remove this warning count after 34.0 +# Assign bool to int/enum warnings will print 100 times at most which should +# be enough for users to notice and do not cause timeout. +_BoolWarningCount = 100 + +def TruncateToFourByteFloat(original): + return struct.unpack(' 0: + _BoolWarningCount -= 1 + message = ( + '%.1024r has type %s, but expected one of: %s. This warning ' + 'will turn into error in 7.34.0, please fix it before that.' + % ( + proposed_value, + type(proposed_value), + (int,), + ) + ) + # TODO: Raise errors in 2026 Q1 release + warnings.warn(message) + + if not hasattr(proposed_value, '__index__') or ( + type(proposed_value).__module__ == 'numpy' and + type(proposed_value).__name__ == 'ndarray'): + message = ('%.1024r has type %s, but expected one of: %s' % + (proposed_value, type(proposed_value), (int,))) + raise TypeError(message) + + if not self._MIN <= int(proposed_value) <= self._MAX: + raise ValueError('Value out of range: %d' % proposed_value) + # We force all values to int to make alternate implementations where the + # distinction is more significant (e.g. the C++ implementation) simpler. + proposed_value = int(proposed_value) + return proposed_value + + def DefaultValue(self): + return 0 + + +class EnumValueChecker(object): + + """Checker used for enum fields. Performs type-check and range check.""" + + def __init__(self, enum_type): + self._enum_type = enum_type + + def CheckValue(self, proposed_value): + global _BoolWarningCount + if type(proposed_value) == bool and _BoolWarningCount > 0: + _BoolWarningCount -= 1 + message = ( + '%.1024r has type %s, but expected one of: %s. This warning ' + 'will turn into error in 7.34.0, please fix it before that.' + % ( + proposed_value, + type(proposed_value), + (int,), + ) + ) + # TODO: Raise errors in 2026 Q1 release + warnings.warn(message) + if not isinstance(proposed_value, numbers.Integral): + message = ('%.1024r has type %s, but expected one of: %s' % + (proposed_value, type(proposed_value), (int,))) + raise TypeError(message) + if int(proposed_value) not in self._enum_type.values_by_number: + raise ValueError('Unknown enum value: %d' % proposed_value) + return proposed_value + + def DefaultValue(self): + return self._enum_type.values[0].number + + +class UnicodeValueChecker(object): + + """Checker used for string fields. + + Always returns a unicode value, even if the input is of type str. + """ + + def CheckValue(self, proposed_value): + if not isinstance(proposed_value, (bytes, str)): + message = ('%.1024r has type %s, but expected one of: %s' % + (proposed_value, type(proposed_value), (bytes, str))) + raise TypeError(message) + + # If the value is of type 'bytes' make sure that it is valid UTF-8 data. + if isinstance(proposed_value, bytes): + try: + proposed_value = proposed_value.decode('utf-8') + except UnicodeDecodeError: + raise ValueError('%.1024r has type bytes, but isn\'t valid UTF-8 ' + 'encoding. Non-UTF-8 strings must be converted to ' + 'unicode objects before being added.' % + (proposed_value)) + else: + try: + proposed_value.encode('utf8') + except UnicodeEncodeError: + raise ValueError('%.1024r isn\'t a valid unicode string and ' + 'can\'t be encoded in UTF-8.'% + (proposed_value)) + + return proposed_value + + def DefaultValue(self): + return u"" + + +class Int32ValueChecker(IntValueChecker): + # We're sure to use ints instead of longs here since comparison may be more + # efficient. + _MIN = -2147483648 + _MAX = 2147483647 + + +class Uint32ValueChecker(IntValueChecker): + _MIN = 0 + _MAX = (1 << 32) - 1 + + +class Int64ValueChecker(IntValueChecker): + _MIN = -(1 << 63) + _MAX = (1 << 63) - 1 + + +class Uint64ValueChecker(IntValueChecker): + _MIN = 0 + _MAX = (1 << 64) - 1 + + +# The max 4 bytes float is about 3.4028234663852886e+38 +_FLOAT_MAX = float.fromhex('0x1.fffffep+127') +_FLOAT_MIN = -_FLOAT_MAX +_MAX_FLOAT_AS_DOUBLE_ROUNDED = 3.4028235677973366e38 +_INF = float('inf') +_NEG_INF = float('-inf') + + +class DoubleValueChecker(object): + """Checker used for double fields. + + Performs type-check and range check. + """ + + def CheckValue(self, proposed_value): + """Check and convert proposed_value to float.""" + if (not hasattr(proposed_value, '__float__') and + not hasattr(proposed_value, '__index__')) or ( + type(proposed_value).__module__ == 'numpy' and + type(proposed_value).__name__ == 'ndarray'): + message = ('%.1024r has type %s, but expected one of: int, float' % + (proposed_value, type(proposed_value))) + raise TypeError(message) + return float(proposed_value) + + def DefaultValue(self): + return 0.0 + + +class FloatValueChecker(DoubleValueChecker): + """Checker used for float fields. + + Performs type-check and range check. + + Values exceeding a 32-bit float will be converted to inf/-inf. + """ + + def CheckValue(self, proposed_value): + """Check and convert proposed_value to float.""" + converted_value = super().CheckValue(proposed_value) + # This inf rounding matches the C++ proto SafeDoubleToFloat logic. + if converted_value > _FLOAT_MAX: + if converted_value <= _MAX_FLOAT_AS_DOUBLE_ROUNDED: + return _FLOAT_MAX + return _INF + if converted_value < _FLOAT_MIN: + if converted_value >= -_MAX_FLOAT_AS_DOUBLE_ROUNDED: + return _FLOAT_MIN + return _NEG_INF + + return TruncateToFourByteFloat(converted_value) + +# Type-checkers for all scalar CPPTYPEs. +_VALUE_CHECKERS = { + _FieldDescriptor.CPPTYPE_INT32: Int32ValueChecker(), + _FieldDescriptor.CPPTYPE_INT64: Int64ValueChecker(), + _FieldDescriptor.CPPTYPE_UINT32: Uint32ValueChecker(), + _FieldDescriptor.CPPTYPE_UINT64: Uint64ValueChecker(), + _FieldDescriptor.CPPTYPE_DOUBLE: DoubleValueChecker(), + _FieldDescriptor.CPPTYPE_FLOAT: FloatValueChecker(), + _FieldDescriptor.CPPTYPE_BOOL: BoolValueChecker(), + _FieldDescriptor.CPPTYPE_STRING: TypeCheckerWithDefault(b'', bytes), +} + + +# Map from field type to a function F, such that F(field_num, value) +# gives the total byte size for a value of the given type. This +# byte size includes tag information and any other additional space +# associated with serializing "value". +TYPE_TO_BYTE_SIZE_FN = { + _FieldDescriptor.TYPE_DOUBLE: wire_format.DoubleByteSize, + _FieldDescriptor.TYPE_FLOAT: wire_format.FloatByteSize, + _FieldDescriptor.TYPE_INT64: wire_format.Int64ByteSize, + _FieldDescriptor.TYPE_UINT64: wire_format.UInt64ByteSize, + _FieldDescriptor.TYPE_INT32: wire_format.Int32ByteSize, + _FieldDescriptor.TYPE_FIXED64: wire_format.Fixed64ByteSize, + _FieldDescriptor.TYPE_FIXED32: wire_format.Fixed32ByteSize, + _FieldDescriptor.TYPE_BOOL: wire_format.BoolByteSize, + _FieldDescriptor.TYPE_STRING: wire_format.StringByteSize, + _FieldDescriptor.TYPE_GROUP: wire_format.GroupByteSize, + _FieldDescriptor.TYPE_MESSAGE: wire_format.MessageByteSize, + _FieldDescriptor.TYPE_BYTES: wire_format.BytesByteSize, + _FieldDescriptor.TYPE_UINT32: wire_format.UInt32ByteSize, + _FieldDescriptor.TYPE_ENUM: wire_format.EnumByteSize, + _FieldDescriptor.TYPE_SFIXED32: wire_format.SFixed32ByteSize, + _FieldDescriptor.TYPE_SFIXED64: wire_format.SFixed64ByteSize, + _FieldDescriptor.TYPE_SINT32: wire_format.SInt32ByteSize, + _FieldDescriptor.TYPE_SINT64: wire_format.SInt64ByteSize + } + + +# Maps from field types to encoder constructors. +TYPE_TO_ENCODER = { + _FieldDescriptor.TYPE_DOUBLE: encoder.DoubleEncoder, + _FieldDescriptor.TYPE_FLOAT: encoder.FloatEncoder, + _FieldDescriptor.TYPE_INT64: encoder.Int64Encoder, + _FieldDescriptor.TYPE_UINT64: encoder.UInt64Encoder, + _FieldDescriptor.TYPE_INT32: encoder.Int32Encoder, + _FieldDescriptor.TYPE_FIXED64: encoder.Fixed64Encoder, + _FieldDescriptor.TYPE_FIXED32: encoder.Fixed32Encoder, + _FieldDescriptor.TYPE_BOOL: encoder.BoolEncoder, + _FieldDescriptor.TYPE_STRING: encoder.StringEncoder, + _FieldDescriptor.TYPE_GROUP: encoder.GroupEncoder, + _FieldDescriptor.TYPE_MESSAGE: encoder.MessageEncoder, + _FieldDescriptor.TYPE_BYTES: encoder.BytesEncoder, + _FieldDescriptor.TYPE_UINT32: encoder.UInt32Encoder, + _FieldDescriptor.TYPE_ENUM: encoder.EnumEncoder, + _FieldDescriptor.TYPE_SFIXED32: encoder.SFixed32Encoder, + _FieldDescriptor.TYPE_SFIXED64: encoder.SFixed64Encoder, + _FieldDescriptor.TYPE_SINT32: encoder.SInt32Encoder, + _FieldDescriptor.TYPE_SINT64: encoder.SInt64Encoder, + } + + +# Maps from field types to sizer constructors. +TYPE_TO_SIZER = { + _FieldDescriptor.TYPE_DOUBLE: encoder.DoubleSizer, + _FieldDescriptor.TYPE_FLOAT: encoder.FloatSizer, + _FieldDescriptor.TYPE_INT64: encoder.Int64Sizer, + _FieldDescriptor.TYPE_UINT64: encoder.UInt64Sizer, + _FieldDescriptor.TYPE_INT32: encoder.Int32Sizer, + _FieldDescriptor.TYPE_FIXED64: encoder.Fixed64Sizer, + _FieldDescriptor.TYPE_FIXED32: encoder.Fixed32Sizer, + _FieldDescriptor.TYPE_BOOL: encoder.BoolSizer, + _FieldDescriptor.TYPE_STRING: encoder.StringSizer, + _FieldDescriptor.TYPE_GROUP: encoder.GroupSizer, + _FieldDescriptor.TYPE_MESSAGE: encoder.MessageSizer, + _FieldDescriptor.TYPE_BYTES: encoder.BytesSizer, + _FieldDescriptor.TYPE_UINT32: encoder.UInt32Sizer, + _FieldDescriptor.TYPE_ENUM: encoder.EnumSizer, + _FieldDescriptor.TYPE_SFIXED32: encoder.SFixed32Sizer, + _FieldDescriptor.TYPE_SFIXED64: encoder.SFixed64Sizer, + _FieldDescriptor.TYPE_SINT32: encoder.SInt32Sizer, + _FieldDescriptor.TYPE_SINT64: encoder.SInt64Sizer, + } + + +# Maps from field type to a decoder constructor. +TYPE_TO_DECODER = { + _FieldDescriptor.TYPE_DOUBLE: decoder.DoubleDecoder, + _FieldDescriptor.TYPE_FLOAT: decoder.FloatDecoder, + _FieldDescriptor.TYPE_INT64: decoder.Int64Decoder, + _FieldDescriptor.TYPE_UINT64: decoder.UInt64Decoder, + _FieldDescriptor.TYPE_INT32: decoder.Int32Decoder, + _FieldDescriptor.TYPE_FIXED64: decoder.Fixed64Decoder, + _FieldDescriptor.TYPE_FIXED32: decoder.Fixed32Decoder, + _FieldDescriptor.TYPE_BOOL: decoder.BoolDecoder, + _FieldDescriptor.TYPE_STRING: decoder.StringDecoder, + _FieldDescriptor.TYPE_GROUP: decoder.GroupDecoder, + _FieldDescriptor.TYPE_MESSAGE: decoder.MessageDecoder, + _FieldDescriptor.TYPE_BYTES: decoder.BytesDecoder, + _FieldDescriptor.TYPE_UINT32: decoder.UInt32Decoder, + _FieldDescriptor.TYPE_ENUM: decoder.EnumDecoder, + _FieldDescriptor.TYPE_SFIXED32: decoder.SFixed32Decoder, + _FieldDescriptor.TYPE_SFIXED64: decoder.SFixed64Decoder, + _FieldDescriptor.TYPE_SINT32: decoder.SInt32Decoder, + _FieldDescriptor.TYPE_SINT64: decoder.SInt64Decoder, + } + +# Maps from field type to expected wiretype. +FIELD_TYPE_TO_WIRE_TYPE = { + _FieldDescriptor.TYPE_DOUBLE: wire_format.WIRETYPE_FIXED64, + _FieldDescriptor.TYPE_FLOAT: wire_format.WIRETYPE_FIXED32, + _FieldDescriptor.TYPE_INT64: wire_format.WIRETYPE_VARINT, + _FieldDescriptor.TYPE_UINT64: wire_format.WIRETYPE_VARINT, + _FieldDescriptor.TYPE_INT32: wire_format.WIRETYPE_VARINT, + _FieldDescriptor.TYPE_FIXED64: wire_format.WIRETYPE_FIXED64, + _FieldDescriptor.TYPE_FIXED32: wire_format.WIRETYPE_FIXED32, + _FieldDescriptor.TYPE_BOOL: wire_format.WIRETYPE_VARINT, + _FieldDescriptor.TYPE_STRING: + wire_format.WIRETYPE_LENGTH_DELIMITED, + _FieldDescriptor.TYPE_GROUP: wire_format.WIRETYPE_START_GROUP, + _FieldDescriptor.TYPE_MESSAGE: + wire_format.WIRETYPE_LENGTH_DELIMITED, + _FieldDescriptor.TYPE_BYTES: + wire_format.WIRETYPE_LENGTH_DELIMITED, + _FieldDescriptor.TYPE_UINT32: wire_format.WIRETYPE_VARINT, + _FieldDescriptor.TYPE_ENUM: wire_format.WIRETYPE_VARINT, + _FieldDescriptor.TYPE_SFIXED32: wire_format.WIRETYPE_FIXED32, + _FieldDescriptor.TYPE_SFIXED64: wire_format.WIRETYPE_FIXED64, + _FieldDescriptor.TYPE_SINT32: wire_format.WIRETYPE_VARINT, + _FieldDescriptor.TYPE_SINT64: wire_format.WIRETYPE_VARINT, + } diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/well_known_types.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/well_known_types.py new file mode 100644 index 0000000000000000000000000000000000000000..32b625a3022e4f30b820b1d24ac15ffefb9b9c93 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/well_known_types.py @@ -0,0 +1,695 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""Contains well known classes. + +This files defines well known classes which need extra maintenance including: + - Any + - Duration + - FieldMask + - Struct + - Timestamp +""" + +__author__ = 'jieluo@google.com (Jie Luo)' + +import calendar +import collections.abc +import datetime +from typing import Union +import warnings +from google.protobuf.internal import field_mask + +FieldMask = field_mask.FieldMask + +_TIMESTAMPFORMAT = '%Y-%m-%dT%H:%M:%S' +_NANOS_PER_SECOND = 1000000000 +_NANOS_PER_MILLISECOND = 1000000 +_NANOS_PER_MICROSECOND = 1000 +_MILLIS_PER_SECOND = 1000 +_MICROS_PER_SECOND = 1000000 +_SECONDS_PER_DAY = 24 * 3600 +_DURATION_SECONDS_MAX = 315576000000 +_TIMESTAMP_SECONDS_MIN = -62135596800 +_TIMESTAMP_SECONDS_MAX = 253402300799 + +_EPOCH_DATETIME_NAIVE = datetime.datetime(1970, 1, 1, tzinfo=None) +_EPOCH_DATETIME_AWARE = _EPOCH_DATETIME_NAIVE.replace( + tzinfo=datetime.timezone.utc +) + + +class Any(object): + """Class for Any Message type.""" + + __slots__ = () + + def Pack( + self, msg, type_url_prefix='type.googleapis.com/', deterministic=None + ): + """Packs the specified message into current Any message.""" + if len(type_url_prefix) < 1 or type_url_prefix[-1] != '/': + self.type_url = '%s/%s' % (type_url_prefix, msg.DESCRIPTOR.full_name) + else: + self.type_url = '%s%s' % (type_url_prefix, msg.DESCRIPTOR.full_name) + self.value = msg.SerializeToString(deterministic=deterministic) + + def Unpack(self, msg): + """Unpacks the current Any message into specified message.""" + descriptor = msg.DESCRIPTOR + if not self.Is(descriptor): + return False + msg.ParseFromString(self.value) + return True + + def TypeName(self): + """Returns the protobuf type name of the inner message.""" + # Only last part is to be used: b/25630112 + return self.type_url.rpartition('/')[2] + + def Is(self, descriptor): + """Checks if this Any represents the given protobuf type.""" + return '/' in self.type_url and self.TypeName() == descriptor.full_name + + +class Timestamp(object): + """Class for Timestamp message type.""" + + __slots__ = () + + def ToJsonString(self): + """Converts Timestamp to RFC 3339 date string format. + + Returns: + A string converted from timestamp. The string is always Z-normalized + and uses 3, 6 or 9 fractional digits as required to represent the + exact time. Example of the return format: '1972-01-01T10:00:20.021Z' + """ + _CheckTimestampValid(self.seconds, self.nanos) + nanos = self.nanos + seconds = self.seconds % _SECONDS_PER_DAY + days = (self.seconds - seconds) // _SECONDS_PER_DAY + dt = datetime.datetime(1970, 1, 1) + datetime.timedelta(days, seconds) + + result = dt.isoformat() + if (nanos % 1e9) == 0: + # If there are 0 fractional digits, the fractional + # point '.' should be omitted when serializing. + return result + 'Z' + if (nanos % 1e6) == 0: + # Serialize 3 fractional digits. + return result + '.%03dZ' % (nanos / 1e6) + if (nanos % 1e3) == 0: + # Serialize 6 fractional digits. + return result + '.%06dZ' % (nanos / 1e3) + # Serialize 9 fractional digits. + return result + '.%09dZ' % nanos + + def FromJsonString(self, value): + """Parse a RFC 3339 date string format to Timestamp. + + Args: + value: A date string. Any fractional digits (or none) and any offset are + accepted as long as they fit into nano-seconds precision. Example of + accepted format: '1972-01-01T10:00:20.021-05:00' + + Raises: + ValueError: On parsing problems. + """ + if not isinstance(value, str): + raise ValueError('Timestamp JSON value not a string: {!r}'.format(value)) + timezone_offset = value.find('Z') + if timezone_offset == -1: + timezone_offset = value.find('+') + if timezone_offset == -1: + timezone_offset = value.rfind('-') + if timezone_offset == -1: + raise ValueError( + 'Failed to parse timestamp: missing valid timezone offset.' + ) + time_value = value[0:timezone_offset] + # Parse datetime and nanos. + point_position = time_value.find('.') + if point_position == -1: + second_value = time_value + nano_value = '' + else: + second_value = time_value[:point_position] + nano_value = time_value[point_position + 1 :] + if 't' in second_value: + raise ValueError( + "time data '{0}' does not match format '%Y-%m-%dT%H:%M:%S', " + "lowercase 't' is not accepted".format(second_value) + ) + date_object = datetime.datetime.strptime(second_value, _TIMESTAMPFORMAT) + td = date_object - datetime.datetime(1970, 1, 1) + seconds = td.seconds + td.days * _SECONDS_PER_DAY + if len(nano_value) > 9: + raise ValueError( + 'Failed to parse Timestamp: nanos {0} more than ' + '9 fractional digits.'.format(nano_value) + ) + if nano_value: + nanos = round(float('0.' + nano_value) * 1e9) + else: + nanos = 0 + # Parse timezone offsets. + if value[timezone_offset] == 'Z': + if len(value) != timezone_offset + 1: + raise ValueError( + 'Failed to parse timestamp: invalid trailing data {0}.'.format( + value + ) + ) + else: + timezone = value[timezone_offset:] + pos = timezone.find(':') + if pos == -1: + raise ValueError('Invalid timezone offset value: {0}.'.format(timezone)) + if timezone[0] == '+': + seconds -= (int(timezone[1:pos]) * 60 + int(timezone[pos + 1 :])) * 60 + else: + seconds += (int(timezone[1:pos]) * 60 + int(timezone[pos + 1 :])) * 60 + # Set seconds and nanos + _CheckTimestampValid(seconds, nanos) + self.seconds = int(seconds) + self.nanos = int(nanos) + + def GetCurrentTime(self): + """Get the current UTC into Timestamp.""" + self.FromDatetime(datetime.datetime.now(tz=datetime.timezone.utc)) + + def ToNanoseconds(self): + """Converts Timestamp to nanoseconds since epoch.""" + _CheckTimestampValid(self.seconds, self.nanos) + return self.seconds * _NANOS_PER_SECOND + self.nanos + + def ToMicroseconds(self): + """Converts Timestamp to microseconds since epoch.""" + _CheckTimestampValid(self.seconds, self.nanos) + return ( + self.seconds * _MICROS_PER_SECOND + self.nanos // _NANOS_PER_MICROSECOND + ) + + def ToMilliseconds(self): + """Converts Timestamp to milliseconds since epoch.""" + _CheckTimestampValid(self.seconds, self.nanos) + return ( + self.seconds * _MILLIS_PER_SECOND + self.nanos // _NANOS_PER_MILLISECOND + ) + + def ToSeconds(self): + """Converts Timestamp to seconds since epoch.""" + _CheckTimestampValid(self.seconds, self.nanos) + return self.seconds + + def FromNanoseconds(self, nanos): + """Converts nanoseconds since epoch to Timestamp.""" + seconds = nanos // _NANOS_PER_SECOND + nanos = nanos % _NANOS_PER_SECOND + _CheckTimestampValid(seconds, nanos) + self.seconds = seconds + self.nanos = nanos + + def FromMicroseconds(self, micros): + """Converts microseconds since epoch to Timestamp.""" + seconds = micros // _MICROS_PER_SECOND + nanos = (micros % _MICROS_PER_SECOND) * _NANOS_PER_MICROSECOND + _CheckTimestampValid(seconds, nanos) + self.seconds = seconds + self.nanos = nanos + + def FromMilliseconds(self, millis): + """Converts milliseconds since epoch to Timestamp.""" + seconds = millis // _MILLIS_PER_SECOND + nanos = (millis % _MILLIS_PER_SECOND) * _NANOS_PER_MILLISECOND + _CheckTimestampValid(seconds, nanos) + self.seconds = seconds + self.nanos = nanos + + def FromSeconds(self, seconds): + """Converts seconds since epoch to Timestamp.""" + _CheckTimestampValid(seconds, 0) + self.seconds = seconds + self.nanos = 0 + + def ToDatetime(self, tzinfo=None): + """Converts Timestamp to a datetime. + + Args: + tzinfo: A datetime.tzinfo subclass; defaults to None. + + Returns: + If tzinfo is None, returns a timezone-naive UTC datetime (with no timezone + information, i.e. not aware that it's UTC). + + Otherwise, returns a timezone-aware datetime in the input timezone. + """ + # Using datetime.fromtimestamp for this would avoid constructing an extra + # timedelta object and possibly an extra datetime. Unfortunately, that has + # the disadvantage of not handling the full precision (on all platforms, see + # https://github.com/python/cpython/issues/109849) or full range (on some + # platforms, see https://github.com/python/cpython/issues/110042) of + # datetime. + _CheckTimestampValid(self.seconds, self.nanos) + delta = datetime.timedelta( + seconds=self.seconds, + microseconds=_RoundTowardZero(self.nanos, _NANOS_PER_MICROSECOND), + ) + if tzinfo is None: + return _EPOCH_DATETIME_NAIVE + delta + else: + # Note the tz conversion has to come after the timedelta arithmetic. + return (_EPOCH_DATETIME_AWARE + delta).astimezone(tzinfo) + + def FromDatetime(self, dt): + """Converts datetime to Timestamp. + + Args: + dt: A datetime. If it's timezone-naive, it's assumed to be in UTC. + """ + # Using this guide: http://wiki.python.org/moin/WorkingWithTime + # And this conversion guide: http://docs.python.org/library/time.html + + # Turn the date parameter into a tuple (struct_time) that can then be + # manipulated into a long value of seconds. During the conversion from + # struct_time to long, the source date in UTC, and so it follows that the + # correct transformation is calendar.timegm() + try: + seconds = calendar.timegm(dt.utctimetuple()) + nanos = dt.microsecond * _NANOS_PER_MICROSECOND + except AttributeError as e: + raise AttributeError( + 'Fail to convert to Timestamp. Expected a datetime like ' + 'object got {0} : {1}'.format(type(dt).__name__, e) + ) from e + _CheckTimestampValid(seconds, nanos) + self.seconds = seconds + self.nanos = nanos + + def _internal_assign(self, dt): + self.FromDatetime(dt) + + def __add__(self, value) -> datetime.datetime: + if isinstance(value, Duration): + return self.ToDatetime() + value.ToTimedelta() + return self.ToDatetime() + value + + __radd__ = __add__ + + def __sub__(self, value) -> Union[datetime.datetime, datetime.timedelta]: + if isinstance(value, Timestamp): + return self.ToDatetime() - value.ToDatetime() + elif isinstance(value, Duration): + return self.ToDatetime() - value.ToTimedelta() + return self.ToDatetime() - value + + def __rsub__(self, dt) -> datetime.timedelta: + return dt - self.ToDatetime() + + +def _CheckTimestampValid(seconds, nanos): + if seconds < _TIMESTAMP_SECONDS_MIN or seconds > _TIMESTAMP_SECONDS_MAX: + raise ValueError( + 'Timestamp is not valid: Seconds {0} must be in range ' + '[-62135596800, 253402300799].'.format(seconds)) + if nanos < 0 or nanos >= _NANOS_PER_SECOND: + raise ValueError( + 'Timestamp is not valid: Nanos {} must be in a range ' + '[0, 999999].'.format(nanos) + ) + + +class Duration(object): + """Class for Duration message type.""" + + __slots__ = () + + def ToJsonString(self): + """Converts Duration to string format. + + Returns: + A string converted from self. The string format will contains + 3, 6, or 9 fractional digits depending on the precision required to + represent the exact Duration value. For example: "1s", "1.010s", + "1.000000100s", "-3.100s" + """ + _CheckDurationValid(self.seconds, self.nanos) + if self.seconds < 0 or self.nanos < 0: + result = '-' + seconds = -self.seconds + int((0 - self.nanos) // 1e9) + nanos = (0 - self.nanos) % 1e9 + else: + result = '' + seconds = self.seconds + int(self.nanos // 1e9) + nanos = self.nanos % 1e9 + result += '%d' % seconds + if (nanos % 1e9) == 0: + # If there are 0 fractional digits, the fractional + # point '.' should be omitted when serializing. + return result + 's' + if (nanos % 1e6) == 0: + # Serialize 3 fractional digits. + return result + '.%03ds' % (nanos / 1e6) + if (nanos % 1e3) == 0: + # Serialize 6 fractional digits. + return result + '.%06ds' % (nanos / 1e3) + # Serialize 9 fractional digits. + return result + '.%09ds' % nanos + + def FromJsonString(self, value): + """Converts a string to Duration. + + Args: + value: A string to be converted. The string must end with 's'. Any + fractional digits (or none) are accepted as long as they fit into + precision. For example: "1s", "1.01s", "1.0000001s", "-3.100s + + Raises: + ValueError: On parsing problems. + """ + if not isinstance(value, str): + raise ValueError('Duration JSON value not a string: {!r}'.format(value)) + if len(value) < 1 or value[-1] != 's': + raise ValueError('Duration must end with letter "s": {0}.'.format(value)) + try: + pos = value.find('.') + if pos == -1: + seconds = int(value[:-1]) + nanos = 0 + else: + seconds = int(value[:pos]) + if value[0] == '-': + nanos = int(round(float('-0{0}'.format(value[pos:-1])) * 1e9)) + else: + nanos = int(round(float('0{0}'.format(value[pos:-1])) * 1e9)) + _CheckDurationValid(seconds, nanos) + self.seconds = seconds + self.nanos = nanos + except ValueError as e: + raise ValueError("Couldn't parse duration: {0} : {1}.".format(value, e)) + + def ToNanoseconds(self): + """Converts a Duration to nanoseconds.""" + return self.seconds * _NANOS_PER_SECOND + self.nanos + + def ToMicroseconds(self): + """Converts a Duration to microseconds.""" + micros = _RoundTowardZero(self.nanos, _NANOS_PER_MICROSECOND) + return self.seconds * _MICROS_PER_SECOND + micros + + def ToMilliseconds(self): + """Converts a Duration to milliseconds.""" + millis = _RoundTowardZero(self.nanos, _NANOS_PER_MILLISECOND) + return self.seconds * _MILLIS_PER_SECOND + millis + + def ToSeconds(self): + """Converts a Duration to seconds.""" + return self.seconds + + def FromNanoseconds(self, nanos): + """Converts nanoseconds to Duration.""" + self._NormalizeDuration( + nanos // _NANOS_PER_SECOND, nanos % _NANOS_PER_SECOND + ) + + def FromMicroseconds(self, micros): + """Converts microseconds to Duration.""" + self._NormalizeDuration( + micros // _MICROS_PER_SECOND, + (micros % _MICROS_PER_SECOND) * _NANOS_PER_MICROSECOND, + ) + + def FromMilliseconds(self, millis): + """Converts milliseconds to Duration.""" + self._NormalizeDuration( + millis // _MILLIS_PER_SECOND, + (millis % _MILLIS_PER_SECOND) * _NANOS_PER_MILLISECOND, + ) + + def FromSeconds(self, seconds): + """Converts seconds to Duration.""" + self.seconds = seconds + self.nanos = 0 + + def ToTimedelta(self) -> datetime.timedelta: + """Converts Duration to timedelta.""" + return datetime.timedelta( + seconds=self.seconds, + microseconds=_RoundTowardZero(self.nanos, _NANOS_PER_MICROSECOND), + ) + + def FromTimedelta(self, td): + """Converts timedelta to Duration.""" + try: + self._NormalizeDuration( + td.seconds + td.days * _SECONDS_PER_DAY, + td.microseconds * _NANOS_PER_MICROSECOND, + ) + except AttributeError as e: + raise AttributeError( + 'Fail to convert to Duration. Expected a timedelta like ' + 'object got {0}: {1}'.format(type(td).__name__, e) + ) from e + + def _internal_assign(self, td): + self.FromTimedelta(td) + + def _NormalizeDuration(self, seconds, nanos): + """Set Duration by seconds and nanos.""" + # Force nanos to be negative if the duration is negative. + if seconds < 0 and nanos > 0: + seconds += 1 + nanos -= _NANOS_PER_SECOND + self.seconds = seconds + self.nanos = nanos + + def __add__(self, value) -> Union[datetime.datetime, datetime.timedelta]: + if isinstance(value, Timestamp): + return self.ToTimedelta() + value.ToDatetime() + return self.ToTimedelta() + value + + __radd__ = __add__ + + def __sub__(self, value) -> datetime.timedelta: + return self.ToTimedelta() - value + + def __rsub__(self, value) -> Union[datetime.datetime, datetime.timedelta]: + return value - self.ToTimedelta() + + +def _CheckDurationValid(seconds, nanos): + if seconds < -_DURATION_SECONDS_MAX or seconds > _DURATION_SECONDS_MAX: + raise ValueError( + 'Duration is not valid: Seconds {0} must be in range ' + '[-315576000000, 315576000000].'.format(seconds) + ) + if nanos <= -_NANOS_PER_SECOND or nanos >= _NANOS_PER_SECOND: + raise ValueError( + 'Duration is not valid: Nanos {0} must be in range ' + '[-999999999, 999999999].'.format(nanos) + ) + if (nanos < 0 and seconds > 0) or (nanos > 0 and seconds < 0): + raise ValueError('Duration is not valid: Sign mismatch.') + + +def _RoundTowardZero(value, divider): + """Truncates the remainder part after division.""" + # For some languages, the sign of the remainder is implementation + # dependent if any of the operands is negative. Here we enforce + # "rounded toward zero" semantics. For example, for (-5) / 2 an + # implementation may give -3 as the result with the remainder being + # 1. This function ensures we always return -2 (closer to zero). + result = value // divider + remainder = value % divider + if result < 0 and remainder > 0: + return result + 1 + else: + return result + + +def _SetStructValue(struct_value, value): + if value is None: + struct_value.null_value = 0 + elif isinstance(value, bool): + # Note: this check must come before the number check because in Python + # True and False are also considered numbers. + struct_value.bool_value = value + elif isinstance(value, str): + struct_value.string_value = value + elif isinstance(value, (int, float)): + struct_value.number_value = value + elif isinstance(value, (dict, Struct)): + struct_value.struct_value.Clear() + struct_value.struct_value.update(value) + elif isinstance(value, (list, tuple, ListValue)): + struct_value.list_value.Clear() + struct_value.list_value.extend(value) + else: + raise ValueError('Unexpected type') + + +def _GetStructValue(struct_value): + which = struct_value.WhichOneof('kind') + if which == 'struct_value': + return struct_value.struct_value + elif which == 'null_value': + return None + elif which == 'number_value': + return struct_value.number_value + elif which == 'string_value': + return struct_value.string_value + elif which == 'bool_value': + return struct_value.bool_value + elif which == 'list_value': + return struct_value.list_value + elif which is None: + raise ValueError('Value not set') + + +class Struct(object): + """Class for Struct message type.""" + + __slots__ = () + + def __getitem__(self, key): + return _GetStructValue(self.fields[key]) + + def __setitem__(self, key, value): + _SetStructValue(self.fields[key], value) + + def __delitem__(self, key): + del self.fields[key] + + def __len__(self): + return len(self.fields) + + def __iter__(self): + return iter(self.fields) + + def _internal_assign(self, dictionary): + self.Clear() + self.update(dictionary) + + def _internal_compare(self, other): + size = len(self) + if size != len(other): + return False + for key, value in self.items(): + if key not in other: + return False + if isinstance(other[key], (dict, list)): + if not value._internal_compare(other[key]): + return False + elif value != other[key]: + return False + return True + + def keys(self): # pylint: disable=invalid-name + return self.fields.keys() + + def values(self): # pylint: disable=invalid-name + return [self[key] for key in self] + + def items(self): # pylint: disable=invalid-name + return [(key, self[key]) for key in self] + + def get_or_create_list(self, key): + """Returns a list for this key, creating if it didn't exist already.""" + if not self.fields[key].HasField('list_value'): + # Clear will mark list_value modified which will indeed create a list. + self.fields[key].list_value.Clear() + return self.fields[key].list_value + + def get_or_create_struct(self, key): + """Returns a struct for this key, creating if it didn't exist already.""" + if not self.fields[key].HasField('struct_value'): + # Clear will mark struct_value modified which will indeed create a struct. + self.fields[key].struct_value.Clear() + return self.fields[key].struct_value + + def update(self, dictionary): # pylint: disable=invalid-name + for key, value in dictionary.items(): + _SetStructValue(self.fields[key], value) + + +collections.abc.MutableMapping.register(Struct) + + +class ListValue(object): + """Class for ListValue message type.""" + + __slots__ = () + + def __len__(self): + return len(self.values) + + def append(self, value): + _SetStructValue(self.values.add(), value) + + def extend(self, elem_seq): + for value in elem_seq: + self.append(value) + + def __getitem__(self, index): + """Retrieves item by the specified index.""" + return _GetStructValue(self.values.__getitem__(index)) + + def __setitem__(self, index, value): + _SetStructValue(self.values.__getitem__(index), value) + + def __delitem__(self, key): + del self.values[key] + + def _internal_assign(self, elem_seq): + self.Clear() + self.extend(elem_seq) + + def _internal_compare(self, other): + size = len(self) + if size != len(other): + return False + for i in range(size): + if isinstance(other[i], (dict, list)): + if not self[i]._internal_compare(other[i]): + return False + elif self[i] != other[i]: + return False + return True + + def items(self): + for i in range(len(self)): + yield self[i] + + def add_struct(self): + """Appends and returns a struct value as the next value in the list.""" + struct_value = self.values.add().struct_value + # Clear will mark struct_value modified which will indeed create a struct. + struct_value.Clear() + return struct_value + + def add_list(self): + """Appends and returns a list value as the next value in the list.""" + list_value = self.values.add().list_value + # Clear will mark list_value modified which will indeed create a list. + list_value.Clear() + return list_value + + +collections.abc.MutableSequence.register(ListValue) + + +# LINT.IfChange(wktbases) +WKTBASES = { + 'google.protobuf.Any': Any, + 'google.protobuf.Duration': Duration, + 'google.protobuf.FieldMask': FieldMask, + 'google.protobuf.ListValue': ListValue, + 'google.protobuf.Struct': Struct, + 'google.protobuf.Timestamp': Timestamp, +} +# LINT.ThenChange(//depot/google.protobuf/compiler/python/pyi_generator.cc:wktbases) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/wire_format.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/wire_format.py new file mode 100644 index 0000000000000000000000000000000000000000..6237dabf950e49d2d6124340c06724f41c1c2c8d --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/internal/wire_format.py @@ -0,0 +1,245 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""Constants and static functions to support protocol buffer wire format.""" + +__author__ = 'robinson@google.com (Will Robinson)' + +import struct +from google.protobuf import descriptor +from google.protobuf import message + + +TAG_TYPE_BITS = 3 # Number of bits used to hold type info in a proto tag. +TAG_TYPE_MASK = (1 << TAG_TYPE_BITS) - 1 # 0x7 + +# These numbers identify the wire type of a protocol buffer value. +# We use the least-significant TAG_TYPE_BITS bits of the varint-encoded +# tag-and-type to store one of these WIRETYPE_* constants. +# These values must match WireType enum in //google/protobuf/wire_format.h. +WIRETYPE_VARINT = 0 +WIRETYPE_FIXED64 = 1 +WIRETYPE_LENGTH_DELIMITED = 2 +WIRETYPE_START_GROUP = 3 +WIRETYPE_END_GROUP = 4 +WIRETYPE_FIXED32 = 5 +_WIRETYPE_MAX = 5 + + +# Bounds for various integer types. +INT32_MAX = int((1 << 31) - 1) +INT32_MIN = int(-(1 << 31)) +UINT32_MAX = (1 << 32) - 1 + +INT64_MAX = (1 << 63) - 1 +INT64_MIN = -(1 << 63) +UINT64_MAX = (1 << 64) - 1 + +# "struct" format strings that will encode/decode the specified formats. +FORMAT_UINT32_LITTLE_ENDIAN = '> TAG_TYPE_BITS), (tag & TAG_TYPE_MASK) + + +def ZigZagEncode(value): + """ZigZag Transform: Encodes signed integers so that they can be + effectively used with varint encoding. See wire_format.h for + more details. + """ + if value >= 0: + return value << 1 + return (value << 1) ^ (~0) + + +def ZigZagDecode(value): + """Inverse of ZigZagEncode().""" + if not value & 0x1: + return value >> 1 + return (value >> 1) ^ (~0) + + + +# The *ByteSize() functions below return the number of bytes required to +# serialize "field number + type" information and then serialize the value. + + +def Int32ByteSize(field_number, int32): + return Int64ByteSize(field_number, int32) + + +def Int32ByteSizeNoTag(int32): + return _VarUInt64ByteSizeNoTag(0xffffffffffffffff & int32) + + +def Int64ByteSize(field_number, int64): + # Have to convert to uint before calling UInt64ByteSize(). + return UInt64ByteSize(field_number, 0xffffffffffffffff & int64) + + +def UInt32ByteSize(field_number, uint32): + return UInt64ByteSize(field_number, uint32) + + +def UInt64ByteSize(field_number, uint64): + return TagByteSize(field_number) + _VarUInt64ByteSizeNoTag(uint64) + + +def SInt32ByteSize(field_number, int32): + return UInt32ByteSize(field_number, ZigZagEncode(int32)) + + +def SInt64ByteSize(field_number, int64): + return UInt64ByteSize(field_number, ZigZagEncode(int64)) + + +def Fixed32ByteSize(field_number, fixed32): + return TagByteSize(field_number) + 4 + + +def Fixed64ByteSize(field_number, fixed64): + return TagByteSize(field_number) + 8 + + +def SFixed32ByteSize(field_number, sfixed32): + return TagByteSize(field_number) + 4 + + +def SFixed64ByteSize(field_number, sfixed64): + return TagByteSize(field_number) + 8 + + +def FloatByteSize(field_number, flt): + return TagByteSize(field_number) + 4 + + +def DoubleByteSize(field_number, double): + return TagByteSize(field_number) + 8 + + +def BoolByteSize(field_number, b): + return TagByteSize(field_number) + 1 + + +def EnumByteSize(field_number, enum): + return UInt32ByteSize(field_number, enum) + + +def StringByteSize(field_number, string): + return BytesByteSize(field_number, string.encode('utf-8')) + + +def BytesByteSize(field_number, b): + return (TagByteSize(field_number) + + _VarUInt64ByteSizeNoTag(len(b)) + + len(b)) + + +def GroupByteSize(field_number, message): + return (2 * TagByteSize(field_number) # START and END group. + + message.ByteSize()) + + +def MessageByteSize(field_number, message): + return (TagByteSize(field_number) + + _VarUInt64ByteSizeNoTag(message.ByteSize()) + + message.ByteSize()) + + +def MessageSetItemByteSize(field_number, msg): + # First compute the sizes of the tags. + # There are 2 tags for the beginning and ending of the repeated group, that + # is field number 1, one with field number 2 (type_id) and one with field + # number 3 (message). + total_size = (2 * TagByteSize(1) + TagByteSize(2) + TagByteSize(3)) + + # Add the number of bytes for type_id. + total_size += _VarUInt64ByteSizeNoTag(field_number) + + message_size = msg.ByteSize() + + # The number of bytes for encoding the length of the message. + total_size += _VarUInt64ByteSizeNoTag(message_size) + + # The size of the message. + total_size += message_size + return total_size + + +def TagByteSize(field_number): + """Returns the bytes required to serialize a tag with this field number.""" + # Just pass in type 0, since the type won't affect the tag+type size. + return _VarUInt64ByteSizeNoTag(PackTag(field_number, 0)) + + +# Private helper function for the *ByteSize() functions above. + +def _VarUInt64ByteSizeNoTag(uint64): + """Returns the number of bytes required to serialize a single varint + using boundary value comparisons. (unrolled loop optimization -WPierce) + uint64 must be unsigned. + """ + if uint64 <= 0x7f: return 1 + if uint64 <= 0x3fff: return 2 + if uint64 <= 0x1fffff: return 3 + if uint64 <= 0xfffffff: return 4 + if uint64 <= 0x7ffffffff: return 5 + if uint64 <= 0x3ffffffffff: return 6 + if uint64 <= 0x1ffffffffffff: return 7 + if uint64 <= 0xffffffffffffff: return 8 + if uint64 <= 0x7fffffffffffffff: return 9 + if uint64 > UINT64_MAX: + raise message.EncodeError('Value out of range: %d' % uint64) + return 10 + + +NON_PACKABLE_TYPES = ( + descriptor.FieldDescriptor.TYPE_STRING, + descriptor.FieldDescriptor.TYPE_GROUP, + descriptor.FieldDescriptor.TYPE_MESSAGE, + descriptor.FieldDescriptor.TYPE_BYTES +) + + +def IsTypePackable(field_type): + """Return true iff packable = true is valid for fields of this type. + + Args: + field_type: a FieldDescriptor::Type value. + + Returns: + True iff fields of this type are packable. + """ + return field_type not in NON_PACKABLE_TYPES diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/json_format.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/json_format.py new file mode 100644 index 0000000000000000000000000000000000000000..b671d3cc7c040acf4903174bb99c5824d23f6a4f --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/json_format.py @@ -0,0 +1,1114 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""Contains routines for printing protocol messages in JSON format. + +Simple usage example: + + # Create a proto object and serialize it to a json format string. + message = my_proto_pb2.MyMessage(foo='bar') + json_string = json_format.MessageToJson(message) + + # Parse a json format string to proto object. + message = json_format.Parse(json_string, my_proto_pb2.MyMessage()) +""" + +__author__ = 'jieluo@google.com (Jie Luo)' + + +import base64 +from collections import OrderedDict +import json +import math +from operator import methodcaller +import re +import warnings + +from google.protobuf import descriptor +from google.protobuf import message_factory +from google.protobuf import symbol_database +from google.protobuf.internal import type_checkers + + +_INT_TYPES = frozenset([ + descriptor.FieldDescriptor.CPPTYPE_INT32, + descriptor.FieldDescriptor.CPPTYPE_UINT32, + descriptor.FieldDescriptor.CPPTYPE_INT64, + descriptor.FieldDescriptor.CPPTYPE_UINT64, +]) +_INT64_TYPES = frozenset([ + descriptor.FieldDescriptor.CPPTYPE_INT64, + descriptor.FieldDescriptor.CPPTYPE_UINT64, +]) +_FLOAT_TYPES = frozenset([ + descriptor.FieldDescriptor.CPPTYPE_FLOAT, + descriptor.FieldDescriptor.CPPTYPE_DOUBLE, +]) +_INFINITY = 'Infinity' +_NEG_INFINITY = '-Infinity' +_NAN = 'NaN' + +_UNPAIRED_SURROGATE_PATTERN = re.compile( + '[\ud800-\udbff](?![\udc00-\udfff])|(? self.max_recursion_depth: + raise ParseError( + 'Message too deep. Max recursion depth is {0}'.format( + self.max_recursion_depth + ) + ) + message_descriptor = message.DESCRIPTOR + full_name = message_descriptor.full_name + if not path: + path = message_descriptor.name + if _IsWrapperMessage(message_descriptor): + self._ConvertWrapperMessage(value, message, path) + elif full_name in _WKTJSONMETHODS: + methodcaller(_WKTJSONMETHODS[full_name][1], value, message, path)(self) + else: + self._ConvertFieldValuePair(value, message, path) + self.recursion_depth -= 1 + + def _ConvertFieldValuePair(self, js, message, path): + """Convert field value pairs into regular message. + + Args: + js: A JSON object to convert the field value pairs. + message: A regular protocol message to record the data. + path: parent path to log parse error info. + + Raises: + ParseError: In case of problems converting. + """ + names = [] + message_descriptor = message.DESCRIPTOR + fields_by_json_name = dict( + (f.json_name, f) for f in message_descriptor.fields + ) + + def _ClearFieldOrExtension(message, field): + if field.is_extension: + message.ClearExtension(field) + else: + message.ClearField(field.name) + + def _GetFieldOrExtension(message, field): + if field.is_extension: + return message.Extensions[field] + else: + return getattr(message, field.name) + + def _SetFieldOrExtension(message, field, value): + if field.is_extension: + message.Extensions[field] = value + else: + setattr(message, field.name, value) + + for name in js: + try: + field = fields_by_json_name.get(name, None) + if not field: + field = message_descriptor.fields_by_name.get(name, None) + if not field and _VALID_EXTENSION_NAME.match(name): + if not message_descriptor.is_extendable: + raise ParseError( + 'Message type {0} does not have extensions at {1}'.format( + message_descriptor.full_name, path + ) + ) + identifier = name[1:-1] # strip [] brackets + # pylint: disable=protected-access + field = message.Extensions._FindExtensionByName(identifier) + # pylint: enable=protected-access + if not field: + # Try looking for extension by the message type name, dropping the + # field name following the final . separator in full_name. + identifier = '.'.join(identifier.split('.')[:-1]) + # pylint: disable=protected-access + field = message.Extensions._FindExtensionByName(identifier) + # pylint: enable=protected-access + if not field: + if self.ignore_unknown_fields: + continue + raise ParseError( + ( + 'Message type "{0}" has no field named "{1}" at "{2}".\n' + ' Available Fields(except extensions): "{3}"' + ).format( + message_descriptor.full_name, + name, + path, + [f.json_name for f in message_descriptor.fields], + ) + ) + if name in names: + raise ParseError( + 'Message type "{0}" should not have multiple ' + '"{1}" fields at "{2}".'.format( + message.DESCRIPTOR.full_name, name, path + ) + ) + names.append(name) + value = js[name] + # Check no other oneof field is parsed. + if field.containing_oneof is not None and value is not None: + oneof_name = field.containing_oneof.name + if oneof_name in names: + raise ParseError( + 'Message type "{0}" should not have multiple ' + '"{1}" oneof fields at "{2}".'.format( + message.DESCRIPTOR.full_name, oneof_name, path + ) + ) + names.append(oneof_name) + + if value is None: + if ( + field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE + and field.message_type.full_name == 'google.protobuf.Value' + ): + sub_message = _GetFieldOrExtension(message, field) + sub_message.null_value = 0 + elif ( + field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM + and field.enum_type.full_name == 'google.protobuf.NullValue' + ): + _SetFieldOrExtension(message, field, 0) + else: + _ClearFieldOrExtension(message, field) + continue + + # Parse field value. + if _IsMapEntry(field): + _ClearFieldOrExtension(message, field) + self._ConvertMapFieldValue( + value, message, field, '{0}.{1}'.format(path, name) + ) + elif field.is_repeated: + _ClearFieldOrExtension(message, field) + if not isinstance(value, _LIST_LIKE): + raise ParseError( + 'repeated field {0} must be in [] which is {1} at {2}'.format( + name, value, path + ) + ) + if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE: + # Repeated message field. + for index, item in enumerate(value): + sub_message = _GetFieldOrExtension(message, field).add() + # None is a null_value in Value. + if ( + item is None + and sub_message.DESCRIPTOR.full_name + != 'google.protobuf.Value' + ): + raise ParseError( + 'null is not allowed to be used as an element' + ' in a repeated field at {0}.{1}[{2}]'.format( + path, name, index + ) + ) + self.ConvertMessage( + item, sub_message, '{0}.{1}[{2}]'.format(path, name, index) + ) + else: + # Repeated scalar field. + for index, item in enumerate(value): + if item is None: + raise ParseError( + 'null is not allowed to be used as an element' + ' in a repeated field at {0}.{1}[{2}]'.format( + path, name, index + ) + ) + self._ConvertAndAppendScalar( + message, field, item, '{0}.{1}[{2}]'.format(path, name, index) + ) + elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE: + sub_message = _GetFieldOrExtension(message, field) + sub_message.SetInParent() + self.ConvertMessage(value, sub_message, '{0}.{1}'.format(path, name)) + else: + self._ConvertAndSetScalar( + message, field, value, '{0}.{1}'.format(path, name) + ) + except ParseError as e: + if field and field.containing_oneof is None: + raise ParseError( + 'Failed to parse {0} field: {1}.'.format(name, e) + ) from e + else: + raise ParseError(str(e)) from e + except ValueError as e: + raise ParseError( + 'Failed to parse {0} field: {1}.'.format(name, e) + ) from e + except TypeError as e: + raise ParseError( + 'Failed to parse {0} field: {1}.'.format(name, e) + ) from e + + def _ConvertAnyMessage(self, value, message, path): + """Convert a JSON representation into Any message.""" + if isinstance(value, dict) and not value: + return + try: + type_url = value['@type'] + except KeyError as e: + raise ParseError( + '@type is missing when parsing any message at {0}'.format(path) + ) from e + + try: + sub_message = _CreateMessageFromTypeUrl(type_url, self.descriptor_pool) + except TypeError as e: + raise ParseError('{0} at {1}'.format(e, path)) from e + message_descriptor = sub_message.DESCRIPTOR + full_name = message_descriptor.full_name + if _IsWrapperMessage(message_descriptor): + self._ConvertWrapperMessage( + value['value'], sub_message, '{0}.value'.format(path) + ) + elif full_name in _WKTJSONMETHODS: + # For well-known types (including nested Any), use ConvertMessage + # to ensure recursion depth is properly tracked + self.ConvertMessage( + value['value'], sub_message, '{0}.value'.format(path) + ) + else: + del value['@type'] + try: + self._ConvertFieldValuePair(value, sub_message, path) + finally: + value['@type'] = type_url + # Sets Any message + message.value = sub_message.SerializeToString() + message.type_url = type_url + + def _ConvertGenericMessage(self, value, message, path): + """Convert a JSON representation into message with FromJsonString.""" + # Duration, Timestamp, FieldMask have a FromJsonString method to do the + # conversion. Users can also call the method directly. + try: + message.FromJsonString(value) + except ValueError as e: + raise ParseError('{0} at {1}'.format(e, path)) from e + + def _ConvertValueMessage(self, value, message, path): + """Convert a JSON representation into Value message.""" + if isinstance(value, dict): + self._ConvertStructMessage(value, message.struct_value, path) + elif isinstance(value, _LIST_LIKE): + self._ConvertListOrTupleValueMessage(value, message.list_value, path) + elif value is None: + message.null_value = 0 + elif isinstance(value, bool): + message.bool_value = value + elif isinstance(value, str): + message.string_value = value + elif isinstance(value, _INT_OR_FLOAT): + message.number_value = value + else: + raise ParseError( + 'Value {0} has unexpected type {1} at {2}'.format( + value, type(value), path + ) + ) + + def _ConvertListOrTupleValueMessage(self, value, message, path): + """Convert a JSON representation into ListValue message.""" + if not isinstance(value, _LIST_LIKE): + raise ParseError( + 'ListValue must be in [] which is {0} at {1}'.format(value, path) + ) + message.ClearField('values') + for index, item in enumerate(value): + self._ConvertValueMessage( + item, message.values.add(), '{0}[{1}]'.format(path, index) + ) + + def _ConvertStructMessage(self, value, message, path): + """Convert a JSON representation into Struct message.""" + if not isinstance(value, dict): + raise ParseError( + 'Struct must be in a dict which is {0} at {1}'.format(value, path) + ) + # Clear will mark the struct as modified so it will be created even if + # there are no values. + message.Clear() + for key in value: + self._ConvertValueMessage( + value[key], message.fields[key], '{0}.{1}'.format(path, key) + ) + return + + def _ConvertWrapperMessage(self, value, message, path): + """Convert a JSON representation into Wrapper message.""" + field = message.DESCRIPTOR.fields_by_name['value'] + self._ConvertAndSetScalar( + message, field, value, path='{0}.value'.format(path) + ) + + def _ConvertMapFieldValue(self, value, message, field, path): + """Convert map field value for a message map field. + + Args: + value: A JSON object to convert the map field value. + message: A protocol message to record the converted data. + field: The descriptor of the map field to be converted. + path: parent path to log parse error info. + + Raises: + ParseError: In case of convert problems. + """ + if not isinstance(value, dict): + raise ParseError( + 'Map field {0} must be in a dict which is {1} at {2}'.format( + field.name, value, path + ) + ) + key_field = field.message_type.fields_by_name['key'] + value_field = field.message_type.fields_by_name['value'] + for key in value: + key_value = _ConvertScalarFieldValue( + key, key_field, '{0}.key'.format(path), True + ) + if value_field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE: + self.ConvertMessage( + value[key], + getattr(message, field.name)[key_value], + '{0}[{1}]'.format(path, key_value), + ) + else: + self._ConvertAndSetScalarToMapKey( + message, + field, + key_value, + value[key], + path='{0}[{1}]'.format(path, key_value), + ) + + def _ConvertAndSetScalar(self, message, field, js_value, path): + """Convert scalar from js_value and assign it to message.field.""" + try: + value = _ConvertScalarFieldValue(js_value, field, path) + if field.is_extension: + message.Extensions[field] = value + else: + setattr(message, field.name, value) + except EnumStringValueParseError: + if not self.ignore_unknown_fields: + raise + + def _ConvertAndAppendScalar(self, message, repeated_field, js_value, path): + """Convert scalar from js_value and append it to message.repeated_field.""" + try: + if repeated_field.is_extension: + repeated = message.Extensions[repeated_field] + else: + repeated = getattr(message, repeated_field.name) + value = _ConvertScalarFieldValue(js_value, repeated_field, path) + repeated.append(value) + except EnumStringValueParseError: + if not self.ignore_unknown_fields: + raise + + def _ConvertAndSetScalarToMapKey( + self, message, map_field, converted_key, js_value, path + ): + """Convert scalar from 'js_value' and add it to message.map_field[converted_key].""" + try: + getattr(message, map_field.name)[converted_key] = ( + _ConvertScalarFieldValue( + js_value, + map_field.message_type.fields_by_name['value'], + path, + ) + ) + except EnumStringValueParseError: + if not self.ignore_unknown_fields: + raise + + +def _ConvertScalarFieldValue(value, field, path, require_str=False): + """Convert a single scalar field value. + + Args: + value: A scalar value to convert the scalar field value. + field: The descriptor of the field to convert. + path: parent path to log parse error info. + require_str: If True, the field value must be a str. + + Returns: + The converted scalar field value + + Raises: + ParseError: In case of convert problems. + EnumStringValueParseError: In case of unknown enum string value. + """ + try: + if field.cpp_type in _INT_TYPES: + return _ConvertInteger(value) + elif field.cpp_type in _FLOAT_TYPES: + return _ConvertFloat(value, field) + elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL: + return _ConvertBool(value, require_str) + elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING: + if field.type == descriptor.FieldDescriptor.TYPE_BYTES: + if isinstance(value, str): + encoded = value.encode('utf-8') + else: + encoded = value + # Add extra padding '=' + padded_value = encoded + b'=' * (4 - len(encoded) % 4) + return base64.urlsafe_b64decode(padded_value) + else: + # Checking for unpaired surrogates appears to be unreliable, + # depending on the specific Python version, so we check manually. + if _UNPAIRED_SURROGATE_PATTERN.search(value): + raise ParseError('Unpaired surrogate') + return value + elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM: + # Convert an enum value. + enum_value = field.enum_type.values_by_name.get(value, None) + if enum_value is None: + try: + number = int(value) + enum_value = field.enum_type.values_by_number.get(number, None) + except ValueError as e: + # Since parsing to integer failed and lookup in values_by_name didn't + # find this name, we have an enum string value which is unknown. + raise EnumStringValueParseError( + 'Invalid enum value {0} for enum type {1}'.format( + value, field.enum_type.full_name + ) + ) from e + if enum_value is None: + if field.enum_type.is_closed: + raise ParseError( + 'Invalid enum value {0} for enum type {1}'.format( + value, field.enum_type.full_name + ) + ) + else: + return number + return enum_value.number + except EnumStringValueParseError as e: + raise EnumStringValueParseError('{0} at {1}'.format(e, path)) from e + except ParseError as e: + raise ParseError('{0} at {1}'.format(e, path)) from e + + +def _ConvertInteger(value): + """Convert an integer. + + Args: + value: A scalar value to convert. + + Returns: + The integer value. + + Raises: + ParseError: If an integer couldn't be consumed. + """ + if isinstance(value, float) and not value.is_integer(): + raise ParseError("Couldn't parse integer: {0}".format(value)) + + if isinstance(value, str) and value.find(' ') != -1: + raise ParseError('Couldn\'t parse integer: "{0}"'.format(value)) + + if isinstance(value, bool): + raise ParseError( + 'Bool value {0} is not acceptable for integer field'.format(value) + ) + + try: + return int(value) + except ValueError as e: + # Attempt to parse as an integer-valued float. + try: + f = float(value) + except ValueError: + # Raise the original exception for the int parse. + raise e # pylint: disable=raise-missing-from + if not f.is_integer(): + raise ParseError( + 'Couldn\'t parse non-integer string: "{0}"'.format(value) + ) from e + return int(f) + + +def _ConvertFloat(value, field): + """Convert an floating point number.""" + if isinstance(value, float): + if math.isnan(value): + raise ParseError('Couldn\'t parse NaN, use quoted "NaN" instead') + if math.isinf(value): + if value > 0: + raise ParseError( + "Couldn't parse Infinity or value too large, " + 'use quoted "Infinity" instead' + ) + else: + raise ParseError( + "Couldn't parse -Infinity or value too small, " + 'use quoted "-Infinity" instead' + ) + if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_FLOAT: + # pylint: disable=protected-access + if value > type_checkers._FLOAT_MAX: + raise ParseError('Float value too large') + # pylint: disable=protected-access + if value < type_checkers._FLOAT_MIN: + raise ParseError('Float value too small') + if value == 'nan': + raise ParseError('Couldn\'t parse float "nan", use "NaN" instead') + try: + # Assume Python compatible syntax. + return float(value) + except ValueError as e: + # Check alternative spellings. + if value == _NEG_INFINITY: + return float('-inf') + elif value == _INFINITY: + return float('inf') + elif value == _NAN: + return float('nan') + else: + raise ParseError("Couldn't parse float: {0}".format(value)) from e + + +def _ConvertBool(value, require_str): + """Convert a boolean value. + + Args: + value: A scalar value to convert. + require_str: If True, value must be a str. + + Returns: + The bool parsed. + + Raises: + ParseError: If a boolean value couldn't be consumed. + """ + if require_str: + if value == 'true': + return True + elif value == 'false': + return False + else: + raise ParseError('Expected "true" or "false", not {0}'.format(value)) + + if not isinstance(value, bool): + raise ParseError('Expected true or false without quotes') + return value + + +_WKTJSONMETHODS = { + 'google.protobuf.Any': ['_AnyMessageToJsonObject', '_ConvertAnyMessage'], + 'google.protobuf.Duration': [ + '_GenericMessageToJsonObject', + '_ConvertGenericMessage', + ], + 'google.protobuf.FieldMask': [ + '_GenericMessageToJsonObject', + '_ConvertGenericMessage', + ], + 'google.protobuf.ListValue': [ + '_ListValueMessageToJsonObject', + '_ConvertListOrTupleValueMessage', + ], + 'google.protobuf.Struct': [ + '_StructMessageToJsonObject', + '_ConvertStructMessage', + ], + 'google.protobuf.Timestamp': [ + '_GenericMessageToJsonObject', + '_ConvertGenericMessage', + ], + 'google.protobuf.Value': [ + '_ValueMessageToJsonObject', + '_ConvertValueMessage', + ], +} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/message.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/message.py new file mode 100644 index 0000000000000000000000000000000000000000..d48f4f409d055f6e47fa7985a8be0c96bdb57797 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/message.py @@ -0,0 +1,448 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +# TODO: We should just make these methods all "pure-virtual" and move +# all implementation out, into reflection.py for now. + + +"""Contains an abstract base class for protocol messages.""" + +__author__ = 'robinson@google.com (Will Robinson)' + +_INCONSISTENT_MESSAGE_ATTRIBUTES = ('Extensions',) + + +class Error(Exception): + """Base error type for this module.""" + pass + + +class DecodeError(Error): + """Exception raised when deserializing messages.""" + pass + + +class EncodeError(Error): + """Exception raised when serializing messages.""" + pass + + +class Message(object): + + """Abstract base class for protocol messages. + + Protocol message classes are almost always generated by the protocol + compiler. These generated types subclass Message and implement the methods + shown below. + """ + + # TODO: Link to an HTML document here. + + # TODO: Document that instances of this class will also + # have an Extensions attribute with __getitem__ and __setitem__. + # Again, not sure how to best convey this. + + # TODO: Document these fields and methods. + + __slots__ = [] + + #: The :class:`google.protobuf.Descriptor` + # for this message type. + DESCRIPTOR = None + + def __deepcopy__(self, memo=None): + clone = type(self)() + clone.MergeFrom(self) + return clone + + def __dir__(self): + """Provides the list of all accessible Message attributes.""" + message_attributes = set(super().__dir__()) + + # TODO: Remove this once the UPB implementation is improved. + # The UPB proto implementation currently doesn't provide proto fields as + # attributes and they have to added. + if self.DESCRIPTOR is not None: + for field in self.DESCRIPTOR.fields: + message_attributes.add(field.name) + + # The Fast C++ proto implementation provides inaccessible attributes that + # have to be removed. + for attribute in _INCONSISTENT_MESSAGE_ATTRIBUTES: + if attribute not in message_attributes: + continue + try: + getattr(self, attribute) + except AttributeError: + message_attributes.remove(attribute) + + return sorted(message_attributes) + + def __eq__(self, other_msg): + """Recursively compares two messages by value and structure.""" + raise NotImplementedError + + def __ne__(self, other_msg): + # Can't just say self != other_msg, since that would infinitely recurse. :) + return not self == other_msg + + def __hash__(self): + raise TypeError('unhashable object') + + def __str__(self): + """Outputs a human-readable representation of the message.""" + raise NotImplementedError + + def __unicode__(self): + """Outputs a human-readable representation of the message.""" + raise NotImplementedError + + def __contains__(self, field_name_or_key): + """Checks if a certain field is set for the message. + + Has presence fields return true if the field is set, false if the field is + not set. Fields without presence do raise `ValueError` (this includes + repeated fields, map fields, and implicit presence fields). + + If field_name is not defined in the message descriptor, `ValueError` will + be raised. + Note: WKT Struct checks if the key is contained in fields. ListValue checks + if the item is contained in the list. + + Args: + field_name_or_key: For Struct, the key (str) of the fields map. For + ListValue, any type that may be contained in the list. For other + messages, name of the field (str) to check for presence. + + Returns: + bool: For Struct, whether the item is contained in fields. For ListValue, + whether the item is contained in the list. For other message, + whether a value has been set for the named field. + + Raises: + ValueError: For normal messages, if the `field_name_or_key` is not a + member of this message or `field_name_or_key` is not a string. + """ + raise NotImplementedError + + def MergeFrom(self, other_msg): + """Merges the contents of the specified message into current message. + + This method merges the contents of the specified message into the current + message. Singular fields that are set in the specified message overwrite + the corresponding fields in the current message. Repeated fields are + appended. Singular sub-messages and groups are recursively merged. + + Args: + other_msg (Message): A message to merge into the current message. + """ + raise NotImplementedError + + def CopyFrom(self, other_msg): + """Copies the content of the specified message into the current message. + + The method clears the current message and then merges the specified + message using MergeFrom. + + Args: + other_msg (Message): A message to copy into the current one. + """ + if self is other_msg: + return + self.Clear() + self.MergeFrom(other_msg) + + def Clear(self): + """Clears all data that was set in the message.""" + raise NotImplementedError + + def SetInParent(self): + """Mark this as present in the parent. + + This normally happens automatically when you assign a field of a + sub-message, but sometimes you want to make the sub-message + present while keeping it empty. If you find yourself using this, + you may want to reconsider your design. + """ + raise NotImplementedError + + def IsInitialized(self): + """Checks if the message is initialized. + + Returns: + bool: The method returns True if the message is initialized (i.e. all of + its required fields are set). + """ + raise NotImplementedError + + # TODO: MergeFromString() should probably return None and be + # implemented in terms of a helper that returns the # of bytes read. Our + # deserialization routines would use the helper when recursively + # deserializing, but the end user would almost always just want the no-return + # MergeFromString(). + + def MergeFromString(self, serialized): + """Merges serialized protocol buffer data into this message. + + When we find a field in `serialized` that is already present + in this message: + + - If it's a "repeated" field, we append to the end of our list. + - Else, if it's a scalar, we overwrite our field. + - Else, (it's a nonrepeated composite), we recursively merge + into the existing composite. + + Args: + serialized (bytes): Any object that allows us to call + ``memoryview(serialized)`` to access a string of bytes using the + buffer interface. + + Returns: + int: The number of bytes read from `serialized`. + For non-group messages, this will always be `len(serialized)`, + but for messages which are actually groups, this will + generally be less than `len(serialized)`, since we must + stop when we reach an ``END_GROUP`` tag. Note that if + we *do* stop because of an ``END_GROUP`` tag, the number + of bytes returned does not include the bytes + for the ``END_GROUP`` tag information. + + Raises: + DecodeError: if the input cannot be parsed. + """ + # TODO: Document handling of unknown fields. + # TODO: When we switch to a helper, this will return None. + raise NotImplementedError + + def ParseFromString(self, serialized): + """Parse serialized protocol buffer data in binary form into this message. + + Like :func:`MergeFromString()`, except we clear the object first. + + Raises: + message.DecodeError if the input cannot be parsed. + """ + self.Clear() + return self.MergeFromString(serialized) + + def SerializeToString(self, **kwargs): + """Serializes the protocol message to a binary string. + + Keyword Args: + deterministic (bool): If true, requests deterministic serialization + of the protobuf, with predictable ordering of map keys. + + Returns: + A binary string representation of the message if all of the required + fields in the message are set (i.e. the message is initialized). + + Raises: + EncodeError: if the message isn't initialized (see :func:`IsInitialized`). + """ + raise NotImplementedError + + def SerializePartialToString(self, **kwargs): + """Serializes the protocol message to a binary string. + + This method is similar to SerializeToString but doesn't check if the + message is initialized. + + Keyword Args: + deterministic (bool): If true, requests deterministic serialization + of the protobuf, with predictable ordering of map keys. + + Returns: + bytes: A serialized representation of the partial message. + """ + raise NotImplementedError + + # TODO: Decide whether we like these better + # than auto-generated has_foo() and clear_foo() methods + # on the instances themselves. This way is less consistent + # with C++, but it makes reflection-type access easier and + # reduces the number of magically autogenerated things. + # + # TODO: Be sure to document (and test) exactly + # which field names are accepted here. Are we case-sensitive? + # What do we do with fields that share names with Python keywords + # like 'lambda' and 'yield'? + # + # nnorwitz says: + # """ + # Typically (in python), an underscore is appended to names that are + # keywords. So they would become lambda_ or yield_. + # """ + def ListFields(self): + """Returns a list of (FieldDescriptor, value) tuples for present fields. + + A message field is non-empty if HasField() would return true. A singular + primitive field is non-empty if HasField() would return true in proto2 or it + is non zero in proto3. A repeated field is non-empty if it contains at least + one element. The fields are ordered by field number. + + Returns: + list[tuple(FieldDescriptor, value)]: field descriptors and values + for all fields in the message which are not empty. The values vary by + field type. + """ + raise NotImplementedError + + def HasField(self, field_name): + """Checks if a certain field is set for the message. + + For a oneof group, checks if any field inside is set. Note that if the + field_name is not defined in the message descriptor, :exc:`ValueError` will + be raised. + + Args: + field_name (str): The name of the field to check for presence. + + Returns: + bool: Whether a value has been set for the named field. + + Raises: + ValueError: if the `field_name` is not a member of this message. + """ + raise NotImplementedError + + def ClearField(self, field_name): + """Clears the contents of a given field. + + Inside a oneof group, clears the field set. If the name neither refers to a + defined field or oneof group, :exc:`ValueError` is raised. + + Args: + field_name (str): The name of the field to check for presence. + + Raises: + ValueError: if the `field_name` is not a member of this message. + """ + raise NotImplementedError + + def WhichOneof(self, oneof_group): + """Returns the name of the field that is set inside a oneof group. + + If no field is set, returns None. + + Args: + oneof_group (str): the name of the oneof group to check. + + Returns: + str or None: The name of the group that is set, or None. + + Raises: + ValueError: no group with the given name exists + """ + raise NotImplementedError + + def HasExtension(self, field_descriptor): + """Checks if a certain extension is present for this message. + + Extensions are retrieved using the :attr:`Extensions` mapping (if present). + + Args: + field_descriptor: The field descriptor for the extension to check. + + Returns: + bool: Whether the extension is present for this message. + + Raises: + KeyError: if the extension is repeated. Similar to repeated fields, + there is no separate notion of presence: a "not present" repeated + extension is an empty list. + """ + raise NotImplementedError + + def ClearExtension(self, field_descriptor): + """Clears the contents of a given extension. + + Args: + field_descriptor: The field descriptor for the extension to clear. + """ + raise NotImplementedError + + def UnknownFields(self): + """Returns the UnknownFieldSet. + + Returns: + UnknownFieldSet: The unknown fields stored in this message. + """ + raise NotImplementedError + + def DiscardUnknownFields(self): + """Clears all fields in the :class:`UnknownFieldSet`. + + This operation is recursive for nested message. + """ + raise NotImplementedError + + def ByteSize(self): + """Returns the serialized size of this message. + + Recursively calls ByteSize() on all contained messages. + + Returns: + int: The number of bytes required to serialize this message. + """ + raise NotImplementedError + + @classmethod + def FromString(cls, s): + raise NotImplementedError + + def _SetListener(self, message_listener): + """Internal method used by the protocol message implementation. + Clients should not call this directly. + + Sets a listener that this message will call on certain state transitions. + + The purpose of this method is to register back-edges from children to + parents at runtime, for the purpose of setting "has" bits and + byte-size-dirty bits in the parent and ancestor objects whenever a child or + descendant object is modified. + + If the client wants to disconnect this Message from the object tree, she + explicitly sets callback to None. + + If message_listener is None, unregisters any existing listener. Otherwise, + message_listener must implement the MessageListener interface in + internal/message_listener.py, and we discard any listener registered + via a previous _SetListener() call. + """ + raise NotImplementedError + + def __getstate__(self): + """Support the pickle protocol.""" + return dict(serialized=self.SerializePartialToString()) + + def __setstate__(self, state): + """Support the pickle protocol.""" + self.__init__() + serialized = state['serialized'] + # On Python 3, using encoding='latin1' is required for unpickling + # protos pickled by Python 2. + if not isinstance(serialized, bytes): + serialized = serialized.encode('latin1') + self.ParseFromString(serialized) + + def __reduce__(self): + message_descriptor = self.DESCRIPTOR + if message_descriptor.containing_type is None: + return type(self), (), self.__getstate__() + # the message type must be nested. + # Python does not pickle nested classes; use the symbol_database on the + # receiving end. + container = message_descriptor + return (_InternalConstructMessage, (container.full_name,), + self.__getstate__()) + + +def _InternalConstructMessage(full_name): + """Constructs a nested message.""" + from google.protobuf import symbol_database # pylint:disable=g-import-not-at-top + + return symbol_database.Default().GetSymbol(full_name)() diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/message_factory.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/message_factory.py new file mode 100644 index 0000000000000000000000000000000000000000..3bc4d92867c08199a582d515e6e326e3bc29ce82 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/message_factory.py @@ -0,0 +1,190 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""Provides a factory class for generating dynamic messages. + +The easiest way to use this class is if you have access to the FileDescriptor +protos containing the messages you want to create you can just do the following: + +message_classes = message_factory.GetMessages(iterable_of_file_descriptors) +my_proto_instance = message_classes['some.proto.package.MessageName']() +""" + +__author__ = 'matthewtoia@google.com (Matt Toia)' + +import warnings + +from google.protobuf import descriptor_pool +from google.protobuf import message +from google.protobuf.internal import api_implementation + +if api_implementation.Type() == 'python': + from google.protobuf.internal import python_message as message_impl +else: + from google.protobuf.pyext import cpp_message as message_impl # pylint: disable=g-import-not-at-top + + +# The type of all Message classes. +_GENERATED_PROTOCOL_MESSAGE_TYPE = message_impl.GeneratedProtocolMessageType + + +def GetMessageClass(descriptor): + """Obtains a proto2 message class based on the passed in descriptor. + + Passing a descriptor with a fully qualified name matching a previous + invocation will cause the same class to be returned. + + Args: + descriptor: The descriptor to build from. + + Returns: + A class describing the passed in descriptor. + """ + concrete_class = getattr(descriptor, '_concrete_class', None) + if concrete_class: + return concrete_class + return _InternalCreateMessageClass(descriptor) + + +def GetMessageClassesForFiles(files, pool): + """Gets all the messages from specified files. + + This will find and resolve dependencies, failing if the descriptor + pool cannot satisfy them. + + This will not return the classes for nested types within those classes, for + those, use GetMessageClass() on the nested types within their containing + messages. + + For example, for the message: + + message NestedTypeMessage { + message NestedType { + string data = 1; + } + NestedType nested = 1; + } + + NestedTypeMessage will be in the result, but not + NestedTypeMessage.NestedType. + + Args: + files: The file names to extract messages from. + pool: The descriptor pool to find the files including the dependent files. + + Returns: + A dictionary mapping proto names to the message classes. + """ + result = {} + for file_name in files: + file_desc = pool.FindFileByName(file_name) + for desc in file_desc.message_types_by_name.values(): + result[desc.full_name] = GetMessageClass(desc) + + # While the extension FieldDescriptors are created by the descriptor pool, + # the python classes created in the factory need them to be registered + # explicitly, which is done below. + # + # The call to RegisterExtension will specifically check if the + # extension was already registered on the object and either + # ignore the registration if the original was the same, or raise + # an error if they were different. + + for extension in file_desc.extensions_by_name.values(): + _ = GetMessageClass(extension.containing_type) + if api_implementation.Type() != 'python': + # TODO: Remove this check here. Duplicate extension + # register check should be in descriptor_pool. + if extension is not pool.FindExtensionByNumber( + extension.containing_type, extension.number + ): + raise ValueError('Double registration of Extensions') + # Recursively load protos for extension field, in order to be able to + # fully represent the extension. This matches the behavior for regular + # fields too. + if extension.message_type: + GetMessageClass(extension.message_type) + return result + + +def _InternalCreateMessageClass(descriptor): + """Builds a proto2 message class based on the passed in descriptor. + + Args: + descriptor: The descriptor to build from. + + Returns: + A class describing the passed in descriptor. + """ + descriptor_name = descriptor.name + result_class = _GENERATED_PROTOCOL_MESSAGE_TYPE( + descriptor_name, + (message.Message,), + { + 'DESCRIPTOR': descriptor, + # If module not set, it wrongly points to message_factory module. + '__module__': None, + }, + ) + for field in descriptor.fields: + if field.message_type: + GetMessageClass(field.message_type) + + for extension in result_class.DESCRIPTOR.extensions: + extended_class = GetMessageClass(extension.containing_type) + if api_implementation.Type() != 'python': + # TODO: Remove this check here. Duplicate extension + # register check should be in descriptor_pool. + pool = extension.containing_type.file.pool + if extension is not pool.FindExtensionByNumber( + extension.containing_type, extension.number + ): + raise ValueError('Double registration of Extensions') + if extension.message_type: + GetMessageClass(extension.message_type) + return result_class + + +# Deprecated. Please use GetMessageClass() or GetMessageClassesForFiles() +# method above instead. +class MessageFactory(object): + """Factory for creating Proto2 messages from descriptors in a pool.""" + + def __init__(self, pool=None): + """Initializes a new factory.""" + self.pool = pool or descriptor_pool.DescriptorPool() + + +def GetMessages(file_protos, pool=None): + """Builds a dictionary of all the messages available in a set of files. + + Args: + file_protos: Iterable of FileDescriptorProto to build messages out of. + pool: The descriptor pool to add the file protos. + + Returns: + A dictionary mapping proto names to the message classes. This will include + any dependent messages as well as any messages defined in the same file as + a specified message. + """ + # The cpp implementation of the protocol buffer library requires to add the + # message in topological order of the dependency graph. + des_pool = pool or descriptor_pool.DescriptorPool() + file_by_name = {file_proto.name: file_proto for file_proto in file_protos} + + def _AddFile(file_proto): + for dependency in file_proto.dependency: + if dependency in file_by_name: + # Remove from elements to be visited, in order to cut cycles. + _AddFile(file_by_name.pop(dependency)) + des_pool.Add(file_proto) + + while file_by_name: + _AddFile(file_by_name.popitem()[1]) + return GetMessageClassesForFiles( + [file_proto.name for file_proto in file_protos], des_pool + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/proto.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/proto.py new file mode 100644 index 0000000000000000000000000000000000000000..1e6291c3ae4a6908b66437648e6f550e1113acc0 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/proto.py @@ -0,0 +1,153 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""Contains the Nextgen Pythonic protobuf APIs.""" + +import io +from typing import Text, Type, TypeVar + +from google.protobuf.internal import decoder +from google.protobuf.internal import encoder +from google.protobuf.message import Message + +_MESSAGE = TypeVar('_MESSAGE', bound='Message') + + +def serialize(message: _MESSAGE, deterministic: bool = None) -> bytes: + """Return the serialized proto. + + Args: + message: The proto message to be serialized. + deterministic: If true, requests deterministic serialization + of the protobuf, with predictable ordering of map keys. + + Returns: + A binary bytes representation of the message. + """ + return message.SerializeToString(deterministic=deterministic) + + +def parse(message_class: Type[_MESSAGE], payload: bytes) -> _MESSAGE: + """Given a serialized data in binary form, deserialize it into a Message. + + Args: + message_class: The message meta class. + payload: A serialized bytes in binary form. + + Returns: + A new message deserialized from payload. + """ + new_message = message_class() + new_message.ParseFromString(payload) + return new_message + + +def serialize_length_prefixed(message: _MESSAGE, output: io.BytesIO) -> None: + """Writes the size of the message as a varint and the serialized message. + + Writes the size of the message as a varint and then the serialized message. + This allows more data to be written to the output after the message. Use + parse_length_prefixed to parse messages written by this method. + + The output stream must be buffered, e.g. using + https://docs.python.org/3/library/io.html#buffered-streams. + + Example usage: + out = io.BytesIO() + for msg in message_list: + proto.serialize_length_prefixed(msg, out) + + Args: + message: The protocol buffer message that should be serialized. + output: BytesIO or custom buffered IO that data should be written to. + """ + size = message.ByteSize() + encoder._VarintEncoder()(output.write, size) + out_size = output.write(serialize(message)) + + if out_size != size: + raise TypeError( + 'Failed to write complete message (wrote: %d, expected: %d)' + '. Ensure output is using buffered IO.' % (out_size, size) + ) + + +def parse_length_prefixed( + message_class: Type[_MESSAGE], input_bytes: io.BytesIO +) -> _MESSAGE: + """Parse a message from input_bytes. + + Args: + message_class: The protocol buffer message class that parser should parse. + input_bytes: A buffered input. + + Example usage: + while True: + msg = proto.parse_length_prefixed(message_class, input_bytes) + if msg is None: + break + ... + + Returns: + A parsed message if successful. None if input_bytes is at EOF. + """ + size = decoder._DecodeVarint(input_bytes) + if size is None: + # It is the end of buffered input. See example usage in the + # API description. + return None + + message = message_class() + + if size == 0: + return message + + parsed_size = message.ParseFromString(input_bytes.read(size)) + if parsed_size != size: + raise ValueError( + 'Truncated message or non-buffered input_bytes: ' + 'Expected {0} bytes but only {1} bytes parsed for ' + '{2}.'.format(size, parsed_size, message.DESCRIPTOR.name) + ) + return message + + +def byte_size(message: Message) -> int: + """Returns the serialized size of this message. + + Args: + message: A proto message. + + Returns: + int: The number of bytes required to serialize this message. + """ + return message.ByteSize() + + +def clear_message(message: Message) -> None: + """Clears all data that was set in the message. + + Args: + message: The proto message to be cleared. + """ + message.Clear() + + +def clear_field(message: Message, field_name: Text) -> None: + """Clears the contents of a given field. + + Inside a oneof group, clears the field set. If the name neither refers to a + defined field or oneof group, :exc:`ValueError` is raised. + + Args: + message: The proto message. + field_name (str): The name of the field to be cleared. + + Raises: + ValueError: if the `field_name` is not a member of this message. + """ + message.ClearField(field_name) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/proto_builder.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/proto_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..803d0040a99b6347d12c1e3891e0928ec8a4751f --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/proto_builder.py @@ -0,0 +1,111 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""Dynamic Protobuf class creator.""" + +from collections import OrderedDict +import hashlib +import os + +from google.protobuf import descriptor_pb2 +from google.protobuf import descriptor +from google.protobuf import descriptor_pool +from google.protobuf import message_factory + + +def _GetMessageFromFactory(pool, full_name): + """Get a proto class from the MessageFactory by name. + + Args: + pool: a descriptor pool. + full_name: str, the fully qualified name of the proto type. + Returns: + A class, for the type identified by full_name. + Raises: + KeyError, if the proto is not found in the factory's descriptor pool. + """ + proto_descriptor = pool.FindMessageTypeByName(full_name) + proto_cls = message_factory.GetMessageClass(proto_descriptor) + return proto_cls + + +def MakeSimpleProtoClass(fields, full_name=None, pool=None): + """Create a Protobuf class whose fields are basic types. + + Note: this doesn't validate field names! + + Args: + fields: dict of {name: field_type} mappings for each field in the proto. If + this is an OrderedDict the order will be maintained, otherwise the + fields will be sorted by name. + full_name: optional str, the fully-qualified name of the proto type. + pool: optional DescriptorPool instance. + Returns: + a class, the new protobuf class with a FileDescriptor. + """ + pool_instance = pool or descriptor_pool.DescriptorPool() + if full_name is not None: + try: + proto_cls = _GetMessageFromFactory(pool_instance, full_name) + return proto_cls + except KeyError: + # The factory's DescriptorPool doesn't know about this class yet. + pass + + # Get a list of (name, field_type) tuples from the fields dict. If fields was + # an OrderedDict we keep the order, but otherwise we sort the field to ensure + # consistent ordering. + field_items = fields.items() + if not isinstance(fields, OrderedDict): + field_items = sorted(field_items) + + # Use a consistent file name that is unlikely to conflict with any imported + # proto files. + fields_hash = hashlib.sha1() + for f_name, f_type in field_items: + fields_hash.update(f_name.encode('utf-8')) + fields_hash.update(str(f_type).encode('utf-8')) + proto_file_name = fields_hash.hexdigest() + '.proto' + + # If the proto is anonymous, use the same hash to name it. + if full_name is None: + full_name = ('net.proto2.python.public.proto_builder.AnonymousProto_' + + fields_hash.hexdigest()) + try: + proto_cls = _GetMessageFromFactory(pool_instance, full_name) + return proto_cls + except KeyError: + # The factory's DescriptorPool doesn't know about this class yet. + pass + + # This is the first time we see this proto: add a new descriptor to the pool. + pool_instance.Add( + _MakeFileDescriptorProto(proto_file_name, full_name, field_items)) + return _GetMessageFromFactory(pool_instance, full_name) + + +def _MakeFileDescriptorProto(proto_file_name, full_name, field_items): + """Populate FileDescriptorProto for MessageFactory's DescriptorPool.""" + package, name = full_name.rsplit('.', 1) + file_proto = descriptor_pb2.FileDescriptorProto() + file_proto.name = os.path.join(package.replace('.', '/'), proto_file_name) + file_proto.package = package + desc_proto = file_proto.message_type.add() + desc_proto.name = name + for f_number, (f_name, f_type) in enumerate(field_items, 1): + field_proto = desc_proto.field.add() + field_proto.name = f_name + # # If the number falls in the reserved range, reassign it to the correct + # # number after the range. + if f_number >= descriptor.FieldDescriptor.FIRST_RESERVED_FIELD_NUMBER: + f_number += ( + descriptor.FieldDescriptor.LAST_RESERVED_FIELD_NUMBER - + descriptor.FieldDescriptor.FIRST_RESERVED_FIELD_NUMBER + 1) + field_proto.number = f_number + field_proto.label = descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL + field_proto.type = f_type + return file_proto diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/proto_json.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/proto_json.py new file mode 100644 index 0000000000000000000000000000000000000000..ea670ab0810bfcb43abdc0b1ef71fbfdf95ecc68 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/proto_json.py @@ -0,0 +1,83 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""Contains the Nextgen Pythonic Protobuf JSON APIs.""" + +from typing import Optional, Type + +from google.protobuf.message import Message +from google.protobuf.descriptor_pool import DescriptorPool +from google.protobuf import json_format + +def serialize( + message: Message, + always_print_fields_with_no_presence: bool=False, + preserving_proto_field_name: bool=False, + use_integers_for_enums: bool=False, + descriptor_pool: Optional[DescriptorPool]=None, + float_precision: int=None, +) -> dict: + """Converts protobuf message to a dictionary. + + When the dictionary is encoded to JSON, it conforms to proto3 JSON spec. + + Args: + message: The protocol buffers message instance to serialize. + always_print_fields_with_no_presence: If True, fields without + presence (implicit presence scalars, repeated fields, and map fields) will + always be serialized. Any field that supports presence is not affected by + this option (including singular message fields and oneof fields). + preserving_proto_field_name: If True, use the original proto field names as + defined in the .proto file. If False, convert the field names to + lowerCamelCase. + use_integers_for_enums: If true, print integers instead of enum names. + descriptor_pool: A Descriptor Pool for resolving types. If None use the + default. + float_precision: If set, use this to specify float field valid digits. + + Returns: + A dict representation of the protocol buffer message. + """ + return json_format.MessageToDict( + message, + always_print_fields_with_no_presence=always_print_fields_with_no_presence, + preserving_proto_field_name=preserving_proto_field_name, + use_integers_for_enums=use_integers_for_enums, + float_precision=float_precision, + ) + +def parse( + message_class: Type[Message], + js_dict: dict, + ignore_unknown_fields: bool=False, + descriptor_pool: Optional[DescriptorPool]=None, + max_recursion_depth: int=100 +) -> Message: + """Parses a JSON dictionary representation into a message. + + Args: + message_class: The message meta class. + js_dict: Dict representation of a JSON message. + ignore_unknown_fields: If True, do not raise errors for unknown fields. + descriptor_pool: A Descriptor Pool for resolving types. If None use the + default. + max_recursion_depth: max recursion depth of JSON message to be deserialized. + JSON messages over this depth will fail to be deserialized. Default value + is 100. + + Returns: + A new message passed from json_dict. + """ + new_message = message_class() + json_format.ParseDict( + js_dict=js_dict, + message=new_message, + ignore_unknown_fields=ignore_unknown_fields, + descriptor_pool=descriptor_pool, + max_recursion_depth=max_recursion_depth, + ) + return new_message diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/proto_text.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/proto_text.py new file mode 100644 index 0000000000000000000000000000000000000000..169fb4fce21f9ed8afdc90ec64abf0b784a3c60f --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/proto_text.py @@ -0,0 +1,129 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2025 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""Contains the Nextgen Pythonic Protobuf Text Format APIs.""" +from typing import AnyStr, Callable, Optional, Text, Type, Union + +from google.protobuf import text_format +from google.protobuf.descriptor_pool import DescriptorPool +from google.protobuf.message import Message + +_MsgFormatter = Callable[[Message, Union[int, bool], bool], Optional[Text]] + + +def serialize( + message: Message, + as_utf8: bool = True, + as_one_line: bool = False, + use_short_repeated_primitives: bool = False, + pointy_brackets: bool = False, + use_index_order: bool = False, + float_format: Optional[str] = None, + double_format: Optional[str] = None, + use_field_number: bool = False, + descriptor_pool: Optional[DescriptorPool] = None, + indent: int = 0, + message_formatter: Optional[_MsgFormatter] = None, + print_unknown_fields: bool = False, + force_colon: bool = False, +) -> str: + """Convert protobuf message to text format. + + Double values can be formatted compactly with 15 digits of + precision (which is the most that IEEE 754 "double" can guarantee) + using double_format='.15g'. To ensure that converting to text and back to a + proto will result in an identical value, double_format='.17g' should be used. + + Args: + message: The protocol buffers message. + as_utf8: Return unescaped Unicode for non-ASCII characters. + as_one_line: Don't introduce newlines between fields. + use_short_repeated_primitives: Use short repeated format for primitives. + pointy_brackets: If True, use angle brackets instead of curly braces for + nesting. + use_index_order: If True, fields of a proto message will be printed using + the order defined in source code instead of the field number, extensions + will be printed at the end of the message and their relative order is + determined by the extension number. By default, use the field number + order. + float_format (str): If set, use this to specify float field formatting (per + the "Format Specification Mini-Language"); otherwise, shortest float that + has same value in wire will be printed. Also affect double field if + double_format is not set but float_format is set. + double_format (str): If set, use this to specify double field formatting + (per the "Format Specification Mini-Language"); if it is not set but + float_format is set, use float_format. Otherwise, use ``str()`` + use_field_number: If True, print field numbers instead of names. + descriptor_pool (DescriptorPool): Descriptor pool used to resolve Any types. + indent (int): The initial indent level, in terms of spaces, for pretty + print. + message_formatter (function(message, indent, as_one_line) -> unicode|None): + Custom formatter for selected sub-messages (usually based on message + type). Use to pretty print parts of the protobuf for easier diffing. + print_unknown_fields: If True, unknown fields will be printed. + force_colon: If set, a colon will be added after the field name even if the + field is a proto message. + + Returns: + str: A string of the text formatted protocol buffer message. + """ + return text_format.MessageToString( + message=message, + as_utf8=as_utf8, + as_one_line=as_one_line, + use_short_repeated_primitives=use_short_repeated_primitives, + pointy_brackets=pointy_brackets, + use_index_order=use_index_order, + float_format=float_format, + double_format=double_format, + use_field_number=use_field_number, + descriptor_pool=descriptor_pool, + indent=indent, + message_formatter=message_formatter, + print_unknown_fields=print_unknown_fields, + force_colon=force_colon, + ) + + +def parse( + message_class: Type[Message], + text: AnyStr, + allow_unknown_extension: bool = False, + allow_field_number: bool = False, + descriptor_pool: Optional[DescriptorPool] = None, + allow_unknown_field: bool = False, +) -> Message: + """Parses a text representation of a protocol message into a message. + + Args: + message_class: The message meta class. + text (str): Message text representation. + message (Message): A protocol buffer message to merge into. + allow_unknown_extension: if True, skip over missing extensions and keep + parsing + allow_field_number: if True, both field number and field name are allowed. + descriptor_pool (DescriptorPool): Descriptor pool used to resolve Any types. + allow_unknown_field: if True, skip over unknown field and keep parsing. + Avoid to use this option if possible. It may hide some errors (e.g. + spelling error on field name) + + Returns: + Message: A new message passed from text. + + Raises: + ParseError: On text parsing problems. + """ + new_message = message_class() + text_format.Parse( + text=text, + message=new_message, + allow_unknown_extension=allow_unknown_extension, + allow_field_number=allow_field_number, + descriptor_pool=descriptor_pool, + allow_unknown_field=allow_unknown_field, + ) + return new_message diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/pyext/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/pyext/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/pyext/__pycache__/__init__.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/pyext/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c8f8f6dcc96b3afd532901f927d047cda49bece Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/pyext/__pycache__/__init__.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/pyext/__pycache__/cpp_message.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/pyext/__pycache__/cpp_message.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1d187ce70dea8a29b3e4262817f4d0f1e3b1ca7d Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/pyext/__pycache__/cpp_message.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/pyext/cpp_message.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/pyext/cpp_message.py new file mode 100644 index 0000000000000000000000000000000000000000..54cfe30646aaaed023e4b6228ad291aa7c53d147 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/pyext/cpp_message.py @@ -0,0 +1,49 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""Protocol message implementation hooks for C++ implementation. + +Contains helper functions used to create protocol message classes from +Descriptor objects at runtime backed by the protocol buffer C++ API. +""" + +__author__ = 'tibell@google.com (Johan Tibell)' + +from google.protobuf.internal import api_implementation + + +# pylint: disable=protected-access +_message = api_implementation._c_module +# TODO: Remove this import after fix api_implementation +if _message is None: + from google.protobuf.pyext import _message + + +class GeneratedProtocolMessageType(_message.MessageMeta): + + """Metaclass for protocol message classes created at runtime from Descriptors. + + The protocol compiler currently uses this metaclass to create protocol + message classes at runtime. Clients can also manually create their own + classes at runtime, as in this example: + + mydescriptor = Descriptor(.....) + factory = symbol_database.Default() + factory.pool.AddDescriptor(mydescriptor) + MyProtoClass = message_factory.GetMessageClass(mydescriptor) + myproto_instance = MyProtoClass() + myproto.foo_field = 23 + ... + + The above example will not work for nested types. If you wish to include them, + use reflection.MakeClass() instead of manually instantiating the class in + order to create the appropriate class structure. + """ + + # Must be consistent with the protocol-compiler code in + # proto2/compiler/internal/generator.*. + _DESCRIPTOR_KEY = 'DESCRIPTOR' diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/reflection.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/reflection.py new file mode 100644 index 0000000000000000000000000000000000000000..a29f41a0527c78f437ecb564d8291a7485413a06 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/reflection.py @@ -0,0 +1,36 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +# This code is meant to work on Python 2.4 and above only. + +"""Contains a metaclass and helper functions used to create +protocol message classes from Descriptor objects at runtime. + +Recall that a metaclass is the "type" of a class. +(A class is to a metaclass what an instance is to a class.) + +In this case, we use the GeneratedProtocolMessageType metaclass +to inject all the useful functionality into the classes +output by the protocol compiler at compile-time. + +The upshot of all this is that the real implementation +details for ALL pure-Python protocol buffers are *here in +this file*. +""" + +__author__ = 'robinson@google.com (Will Robinson)' + +import warnings + +from google.protobuf import message_factory +from google.protobuf import symbol_database + +# The type of all Message classes. +# Part of the public interface, but normally only used by message factories. +GeneratedProtocolMessageType = message_factory._GENERATED_PROTOCOL_MESSAGE_TYPE + +MESSAGE_CLASS_CACHE = {} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/runtime_version.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/runtime_version.py new file mode 100644 index 0000000000000000000000000000000000000000..a699f2a3a3d550d8b4e5b3904c90cd03e4ea4eac --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/runtime_version.py @@ -0,0 +1,104 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""Protobuf Runtime versions and validators. + +It should only be accessed by Protobuf gencodes and tests. DO NOT USE it +elsewhere. +""" + +__author__ = 'shaod@google.com (Dennis Shao)' + +from enum import Enum +import os +import warnings + + +class Domain(Enum): + GOOGLE_INTERNAL = 1 + PUBLIC = 2 + + +# The versions of this Python Protobuf runtime to be changed automatically by +# the Protobuf release process. Do not edit them manually. +# These OSS versions are not stripped to avoid merging conflicts. +OSS_DOMAIN = Domain.PUBLIC +OSS_MAJOR = 6 +OSS_MINOR = 33 +OSS_PATCH = 6 +OSS_SUFFIX = '' + +DOMAIN = OSS_DOMAIN +MAJOR = OSS_MAJOR +MINOR = OSS_MINOR +PATCH = OSS_PATCH +SUFFIX = OSS_SUFFIX + +# Avoid flooding of warnings. +_MAX_WARNING_COUNT = 20 +_warning_count = 0 + +class VersionError(Exception): + """Exception class for version violation.""" + + +def _ReportVersionError(msg): + raise VersionError(msg) + + +def ValidateProtobufRuntimeVersion( + gen_domain, gen_major, gen_minor, gen_patch, gen_suffix, location +): + """Function to validate versions. + + Args: + gen_domain: The domain where the code was generated from. + gen_major: The major version number of the gencode. + gen_minor: The minor version number of the gencode. + gen_patch: The patch version number of the gencode. + gen_suffix: The version suffix e.g. '-dev', '-rc1' of the gencode. + location: The proto location that causes the version violation. + + Raises: + VersionError: if gencode version is invalid or incompatible with the + runtime. + """ + + disable_flag = os.getenv('TEMPORARILY_DISABLE_PROTOBUF_VERSION_CHECK') + if disable_flag is not None and disable_flag.lower() == 'true': + return + + global _warning_count + + version = f'{MAJOR}.{MINOR}.{PATCH}{SUFFIX}' + gen_version = f'{gen_major}.{gen_minor}.{gen_patch}{gen_suffix}' + + if gen_major < 0 or gen_minor < 0 or gen_patch < 0: + raise VersionError(f'Invalid gencode version: {gen_version}') + + error_prompt = ( + 'See Protobuf version guarantees at' + ' https://protobuf.dev/support/cross-version-runtime-guarantee.' + ) + + if gen_domain != DOMAIN: + _ReportVersionError( + 'Detected mismatched Protobuf Gencode/Runtime domains when loading' + f' {location}: gencode {gen_domain.name} runtime {DOMAIN.name}.' + ' Cross-domain usage of Protobuf is not supported.' + ) + + if ( + MAJOR < gen_major + or (MAJOR == gen_major and MINOR < gen_minor) + or (MAJOR == gen_major and MINOR == gen_minor and PATCH < gen_patch) + ): + _ReportVersionError( + 'Detected incompatible Protobuf Gencode/Runtime versions when loading' + f' {location}: gencode {gen_version} runtime {version}. Runtime version' + f' cannot be older than the linked gencode version. {error_prompt}' + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/service_reflection.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/service_reflection.py new file mode 100644 index 0000000000000000000000000000000000000000..7ba3d0b2e448629bc53e1e9c75f0249a0b74c033 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/service_reflection.py @@ -0,0 +1,272 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""Contains metaclasses used to create protocol service and service stub +classes from ServiceDescriptor objects at runtime. + +The GeneratedServiceType and GeneratedServiceStubType metaclasses are used to +inject all useful functionality into the classes output by the protocol +compiler at compile-time. +""" + +__author__ = 'petar@google.com (Petar Petrov)' + + +class GeneratedServiceType(type): + + """Metaclass for service classes created at runtime from ServiceDescriptors. + + Implementations for all methods described in the Service class are added here + by this class. We also create properties to allow getting/setting all fields + in the protocol message. + + The protocol compiler currently uses this metaclass to create protocol service + classes at runtime. Clients can also manually create their own classes at + runtime, as in this example:: + + mydescriptor = ServiceDescriptor(.....) + class MyProtoService(service.Service): + __metaclass__ = GeneratedServiceType + DESCRIPTOR = mydescriptor + myservice_instance = MyProtoService() + # ... + """ + + _DESCRIPTOR_KEY = 'DESCRIPTOR' + + def __init__(cls, name, bases, dictionary): + """Creates a message service class. + + Args: + name: Name of the class (ignored, but required by the metaclass + protocol). + bases: Base classes of the class being constructed. + dictionary: The class dictionary of the class being constructed. + dictionary[_DESCRIPTOR_KEY] must contain a ServiceDescriptor object + describing this protocol service type. + """ + # Don't do anything if this class doesn't have a descriptor. This happens + # when a service class is subclassed. + if GeneratedServiceType._DESCRIPTOR_KEY not in dictionary: + return + + descriptor = dictionary[GeneratedServiceType._DESCRIPTOR_KEY] + service_builder = _ServiceBuilder(descriptor) + service_builder.BuildService(cls) + cls.DESCRIPTOR = descriptor + + +class GeneratedServiceStubType(GeneratedServiceType): + + """Metaclass for service stubs created at runtime from ServiceDescriptors. + + This class has similar responsibilities as GeneratedServiceType, except that + it creates the service stub classes. + """ + + _DESCRIPTOR_KEY = 'DESCRIPTOR' + + def __init__(cls, name, bases, dictionary): + """Creates a message service stub class. + + Args: + name: Name of the class (ignored, here). + bases: Base classes of the class being constructed. + dictionary: The class dictionary of the class being constructed. + dictionary[_DESCRIPTOR_KEY] must contain a ServiceDescriptor object + describing this protocol service type. + """ + super(GeneratedServiceStubType, cls).__init__(name, bases, dictionary) + # Don't do anything if this class doesn't have a descriptor. This happens + # when a service stub is subclassed. + if GeneratedServiceStubType._DESCRIPTOR_KEY not in dictionary: + return + + descriptor = dictionary[GeneratedServiceStubType._DESCRIPTOR_KEY] + service_stub_builder = _ServiceStubBuilder(descriptor) + service_stub_builder.BuildServiceStub(cls) + + +class _ServiceBuilder(object): + + """This class constructs a protocol service class using a service descriptor. + + Given a service descriptor, this class constructs a class that represents + the specified service descriptor. One service builder instance constructs + exactly one service class. That means all instances of that class share the + same builder. + """ + + def __init__(self, service_descriptor): + """Initializes an instance of the service class builder. + + Args: + service_descriptor: ServiceDescriptor to use when constructing the + service class. + """ + self.descriptor = service_descriptor + + def BuildService(builder, cls): + """Constructs the service class. + + Args: + cls: The class that will be constructed. + """ + + # CallMethod needs to operate with an instance of the Service class. This + # internal wrapper function exists only to be able to pass the service + # instance to the method that does the real CallMethod work. + # Making sure to use exact argument names from the abstract interface in + # service.py to match the type signature + def _WrapCallMethod(self, method_descriptor, rpc_controller, request, done): + return builder._CallMethod(self, method_descriptor, rpc_controller, + request, done) + + def _WrapGetRequestClass(self, method_descriptor): + return builder._GetRequestClass(method_descriptor) + + def _WrapGetResponseClass(self, method_descriptor): + return builder._GetResponseClass(method_descriptor) + + builder.cls = cls + cls.CallMethod = _WrapCallMethod + cls.GetDescriptor = staticmethod(lambda: builder.descriptor) + cls.GetDescriptor.__doc__ = 'Returns the service descriptor.' + cls.GetRequestClass = _WrapGetRequestClass + cls.GetResponseClass = _WrapGetResponseClass + for method in builder.descriptor.methods: + setattr(cls, method.name, builder._GenerateNonImplementedMethod(method)) + + def _CallMethod(self, srvc, method_descriptor, + rpc_controller, request, callback): + """Calls the method described by a given method descriptor. + + Args: + srvc: Instance of the service for which this method is called. + method_descriptor: Descriptor that represent the method to call. + rpc_controller: RPC controller to use for this method's execution. + request: Request protocol message. + callback: A callback to invoke after the method has completed. + """ + if method_descriptor.containing_service != self.descriptor: + raise RuntimeError( + 'CallMethod() given method descriptor for wrong service type.') + method = getattr(srvc, method_descriptor.name) + return method(rpc_controller, request, callback) + + def _GetRequestClass(self, method_descriptor): + """Returns the class of the request protocol message. + + Args: + method_descriptor: Descriptor of the method for which to return the + request protocol message class. + + Returns: + A class that represents the input protocol message of the specified + method. + """ + if method_descriptor.containing_service != self.descriptor: + raise RuntimeError( + 'GetRequestClass() given method descriptor for wrong service type.') + return method_descriptor.input_type._concrete_class + + def _GetResponseClass(self, method_descriptor): + """Returns the class of the response protocol message. + + Args: + method_descriptor: Descriptor of the method for which to return the + response protocol message class. + + Returns: + A class that represents the output protocol message of the specified + method. + """ + if method_descriptor.containing_service != self.descriptor: + raise RuntimeError( + 'GetResponseClass() given method descriptor for wrong service type.') + return method_descriptor.output_type._concrete_class + + def _GenerateNonImplementedMethod(self, method): + """Generates and returns a method that can be set for a service methods. + + Args: + method: Descriptor of the service method for which a method is to be + generated. + + Returns: + A method that can be added to the service class. + """ + return lambda inst, rpc_controller, request, callback: ( + self._NonImplementedMethod(method.name, rpc_controller, callback)) + + def _NonImplementedMethod(self, method_name, rpc_controller, callback): + """The body of all methods in the generated service class. + + Args: + method_name: Name of the method being executed. + rpc_controller: RPC controller used to execute this method. + callback: A callback which will be invoked when the method finishes. + """ + rpc_controller.SetFailed('Method %s not implemented.' % method_name) + callback(None) + + +class _ServiceStubBuilder(object): + + """Constructs a protocol service stub class using a service descriptor. + + Given a service descriptor, this class constructs a suitable stub class. + A stub is just a type-safe wrapper around an RpcChannel which emulates a + local implementation of the service. + + One service stub builder instance constructs exactly one class. It means all + instances of that class share the same service stub builder. + """ + + def __init__(self, service_descriptor): + """Initializes an instance of the service stub class builder. + + Args: + service_descriptor: ServiceDescriptor to use when constructing the + stub class. + """ + self.descriptor = service_descriptor + + def BuildServiceStub(self, cls): + """Constructs the stub class. + + Args: + cls: The class that will be constructed. + """ + + def _ServiceStubInit(stub, rpc_channel): + stub.rpc_channel = rpc_channel + self.cls = cls + cls.__init__ = _ServiceStubInit + for method in self.descriptor.methods: + setattr(cls, method.name, self._GenerateStubMethod(method)) + + def _GenerateStubMethod(self, method): + return (lambda inst, rpc_controller, request, callback=None: + self._StubMethod(inst, method, rpc_controller, request, callback)) + + def _StubMethod(self, stub, method_descriptor, + rpc_controller, request, callback): + """The body of all service methods in the generated stub class. + + Args: + stub: Stub instance. + method_descriptor: Descriptor of the invoked method. + rpc_controller: Rpc controller to execute the method. + request: Request protocol message. + callback: A callback to execute when the method finishes. + Returns: + Response message (in case of blocking call). + """ + return stub.rpc_channel.CallMethod( + method_descriptor, rpc_controller, request, + method_descriptor.output_type._concrete_class, callback) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/source_context_pb2.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/source_context_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..c492f271f3fbbf66fafc9c18917115127a8eb1bc --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/source_context_pb2.py @@ -0,0 +1,37 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# NO CHECKED-IN PROTOBUF GENCODE +# source: google/protobuf/source_context.proto +# Protobuf Python Version: 6.33.6 +"""Generated protocol buffer code.""" +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import runtime_version as _runtime_version +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder +_runtime_version.ValidateProtobufRuntimeVersion( + _runtime_version.Domain.PUBLIC, + 6, + 33, + 6, + '', + 'google/protobuf/source_context.proto' +) +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n$google/protobuf/source_context.proto\x12\x0fgoogle.protobuf\",\n\rSourceContext\x12\x1b\n\tfile_name\x18\x01 \x01(\tR\x08\x66ileNameB\x8a\x01\n\x13\x63om.google.protobufB\x12SourceContextProtoP\x01Z6google.golang.org/protobuf/types/known/sourcecontextpb\xa2\x02\x03GPB\xaa\x02\x1eGoogle.Protobuf.WellKnownTypesb\x06proto3') + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.source_context_pb2', _globals) +if not _descriptor._USE_C_DESCRIPTORS: + _globals['DESCRIPTOR']._loaded_options = None + _globals['DESCRIPTOR']._serialized_options = b'\n\023com.google.protobufB\022SourceContextProtoP\001Z6google.golang.org/protobuf/types/known/sourcecontextpb\242\002\003GPB\252\002\036Google.Protobuf.WellKnownTypes' + _globals['_SOURCECONTEXT']._serialized_start=57 + _globals['_SOURCECONTEXT']._serialized_end=101 +# @@protoc_insertion_point(module_scope) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/struct_pb2.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/struct_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..98f755511e0bc798b3da18e892c9e80d27ff2baa --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/struct_pb2.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# NO CHECKED-IN PROTOBUF GENCODE +# source: google/protobuf/struct.proto +# Protobuf Python Version: 6.33.6 +"""Generated protocol buffer code.""" +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import runtime_version as _runtime_version +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder +_runtime_version.ValidateProtobufRuntimeVersion( + _runtime_version.Domain.PUBLIC, + 6, + 33, + 6, + '', + 'google/protobuf/struct.proto' +) +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1cgoogle/protobuf/struct.proto\x12\x0fgoogle.protobuf\"\x98\x01\n\x06Struct\x12;\n\x06\x66ields\x18\x01 \x03(\x0b\x32#.google.protobuf.Struct.FieldsEntryR\x06\x66ields\x1aQ\n\x0b\x46ieldsEntry\x12\x10\n\x03key\x18\x01 \x01(\tR\x03key\x12,\n\x05value\x18\x02 \x01(\x0b\x32\x16.google.protobuf.ValueR\x05value:\x02\x38\x01\"\xb2\x02\n\x05Value\x12;\n\nnull_value\x18\x01 \x01(\x0e\x32\x1a.google.protobuf.NullValueH\x00R\tnullValue\x12#\n\x0cnumber_value\x18\x02 \x01(\x01H\x00R\x0bnumberValue\x12#\n\x0cstring_value\x18\x03 \x01(\tH\x00R\x0bstringValue\x12\x1f\n\nbool_value\x18\x04 \x01(\x08H\x00R\tboolValue\x12<\n\x0cstruct_value\x18\x05 \x01(\x0b\x32\x17.google.protobuf.StructH\x00R\x0bstructValue\x12;\n\nlist_value\x18\x06 \x01(\x0b\x32\x1a.google.protobuf.ListValueH\x00R\tlistValueB\x06\n\x04kind\";\n\tListValue\x12.\n\x06values\x18\x01 \x03(\x0b\x32\x16.google.protobuf.ValueR\x06values*\x1b\n\tNullValue\x12\x0e\n\nNULL_VALUE\x10\x00\x42\x7f\n\x13\x63om.google.protobufB\x0bStructProtoP\x01Z/google.golang.org/protobuf/types/known/structpb\xf8\x01\x01\xa2\x02\x03GPB\xaa\x02\x1eGoogle.Protobuf.WellKnownTypesb\x06proto3') + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.struct_pb2', _globals) +if not _descriptor._USE_C_DESCRIPTORS: + _globals['DESCRIPTOR']._loaded_options = None + _globals['DESCRIPTOR']._serialized_options = b'\n\023com.google.protobufB\013StructProtoP\001Z/google.golang.org/protobuf/types/known/structpb\370\001\001\242\002\003GPB\252\002\036Google.Protobuf.WellKnownTypes' + _globals['_STRUCT_FIELDSENTRY']._loaded_options = None + _globals['_STRUCT_FIELDSENTRY']._serialized_options = b'8\001' + _globals['_NULLVALUE']._serialized_start=574 + _globals['_NULLVALUE']._serialized_end=601 + _globals['_STRUCT']._serialized_start=50 + _globals['_STRUCT']._serialized_end=202 + _globals['_STRUCT_FIELDSENTRY']._serialized_start=121 + _globals['_STRUCT_FIELDSENTRY']._serialized_end=202 + _globals['_VALUE']._serialized_start=205 + _globals['_VALUE']._serialized_end=511 + _globals['_LISTVALUE']._serialized_start=513 + _globals['_LISTVALUE']._serialized_end=572 +# @@protoc_insertion_point(module_scope) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/symbol_database.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/symbol_database.py new file mode 100644 index 0000000000000000000000000000000000000000..a538d5d6da750ed4b48d14689b5f3d894a263538 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/symbol_database.py @@ -0,0 +1,179 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""A database of Python protocol buffer generated symbols. + +SymbolDatabase is the MessageFactory for messages generated at compile time, +and makes it easy to create new instances of a registered type, given only the +type's protocol buffer symbol name. + +Example usage:: + + db = symbol_database.SymbolDatabase() + + # Register symbols of interest, from one or multiple files. + db.RegisterFileDescriptor(my_proto_pb2.DESCRIPTOR) + db.RegisterMessage(my_proto_pb2.MyMessage) + db.RegisterEnumDescriptor(my_proto_pb2.MyEnum.DESCRIPTOR) + + # The database can be used as a MessageFactory, to generate types based on + # their name: + types = db.GetMessages(['my_proto.proto']) + my_message_instance = types['MyMessage']() + + # The database's underlying descriptor pool can be queried, so it's not + # necessary to know a type's filename to be able to generate it: + filename = db.pool.FindFileContainingSymbol('MyMessage') + my_message_instance = db.GetMessages([filename])['MyMessage']() + + # This functionality is also provided directly via a convenience method: + my_message_instance = db.GetSymbol('MyMessage')() +""" + +import warnings + +from google.protobuf.internal import api_implementation +from google.protobuf import descriptor_pool +from google.protobuf import message_factory + + +class SymbolDatabase(): + """A database of Python generated symbols.""" + + # local cache of registered classes. + _classes = {} + + def __init__(self, pool=None): + """Initializes a new SymbolDatabase.""" + self.pool = pool or descriptor_pool.DescriptorPool() + + def RegisterMessage(self, message): + """Registers the given message type in the local database. + + Calls to GetSymbol() and GetMessages() will return messages registered here. + + Args: + message: A :class:`google.protobuf.message.Message` subclass (or + instance); its descriptor will be registered. + + Returns: + The provided message. + """ + + desc = message.DESCRIPTOR + self._classes[desc] = message + self.RegisterMessageDescriptor(desc) + return message + + def RegisterMessageDescriptor(self, message_descriptor): + """Registers the given message descriptor in the local database. + + Args: + message_descriptor (Descriptor): the message descriptor to add. + """ + if api_implementation.Type() == 'python': + # pylint: disable=protected-access + self.pool._AddDescriptor(message_descriptor) + + def RegisterEnumDescriptor(self, enum_descriptor): + """Registers the given enum descriptor in the local database. + + Args: + enum_descriptor (EnumDescriptor): The enum descriptor to register. + + Returns: + EnumDescriptor: The provided descriptor. + """ + if api_implementation.Type() == 'python': + # pylint: disable=protected-access + self.pool._AddEnumDescriptor(enum_descriptor) + return enum_descriptor + + def RegisterServiceDescriptor(self, service_descriptor): + """Registers the given service descriptor in the local database. + + Args: + service_descriptor (ServiceDescriptor): the service descriptor to + register. + """ + if api_implementation.Type() == 'python': + # pylint: disable=protected-access + self.pool._AddServiceDescriptor(service_descriptor) + + def RegisterFileDescriptor(self, file_descriptor): + """Registers the given file descriptor in the local database. + + Args: + file_descriptor (FileDescriptor): The file descriptor to register. + """ + if api_implementation.Type() == 'python': + # pylint: disable=protected-access + self.pool._InternalAddFileDescriptor(file_descriptor) + + def GetSymbol(self, symbol): + """Tries to find a symbol in the local database. + + Currently, this method only returns message.Message instances, however, if + may be extended in future to support other symbol types. + + Args: + symbol (str): a protocol buffer symbol. + + Returns: + A Python class corresponding to the symbol. + + Raises: + KeyError: if the symbol could not be found. + """ + + return self._classes[self.pool.FindMessageTypeByName(symbol)] + + def GetMessages(self, files): + # TODO: Fix the differences with MessageFactory. + """Gets all registered messages from a specified file. + + Only messages already created and registered will be returned; (this is the + case for imported _pb2 modules) + But unlike MessageFactory, this version also returns already defined nested + messages, but does not register any message extensions. + + Args: + files (list[str]): The file names to extract messages from. + + Returns: + A dictionary mapping proto names to the message classes. + + Raises: + KeyError: if a file could not be found. + """ + + def _GetAllMessages(desc): + """Walk a message Descriptor and recursively yields all message names.""" + yield desc + for msg_desc in desc.nested_types: + for nested_desc in _GetAllMessages(msg_desc): + yield nested_desc + + result = {} + for file_name in files: + file_desc = self.pool.FindFileByName(file_name) + for msg_desc in file_desc.message_types_by_name.values(): + for desc in _GetAllMessages(msg_desc): + try: + result[desc.full_name] = self._classes[desc] + except KeyError: + # This descriptor has no registered class, skip it. + pass + return result + + +_DEFAULT = SymbolDatabase(pool=descriptor_pool.Default()) + + +def Default(): + """Returns the default SymbolDatabase.""" + return _DEFAULT diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/testdata/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/testdata/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/text_encoding.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/text_encoding.py new file mode 100644 index 0000000000000000000000000000000000000000..03c27dc104b2b9b9ab708084d9a5480bb9d058b6 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/text_encoding.py @@ -0,0 +1,106 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""Encoding related utilities.""" +import re + +def _AsciiIsPrint(i): + return i >= 32 and i < 127 + +def _MakeStrEscapes(): + ret = {} + for i in range(0, 128): + if not _AsciiIsPrint(i): + ret[i] = r'\%03o' % i + ret[ord('\t')] = r'\t' # optional escape + ret[ord('\n')] = r'\n' # optional escape + ret[ord('\r')] = r'\r' # optional escape + ret[ord('"')] = r'\"' # necessary escape + ret[ord('\'')] = r"\'" # optional escape + ret[ord('\\')] = r'\\' # necessary escape + return ret + +# Maps int -> char, performing string escapes. +_str_escapes = _MakeStrEscapes() + +# Maps int -> char, performing byte escaping and string escapes +_byte_escapes = {i: chr(i) for i in range(0, 256)} +_byte_escapes.update(_str_escapes) +_byte_escapes.update({i: r'\%03o' % i for i in range(128, 256)}) + + +def _DecodeUtf8EscapeErrors(text_bytes): + ret = '' + while text_bytes: + try: + ret += text_bytes.decode('utf-8').translate(_str_escapes) + text_bytes = '' + except UnicodeDecodeError as e: + ret += text_bytes[:e.start].decode('utf-8').translate(_str_escapes) + ret += _byte_escapes[text_bytes[e.start]] + text_bytes = text_bytes[e.start+1:] + return ret + + +def CEscape(text, as_utf8) -> str: + """Escape a bytes string for use in an text protocol buffer. + + Args: + text: A byte string to be escaped. + as_utf8: Specifies if result may contain non-ASCII characters. + In Python 3 this allows unescaped non-ASCII Unicode characters. + In Python 2 the return value will be valid UTF-8 rather than only ASCII. + Returns: + Escaped string (str). + """ + # Python's text.encode() 'string_escape' or 'unicode_escape' codecs do not + # satisfy our needs; they encodes unprintable characters using two-digit hex + # escapes whereas our C++ unescaping function allows hex escapes to be any + # length. So, "\0011".encode('string_escape') ends up being "\\x011", which + # will be decoded in C++ as a single-character string with char code 0x11. + text_is_unicode = isinstance(text, str) + if as_utf8: + if text_is_unicode: + return text.translate(_str_escapes) + else: + return _DecodeUtf8EscapeErrors(text) + else: + if text_is_unicode: + text = text.encode('utf-8') + return ''.join([_byte_escapes[c] for c in text]) + + +_CUNESCAPE_HEX = re.compile(r'(\\+)x([0-9a-fA-F])(?![0-9a-fA-F])') + + +def CUnescape(text: str) -> bytes: + """Unescape a text string with C-style escape sequences to UTF-8 bytes. + + Args: + text: The data to parse in a str. + Returns: + A byte string. + """ + + def ReplaceHex(m): + # Only replace the match if the number of leading back slashes is odd. i.e. + # the slash itself is not escaped. + if len(m.group(1)) & 1: + return m.group(1) + 'x0' + m.group(2) + return m.group(0) + + # This is required because the 'string_escape' encoding doesn't + # allow single-digit hex escapes (like '\xf'). + result = _CUNESCAPE_HEX.sub(ReplaceHex, text) + + # Replaces Unicode escape sequences with their character equivalents. + result = result.encode('raw_unicode_escape').decode('raw_unicode_escape') + # Encode Unicode characters as UTF-8, then decode to Latin-1 escaping + # unprintable characters. + result = result.encode('utf-8').decode('unicode_escape') + # Convert Latin-1 text back to a byte string (latin-1 codec also works here). + return result.encode('latin-1') diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/text_format.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/text_format.py new file mode 100644 index 0000000000000000000000000000000000000000..a3566ee3ded95587eff8263ab95efa9427f6ae1e --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/text_format.py @@ -0,0 +1,1884 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""Contains routines for printing protocol messages in text format. + +Simple usage example:: + + # Create a proto object and serialize it to a text proto string. + message = my_proto_pb2.MyMessage(foo='bar') + text_proto = text_format.MessageToString(message) + + # Parse a text proto string. + message = text_format.Parse(text_proto, my_proto_pb2.MyMessage()) +""" + +__author__ = 'kenton@google.com (Kenton Varda)' + +# TODO Import thread contention leads to test failures. +import encodings.raw_unicode_escape # pylint: disable=unused-import +import encodings.unicode_escape # pylint: disable=unused-import +import io +import math +import re +import warnings + +from google.protobuf.internal import decoder +from google.protobuf.internal import type_checkers +from google.protobuf import descriptor +from google.protobuf import text_encoding +from google.protobuf import unknown_fields + +# pylint: disable=g-import-not-at-top +__all__ = ['MessageToString', 'Parse', 'PrintMessage', 'PrintField', + 'PrintFieldValue', 'Merge', 'MessageToBytes'] + +_INTEGER_CHECKERS = (type_checkers.Uint32ValueChecker(), + type_checkers.Int32ValueChecker(), + type_checkers.Uint64ValueChecker(), + type_checkers.Int64ValueChecker()) +_FLOAT_INFINITY = re.compile('-?inf(?:inity)?f?$', re.IGNORECASE) +_FLOAT_NAN = re.compile('nanf?$', re.IGNORECASE) +_FLOAT_OCTAL_PREFIX = re.compile('-?0[0-9]+') +_QUOTES = frozenset(("'", '"')) +_ANY_FULL_TYPE_NAME = 'google.protobuf.Any' +_DEBUG_STRING_SILENT_MARKER = '\t ' + +_as_utf8_default = True + + +class Error(Exception): + """Top-level module error for text_format.""" + + +class ParseError(Error): + """Thrown in case of text parsing or tokenizing error.""" + + def __init__(self, message=None, line=None, column=None): + if message is not None and line is not None: + loc = str(line) + if column is not None: + loc += ':{0}'.format(column) + message = '{0} : {1}'.format(loc, message) + if message is not None: + super(ParseError, self).__init__(message) + else: + super(ParseError, self).__init__() + self._line = line + self._column = column + + def GetLine(self): + return self._line + + def GetColumn(self): + return self._column + + +class TextWriter(object): + + def __init__(self, as_utf8): + self._writer = io.StringIO() + + def write(self, val): + return self._writer.write(val) + + def close(self): + return self._writer.close() + + def getvalue(self): + return self._writer.getvalue() + + +def MessageToString( + message, + as_utf8=_as_utf8_default, + as_one_line=False, + use_short_repeated_primitives=False, + pointy_brackets=False, + use_index_order=False, + float_format=None, + double_format=None, + use_field_number=False, + descriptor_pool=None, + indent=0, + message_formatter=None, + print_unknown_fields=False, + force_colon=False) -> str: + """Convert protobuf message to text format. + + Double values can be formatted compactly with 15 digits of + precision (which is the most that IEEE 754 "double" can guarantee) + using double_format='.15g'. To ensure that converting to text and back to a + proto will result in an identical value, double_format='.17g' should be used. + + Args: + message: The protocol buffers message. + as_utf8: Return unescaped Unicode for non-ASCII characters. + as_one_line: Don't introduce newlines between fields. + use_short_repeated_primitives: Use short repeated format for primitives. + pointy_brackets: If True, use angle brackets instead of curly braces for + nesting. + use_index_order: If True, fields of a proto message will be printed using + the order defined in source code instead of the field number, extensions + will be printed at the end of the message and their relative order is + determined by the extension number. By default, use the field number + order. + float_format (str): Deprecated. If set, use this to specify float field + formatting (per the "Format Specification Mini-Language"); otherwise, + shortest float that has same value in wire will be printed. Also affect + double field if double_format is not set but float_format is set. + double_format (str): Deprecated. If set, use this to specify double field + formatting (per the "Format Specification Mini-Language"); if it is not + set but float_format is set, use float_format. Otherwise, use ``str()`` + use_field_number: If True, print field numbers instead of names. + descriptor_pool (DescriptorPool): Descriptor pool used to resolve Any types. + indent (int): The initial indent level, in terms of spaces, for pretty + print. + message_formatter (function(message, indent, as_one_line) -> unicode|None): + Custom formatter for selected sub-messages (usually based on message + type). Use to pretty print parts of the protobuf for easier diffing. + print_unknown_fields: If True, unknown fields will be printed. + force_colon: If set, a colon will be added after the field name even if the + field is a proto message. + + Returns: + str: A string of the text formatted protocol buffer message. + """ + out = TextWriter(as_utf8) + printer = _Printer( + out, + indent, + as_utf8, + as_one_line, + use_short_repeated_primitives, + pointy_brackets, + use_index_order, + float_format, + double_format, + use_field_number, + descriptor_pool, + message_formatter, + print_unknown_fields=print_unknown_fields, + force_colon=force_colon) + printer.PrintMessage(message) + result = out.getvalue() + out.close() + if as_one_line: + return result.rstrip() + return result + + +def MessageToBytes(message, **kwargs) -> bytes: + """Convert protobuf message to encoded text format. See MessageToString.""" + text = MessageToString(message, **kwargs) + if isinstance(text, bytes): + return text + codec = 'utf-8' if kwargs.get('as_utf8') else 'ascii' + return text.encode(codec) + + +def _IsMapEntry(field): + return (field.type == descriptor.FieldDescriptor.TYPE_MESSAGE and + field.message_type.has_options and + field.message_type.GetOptions().map_entry) + + +def _IsGroupLike(field): + """Determines if a field is consistent with a proto2 group. + + Args: + field: The field descriptor. + + Returns: + True if this field is group-like, false otherwise. + """ + # Groups are always tag-delimited. + if field.type != descriptor.FieldDescriptor.TYPE_GROUP: + return False + + # Group fields always are always the lowercase type name. + if field.name != field.message_type.name.lower(): + return False + + if field.message_type.file != field.file: + return False + + # Group messages are always defined in the same scope as the field. File + # level extensions will compare NULL == NULL here, which is why the file + # comparison above is necessary to ensure both come from the same file. + return ( + field.message_type.containing_type == field.extension_scope + if field.is_extension + else field.message_type.containing_type == field.containing_type + ) + + +def PrintMessage(message, + out, + indent=0, + as_utf8=_as_utf8_default, + as_one_line=False, + use_short_repeated_primitives=False, + pointy_brackets=False, + use_index_order=False, + float_format=None, + double_format=None, + use_field_number=False, + descriptor_pool=None, + message_formatter=None, + print_unknown_fields=False, + force_colon=False): + """Convert the message to text format and write it to the out stream. + + Args: + message: The Message object to convert to text format. + out: A file handle to write the message to. + indent: The initial indent level for pretty print. + as_utf8: Return unescaped Unicode for non-ASCII characters. + as_one_line: Don't introduce newlines between fields. + use_short_repeated_primitives: Use short repeated format for primitives. + pointy_brackets: If True, use angle brackets instead of curly braces for + nesting. + use_index_order: If True, print fields of a proto message using the order + defined in source code instead of the field number. By default, use the + field number order. + float_format: If set, use this to specify float field formatting + (per the "Format Specification Mini-Language"); otherwise, shortest + float that has same value in wire will be printed. Also affect double + field if double_format is not set but float_format is set. + double_format: If set, use this to specify double field formatting + (per the "Format Specification Mini-Language"); if it is not set but + float_format is set, use float_format. Otherwise, str() is used. + use_field_number: If True, print field numbers instead of names. + descriptor_pool: A DescriptorPool used to resolve Any types. + message_formatter: A function(message, indent, as_one_line): unicode|None + to custom format selected sub-messages (usually based on message type). + Use to pretty print parts of the protobuf for easier diffing. + print_unknown_fields: If True, unknown fields will be printed. + force_colon: If set, a colon will be added after the field name even if + the field is a proto message. + """ + printer = _Printer( + out=out, indent=indent, as_utf8=as_utf8, + as_one_line=as_one_line, + use_short_repeated_primitives=use_short_repeated_primitives, + pointy_brackets=pointy_brackets, + use_index_order=use_index_order, + float_format=float_format, + double_format=double_format, + use_field_number=use_field_number, + descriptor_pool=descriptor_pool, + message_formatter=message_formatter, + print_unknown_fields=print_unknown_fields, + force_colon=force_colon) + printer.PrintMessage(message) + + +def PrintField(field, + value, + out, + indent=0, + as_utf8=_as_utf8_default, + as_one_line=False, + use_short_repeated_primitives=False, + pointy_brackets=False, + use_index_order=False, + float_format=None, + double_format=None, + message_formatter=None, + print_unknown_fields=False, + force_colon=False): + """Print a single field name/value pair.""" + printer = _Printer(out, indent, as_utf8, as_one_line, + use_short_repeated_primitives, pointy_brackets, + use_index_order, float_format, double_format, + message_formatter=message_formatter, + print_unknown_fields=print_unknown_fields, + force_colon=force_colon) + printer.PrintField(field, value) + + +def PrintFieldValue(field, + value, + out, + indent=0, + as_utf8=_as_utf8_default, + as_one_line=False, + use_short_repeated_primitives=False, + pointy_brackets=False, + use_index_order=False, + float_format=None, + double_format=None, + message_formatter=None, + print_unknown_fields=False, + force_colon=False): + """Print a single field value (not including name).""" + printer = _Printer(out, indent, as_utf8, as_one_line, + use_short_repeated_primitives, pointy_brackets, + use_index_order, float_format, double_format, + message_formatter=message_formatter, + print_unknown_fields=print_unknown_fields, + force_colon=force_colon) + printer.PrintFieldValue(field, value) + + +def _BuildMessageFromTypeName(type_name, descriptor_pool): + """Returns a protobuf message instance. + + Args: + type_name: Fully-qualified protobuf message type name string. + descriptor_pool: DescriptorPool instance. + + Returns: + A Message instance of type matching type_name, or None if the a Descriptor + wasn't found matching type_name. + """ + # pylint: disable=g-import-not-at-top + if descriptor_pool is None: + from google.protobuf import descriptor_pool as pool_mod + descriptor_pool = pool_mod.Default() + from google.protobuf import message_factory + try: + message_descriptor = descriptor_pool.FindMessageTypeByName(type_name) + except KeyError: + return None + message_type = message_factory.GetMessageClass(message_descriptor) + return message_type() + + +# These values must match WireType enum in //google/protobuf/wire_format.h. +WIRETYPE_LENGTH_DELIMITED = 2 +WIRETYPE_START_GROUP = 3 + + +class _Printer(object): + """Text format printer for protocol message.""" + + def __init__( + self, + out, + indent=0, + as_utf8=_as_utf8_default, + as_one_line=False, + use_short_repeated_primitives=False, + pointy_brackets=False, + use_index_order=False, + float_format=None, + double_format=None, + use_field_number=False, + descriptor_pool=None, + message_formatter=None, + print_unknown_fields=False, + force_colon=False): + """Initialize the Printer. + + Double values can be formatted compactly with 15 digits of precision + (which is the most that IEEE 754 "double" can guarantee) using + double_format='.15g'. To ensure that converting to text and back to a proto + will result in an identical value, double_format='.17g' should be used. + + Args: + out: To record the text format result. + indent: The initial indent level for pretty print. + as_utf8: Return unescaped Unicode for non-ASCII characters. + as_one_line: Don't introduce newlines between fields. + use_short_repeated_primitives: Use short repeated format for primitives. + pointy_brackets: If True, use angle brackets instead of curly braces for + nesting. + use_index_order: If True, print fields of a proto message using the order + defined in source code instead of the field number. By default, use the + field number order. + float_format: Deprecated. If set, use this to specify float field + formatting (per the "Format Specification Mini-Language"); otherwise, + shortest float that has same value in wire will be printed. Also affect + double field if double_format is not set but float_format is set. + double_format: Deprecated. If set, use this to specify double field + formatting (per the "Format Specification Mini-Language"); if it is not + set but float_format is set, use float_format. Otherwise, str() is used. + use_field_number: If True, print field numbers instead of names. + descriptor_pool: A DescriptorPool used to resolve Any types. + message_formatter: A function(message, indent, as_one_line): unicode|None + to custom format selected sub-messages (usually based on message type). + Use to pretty print parts of the protobuf for easier diffing. + print_unknown_fields: If True, unknown fields will be printed. + force_colon: If set, a colon will be added after the field name even if + the field is a proto message. + """ + self.out = out + self.indent = indent + self.as_utf8 = as_utf8 + self.as_one_line = as_one_line + self.use_short_repeated_primitives = use_short_repeated_primitives + self.pointy_brackets = pointy_brackets + self.use_index_order = use_index_order + self.float_format = float_format + if double_format is not None: + warnings.warn( + 'double_format is deprecated for text_format. This will ' + 'turn into error in 7.34.0, please remove it before that.' + ) + self.double_format = double_format + else: + self.double_format = float_format + self.use_field_number = use_field_number + self.descriptor_pool = descriptor_pool + self.message_formatter = message_formatter + self.print_unknown_fields = print_unknown_fields + self.force_colon = force_colon + + def _TryPrintAsAnyMessage(self, message): + """Serializes if message is a google.protobuf.Any field.""" + if '/' not in message.type_url: + return False + packed_message = _BuildMessageFromTypeName(message.TypeName(), + self.descriptor_pool) + if packed_message is not None: + packed_message.MergeFromString(message.value) + colon = ':' if self.force_colon else '' + self.out.write('%s[%s]%s ' % (self.indent * ' ', message.type_url, colon)) + self._PrintMessageFieldValue(packed_message) + self.out.write(' ' if self.as_one_line else '\n') + return True + else: + return False + + def _TryCustomFormatMessage(self, message): + formatted = self.message_formatter(message, self.indent, self.as_one_line) + if formatted is None: + return False + + out = self.out + out.write(' ' * self.indent) + out.write(formatted) + out.write(' ' if self.as_one_line else '\n') + return True + + def PrintMessage(self, message): + """Convert protobuf message to text format. + + Args: + message: The protocol buffers message. + """ + if self.message_formatter and self._TryCustomFormatMessage(message): + return + if (message.DESCRIPTOR.full_name == _ANY_FULL_TYPE_NAME and + self._TryPrintAsAnyMessage(message)): + return + fields = message.ListFields() + if self.use_index_order: + fields.sort( + key=lambda x: x[0].number if x[0].is_extension else x[0].index) + for field, value in fields: + if _IsMapEntry(field): + for key in sorted(value): + # This is slow for maps with submessage entries because it copies the + # entire tree. Unfortunately this would take significant refactoring + # of this file to work around. + # + # TODO: refactor and optimize if this becomes an issue. + entry_submsg = value.GetEntryClass()(key=key, value=value[key]) + self.PrintField(field, entry_submsg) + elif field.is_repeated: + if (self.use_short_repeated_primitives + and field.cpp_type != descriptor.FieldDescriptor.CPPTYPE_MESSAGE + and field.cpp_type != descriptor.FieldDescriptor.CPPTYPE_STRING): + self._PrintShortRepeatedPrimitivesValue(field, value) + else: + for element in value: + self.PrintField(field, element) + else: + self.PrintField(field, value) + + if self.print_unknown_fields: + self._PrintUnknownFields(unknown_fields.UnknownFieldSet(message)) + + def _PrintUnknownFields(self, unknown_field_set): + """Print unknown fields.""" + out = self.out + for field in unknown_field_set: + out.write(' ' * self.indent) + out.write(str(field.field_number)) + if field.wire_type == WIRETYPE_START_GROUP: + if self.as_one_line: + out.write(' { ') + else: + out.write(' {\n') + self.indent += 2 + + self._PrintUnknownFields(field.data) + + if self.as_one_line: + out.write('} ') + else: + self.indent -= 2 + out.write(' ' * self.indent + '}\n') + elif field.wire_type == WIRETYPE_LENGTH_DELIMITED: + try: + # If this field is parseable as a Message, it is probably + # an embedded message. + # pylint: disable=protected-access + (embedded_unknown_message, pos) = decoder._DecodeUnknownFieldSet( + memoryview(field.data), 0, len(field.data)) + except Exception: # pylint: disable=broad-except + pos = 0 + + if pos == len(field.data): + if self.as_one_line: + out.write(' { ') + else: + out.write(' {\n') + self.indent += 2 + + self._PrintUnknownFields(embedded_unknown_message) + + if self.as_one_line: + out.write('} ') + else: + self.indent -= 2 + out.write(' ' * self.indent + '}\n') + else: + # A string or bytes field. self.as_utf8 may not work. + out.write(': \"') + out.write(text_encoding.CEscape(field.data, False)) + out.write('\" ' if self.as_one_line else '\"\n') + else: + # varint, fixed32, fixed64 + out.write(': ') + out.write(str(field.data)) + out.write(' ' if self.as_one_line else '\n') + + def _PrintFieldName(self, field): + """Print field name.""" + out = self.out + out.write(' ' * self.indent) + if self.use_field_number: + out.write(str(field.number)) + else: + if field.is_extension: + out.write('[') + if (field.containing_type.GetOptions().message_set_wire_format and + field.type == descriptor.FieldDescriptor.TYPE_MESSAGE and + not field.is_required and + not field.is_repeated): + out.write(field.message_type.full_name) + else: + out.write(field.full_name) + out.write(']') + elif _IsGroupLike(field): + # For groups, use the capitalized name. + out.write(field.message_type.name) + else: + out.write(field.name) + + if (self.force_colon or + field.cpp_type != descriptor.FieldDescriptor.CPPTYPE_MESSAGE): + # The colon is optional in this case, but our cross-language golden files + # don't include it. Here, the colon is only included if force_colon is + # set to True + out.write(':') + + def PrintField(self, field, value): + """Print a single field name/value pair.""" + self._PrintFieldName(field) + self.out.write(' ') + self.PrintFieldValue(field, value) + self.out.write(' ' if self.as_one_line else '\n') + + def _PrintShortRepeatedPrimitivesValue(self, field, value): + """"Prints short repeated primitives value.""" + # Note: this is called only when value has at least one element. + self._PrintFieldName(field) + self.out.write(' [') + for i in range(len(value) - 1): + self.PrintFieldValue(field, value[i]) + self.out.write(', ') + self.PrintFieldValue(field, value[-1]) + self.out.write(']') + self.out.write(' ' if self.as_one_line else '\n') + + def _PrintMessageFieldValue(self, value): + if self.pointy_brackets: + openb = '<' + closeb = '>' + else: + openb = '{' + closeb = '}' + + if self.as_one_line: + self.out.write('%s ' % openb) + self.PrintMessage(value) + self.out.write(closeb) + else: + self.out.write('%s\n' % openb) + self.indent += 2 + self.PrintMessage(value) + self.indent -= 2 + self.out.write(' ' * self.indent + closeb) + + def PrintFieldValue(self, field, value): + """Print a single field value (not including name). + + For repeated fields, the value should be a single element. + + Args: + field: The descriptor of the field to be printed. + value: The value of the field. + """ + out = self.out + if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE: + self._PrintMessageFieldValue(value) + elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM: + enum_value = field.enum_type.values_by_number.get(value, None) + if enum_value is not None: + out.write(enum_value.name) + else: + out.write(str(value)) + elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING: + out.write('\"') + if isinstance(value, str) and not self.as_utf8: + out_value = value.encode('utf-8') + else: + out_value = value + if field.type == descriptor.FieldDescriptor.TYPE_BYTES: + # We always need to escape all binary data in TYPE_BYTES fields. + out_as_utf8 = False + else: + out_as_utf8 = self.as_utf8 + out.write(text_encoding.CEscape(out_value, out_as_utf8)) + out.write('\"') + elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL: + if value: + out.write('true') + else: + out.write('false') + elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_FLOAT: + if self.float_format is not None: + warnings.warn( + 'float_format is deprecated for text_format. This ' + 'will turn into error in 7.34.0, please remove it ' + 'before that.' + ) + out.write('{1:{0}}'.format(self.float_format, value)) + else: + if math.isnan(value): + out.write(str(value)) + else: + out.write(str(type_checkers.ToShortestFloat(value))) + elif (field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_DOUBLE and + self.double_format is not None): + out.write('{1:{0}}'.format(self.double_format, value)) + else: + out.write(str(value)) + + +def Parse(text, + message, + allow_unknown_extension=False, + allow_field_number=False, + descriptor_pool=None, + allow_unknown_field=False): + """Parses a text representation of a protocol message into a message. + + NOTE: for historical reasons this function does not clear the input + message. This is different from what the binary msg.ParseFrom(...) does. + If text contains a field already set in message, the value is appended if the + field is repeated. Otherwise, an error is raised. + + Example:: + + a = MyProto() + a.repeated_field.append('test') + b = MyProto() + + # Repeated fields are combined + text_format.Parse(repr(a), b) + text_format.Parse(repr(a), b) # repeated_field contains ["test", "test"] + + # Non-repeated fields cannot be overwritten + a.singular_field = 1 + b.singular_field = 2 + text_format.Parse(repr(a), b) # ParseError + + # Binary version: + b.ParseFromString(a.SerializeToString()) # repeated_field is now "test" + + Caller is responsible for clearing the message as needed. + + Args: + text (str): Message text representation. + message (Message): A protocol buffer message to merge into. + allow_unknown_extension: if True, skip over missing extensions and keep + parsing + allow_field_number: if True, both field number and field name are allowed. + descriptor_pool (DescriptorPool): Descriptor pool used to resolve Any types. + allow_unknown_field: if True, skip over unknown field and keep + parsing. Avoid to use this option if possible. It may hide some + errors (e.g. spelling error on field name) + + Returns: + Message: The same message passed as argument. + + Raises: + ParseError: On text parsing problems. + """ + return ParseLines(text.split(b'\n' if isinstance(text, bytes) else u'\n'), + message, + allow_unknown_extension, + allow_field_number, + descriptor_pool=descriptor_pool, + allow_unknown_field=allow_unknown_field) + + +def Merge(text, + message, + allow_unknown_extension=False, + allow_field_number=False, + descriptor_pool=None, + allow_unknown_field=False): + """Parses a text representation of a protocol message into a message. + + Like Parse(), but allows repeated values for a non-repeated field, and uses + the last one. This means any non-repeated, top-level fields specified in text + replace those in the message. + + Args: + text (str): Message text representation. + message (Message): A protocol buffer message to merge into. + allow_unknown_extension: if True, skip over missing extensions and keep + parsing + allow_field_number: if True, both field number and field name are allowed. + descriptor_pool (DescriptorPool): Descriptor pool used to resolve Any types. + allow_unknown_field: if True, skip over unknown field and keep + parsing. Avoid to use this option if possible. It may hide some + errors (e.g. spelling error on field name) + + Returns: + Message: The same message passed as argument. + + Raises: + ParseError: On text parsing problems. + """ + return MergeLines( + text.split(b'\n' if isinstance(text, bytes) else u'\n'), + message, + allow_unknown_extension, + allow_field_number, + descriptor_pool=descriptor_pool, + allow_unknown_field=allow_unknown_field) + + +def ParseLines(lines, + message, + allow_unknown_extension=False, + allow_field_number=False, + descriptor_pool=None, + allow_unknown_field=False): + """Parses a text representation of a protocol message into a message. + + See Parse() for caveats. + + Args: + lines: An iterable of lines of a message's text representation. + message: A protocol buffer message to merge into. + allow_unknown_extension: if True, skip over missing extensions and keep + parsing + allow_field_number: if True, both field number and field name are allowed. + descriptor_pool: A DescriptorPool used to resolve Any types. + allow_unknown_field: if True, skip over unknown field and keep + parsing. Avoid to use this option if possible. It may hide some + errors (e.g. spelling error on field name) + + Returns: + The same message passed as argument. + + Raises: + ParseError: On text parsing problems. + """ + parser = _Parser(allow_unknown_extension, + allow_field_number, + descriptor_pool=descriptor_pool, + allow_unknown_field=allow_unknown_field) + return parser.ParseLines(lines, message) + + +def MergeLines(lines, + message, + allow_unknown_extension=False, + allow_field_number=False, + descriptor_pool=None, + allow_unknown_field=False): + """Parses a text representation of a protocol message into a message. + + See Merge() for more details. + + Args: + lines: An iterable of lines of a message's text representation. + message: A protocol buffer message to merge into. + allow_unknown_extension: if True, skip over missing extensions and keep + parsing + allow_field_number: if True, both field number and field name are allowed. + descriptor_pool: A DescriptorPool used to resolve Any types. + allow_unknown_field: if True, skip over unknown field and keep + parsing. Avoid to use this option if possible. It may hide some + errors (e.g. spelling error on field name) + + Returns: + The same message passed as argument. + + Raises: + ParseError: On text parsing problems. + """ + parser = _Parser(allow_unknown_extension, + allow_field_number, + descriptor_pool=descriptor_pool, + allow_unknown_field=allow_unknown_field) + return parser.MergeLines(lines, message) + + +class _Parser(object): + """Text format parser for protocol message.""" + + def __init__(self, + allow_unknown_extension=False, + allow_field_number=False, + descriptor_pool=None, + allow_unknown_field=False): + self.allow_unknown_extension = allow_unknown_extension + self.allow_field_number = allow_field_number + self.descriptor_pool = descriptor_pool + self.allow_unknown_field = allow_unknown_field + + def ParseLines(self, lines, message): + """Parses a text representation of a protocol message into a message.""" + self._allow_multiple_scalars = False + self._ParseOrMerge(lines, message) + return message + + def MergeLines(self, lines, message): + """Merges a text representation of a protocol message into a message.""" + self._allow_multiple_scalars = True + self._ParseOrMerge(lines, message) + return message + + def _ParseOrMerge(self, lines, message): + """Converts a text representation of a protocol message into a message. + + Args: + lines: Lines of a message's text representation. + message: A protocol buffer message to merge into. + + Raises: + ParseError: On text parsing problems. + """ + # Tokenize expects native str lines. + try: + str_lines = ( + line if isinstance(line, str) else line.decode('utf-8') + for line in lines) + tokenizer = Tokenizer(str_lines) + except UnicodeDecodeError as e: + raise ParseError from e + if message: + self.root_type = message.DESCRIPTOR.full_name + while not tokenizer.AtEnd(): + self._MergeField(tokenizer, message) + + def _MergeField(self, tokenizer, message): + """Merges a single protocol message field into a message. + + Args: + tokenizer: A tokenizer to parse the field name and values. + message: A protocol message to record the data. + + Raises: + ParseError: In case of text parsing problems. + """ + message_descriptor = message.DESCRIPTOR + if (message_descriptor.full_name == _ANY_FULL_TYPE_NAME and + tokenizer.TryConsume('[')): + type_url_prefix, packed_type_name = self._ConsumeAnyTypeUrl(tokenizer) + tokenizer.Consume(']') + tokenizer.TryConsume(':') + self._DetectSilentMarker(tokenizer, message_descriptor.full_name, + type_url_prefix + '/' + packed_type_name) + if tokenizer.TryConsume('<'): + expanded_any_end_token = '>' + else: + tokenizer.Consume('{') + expanded_any_end_token = '}' + expanded_any_sub_message = _BuildMessageFromTypeName(packed_type_name, + self.descriptor_pool) + # Direct comparison with None is used instead of implicit bool conversion + # to avoid false positives with falsy initial values, e.g. for + # google.protobuf.ListValue. + if expanded_any_sub_message is None: + raise ParseError('Type %s not found in descriptor pool' % + packed_type_name) + while not tokenizer.TryConsume(expanded_any_end_token): + if tokenizer.AtEnd(): + raise tokenizer.ParseErrorPreviousToken('Expected "%s".' % + (expanded_any_end_token,)) + self._MergeField(tokenizer, expanded_any_sub_message) + deterministic = False + + message.Pack(expanded_any_sub_message, + type_url_prefix=type_url_prefix, + deterministic=deterministic) + return + + if tokenizer.TryConsume('['): + name = [tokenizer.ConsumeIdentifier()] + while tokenizer.TryConsume('.'): + name.append(tokenizer.ConsumeIdentifier()) + name = '.'.join(name) + + if not message_descriptor.is_extendable: + raise tokenizer.ParseErrorPreviousToken( + 'Message type "%s" does not have extensions.' % + message_descriptor.full_name) + # pylint: disable=protected-access + field = message.Extensions._FindExtensionByName(name) + # pylint: enable=protected-access + if not field: + if self.allow_unknown_extension: + field = None + else: + raise tokenizer.ParseErrorPreviousToken( + 'Extension "%s" not registered. ' + 'Did you import the _pb2 module which defines it? ' + 'If you are trying to place the extension in the MessageSet ' + 'field of another message that is in an Any or MessageSet field, ' + 'that message\'s _pb2 module must be imported as well' % name) + elif message_descriptor != field.containing_type: + raise tokenizer.ParseErrorPreviousToken( + 'Extension "%s" does not extend message type "%s".' % + (name, message_descriptor.full_name)) + + tokenizer.Consume(']') + + else: + name = tokenizer.ConsumeIdentifierOrNumber() + if self.allow_field_number and name.isdigit(): + number = ParseInteger(name, True, True) + field = message_descriptor.fields_by_number.get(number, None) + if not field and message_descriptor.is_extendable: + field = message.Extensions._FindExtensionByNumber(number) + else: + field = message_descriptor.fields_by_name.get(name, None) + + # Group names are expected to be capitalized as they appear in the + # .proto file, which actually matches their type names, not their field + # names. + if not field: + field = message_descriptor.fields_by_name.get(name.lower(), None) + if field and not _IsGroupLike(field): + field = None + if field and field.message_type.name != name: + field = None + + if not field and not self.allow_unknown_field: + raise tokenizer.ParseErrorPreviousToken( + 'Message type "%s" has no field named "%s".' % + (message_descriptor.full_name, name)) + + if field: + if not self._allow_multiple_scalars and field.containing_oneof: + # Check if there's a different field set in this oneof. + # Note that we ignore the case if the same field was set before, and we + # apply _allow_multiple_scalars to non-scalar fields as well. + which_oneof = message.WhichOneof(field.containing_oneof.name) + if which_oneof is not None and which_oneof != field.name: + raise tokenizer.ParseErrorPreviousToken( + 'Field "%s" is specified along with field "%s", another member ' + 'of oneof "%s" for message type "%s".' % + (field.name, which_oneof, field.containing_oneof.name, + message_descriptor.full_name)) + + if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE: + tokenizer.TryConsume(':') + self._DetectSilentMarker(tokenizer, message_descriptor.full_name, + field.full_name) + merger = self._MergeMessageField + else: + tokenizer.Consume(':') + self._DetectSilentMarker(tokenizer, message_descriptor.full_name, + field.full_name) + merger = self._MergeScalarField + + if (field.is_repeated and + tokenizer.TryConsume('[')): + # Short repeated format, e.g. "foo: [1, 2, 3]" + if not tokenizer.TryConsume(']'): + while True: + merger(tokenizer, message, field) + if tokenizer.TryConsume(']'): + break + tokenizer.Consume(',') + + else: + merger(tokenizer, message, field) + + else: # Proto field is unknown. + assert (self.allow_unknown_extension or self.allow_unknown_field) + self._SkipFieldContents(tokenizer, name, message_descriptor.full_name) + + # For historical reasons, fields may optionally be separated by commas or + # semicolons. + if not tokenizer.TryConsume(','): + tokenizer.TryConsume(';') + + def _LogSilentMarker(self, immediate_message_type, field_name): + pass + + def _DetectSilentMarker(self, tokenizer, immediate_message_type, field_name): + if tokenizer.contains_silent_marker_before_current_token: + self._LogSilentMarker(immediate_message_type, field_name) + + def _ConsumeAnyTypeUrl(self, tokenizer): + """Consumes a google.protobuf.Any type URL and returns the type name.""" + # Consume "type.googleapis.com/". + prefix = [tokenizer.ConsumeIdentifier()] + tokenizer.Consume('.') + prefix.append(tokenizer.ConsumeIdentifier()) + tokenizer.Consume('.') + prefix.append(tokenizer.ConsumeIdentifier()) + tokenizer.Consume('/') + # Consume the fully-qualified type name. + name = [tokenizer.ConsumeIdentifier()] + while tokenizer.TryConsume('.'): + name.append(tokenizer.ConsumeIdentifier()) + return '.'.join(prefix), '.'.join(name) + + def _MergeMessageField(self, tokenizer, message, field): + """Merges a single scalar field into a message. + + Args: + tokenizer: A tokenizer to parse the field value. + message: The message of which field is a member. + field: The descriptor of the field to be merged. + + Raises: + ParseError: In case of text parsing problems. + """ + is_map_entry = _IsMapEntry(field) + + if tokenizer.TryConsume('<'): + end_token = '>' + else: + tokenizer.Consume('{') + end_token = '}' + + if field.is_repeated: + if field.is_extension: + sub_message = message.Extensions[field].add() + elif is_map_entry: + sub_message = getattr(message, field.name).GetEntryClass()() + else: + sub_message = getattr(message, field.name).add() + else: + if field.is_extension: + if (not self._allow_multiple_scalars and + message.HasExtension(field)): + raise tokenizer.ParseErrorPreviousToken( + 'Message type "%s" should not have multiple "%s" extensions.' % + (message.DESCRIPTOR.full_name, field.full_name)) + sub_message = message.Extensions[field] + else: + # Also apply _allow_multiple_scalars to message field. + # TODO: Change to _allow_singular_overwrites. + if (not self._allow_multiple_scalars and + message.HasField(field.name)): + raise tokenizer.ParseErrorPreviousToken( + 'Message type "%s" should not have multiple "%s" fields.' % + (message.DESCRIPTOR.full_name, field.name)) + sub_message = getattr(message, field.name) + sub_message.SetInParent() + + while not tokenizer.TryConsume(end_token): + if tokenizer.AtEnd(): + raise tokenizer.ParseErrorPreviousToken('Expected "%s".' % (end_token,)) + self._MergeField(tokenizer, sub_message) + + if is_map_entry: + value_cpptype = field.message_type.fields_by_name['value'].cpp_type + if value_cpptype == descriptor.FieldDescriptor.CPPTYPE_MESSAGE: + value = getattr(message, field.name)[sub_message.key] + value.CopyFrom(sub_message.value) + else: + getattr(message, field.name)[sub_message.key] = sub_message.value + + def _MergeScalarField(self, tokenizer, message, field): + """Merges a single scalar field into a message. + + Args: + tokenizer: A tokenizer to parse the field value. + message: A protocol message to record the data. + field: The descriptor of the field to be merged. + + Raises: + ParseError: In case of text parsing problems. + RuntimeError: On runtime errors. + """ + _ = self.allow_unknown_extension + value = None + + if field.type in (descriptor.FieldDescriptor.TYPE_INT32, + descriptor.FieldDescriptor.TYPE_SINT32, + descriptor.FieldDescriptor.TYPE_SFIXED32): + value = _ConsumeInt32(tokenizer) + elif field.type in (descriptor.FieldDescriptor.TYPE_INT64, + descriptor.FieldDescriptor.TYPE_SINT64, + descriptor.FieldDescriptor.TYPE_SFIXED64): + value = _ConsumeInt64(tokenizer) + elif field.type in (descriptor.FieldDescriptor.TYPE_UINT32, + descriptor.FieldDescriptor.TYPE_FIXED32): + value = _ConsumeUint32(tokenizer) + elif field.type in (descriptor.FieldDescriptor.TYPE_UINT64, + descriptor.FieldDescriptor.TYPE_FIXED64): + value = _ConsumeUint64(tokenizer) + elif field.type in (descriptor.FieldDescriptor.TYPE_FLOAT, + descriptor.FieldDescriptor.TYPE_DOUBLE): + value = tokenizer.ConsumeFloat() + elif field.type == descriptor.FieldDescriptor.TYPE_BOOL: + value = tokenizer.ConsumeBool() + elif field.type == descriptor.FieldDescriptor.TYPE_STRING: + value = tokenizer.ConsumeString() + elif field.type == descriptor.FieldDescriptor.TYPE_BYTES: + value = tokenizer.ConsumeByteString() + elif field.type == descriptor.FieldDescriptor.TYPE_ENUM: + value = tokenizer.ConsumeEnum(field) + else: + raise RuntimeError('Unknown field type %d' % field.type) + + if field.is_repeated: + if field.is_extension: + message.Extensions[field].append(value) + else: + getattr(message, field.name).append(value) + else: + if field.is_extension: + if (not self._allow_multiple_scalars and + field.has_presence and + message.HasExtension(field)): + raise tokenizer.ParseErrorPreviousToken( + 'Message type "%s" should not have multiple "%s" extensions.' % + (message.DESCRIPTOR.full_name, field.full_name)) + else: + message.Extensions[field] = value + else: + duplicate_error = False + if not self._allow_multiple_scalars: + if field.has_presence: + duplicate_error = message.HasField(field.name) + else: + # For field that doesn't represent presence, try best effort to + # check multiple scalars by compare to default values. + duplicate_error = not decoder.IsDefaultScalarValue( + getattr(message, field.name) + ) + + if duplicate_error: + raise tokenizer.ParseErrorPreviousToken( + 'Message type "%s" should not have multiple "%s" fields.' % + (message.DESCRIPTOR.full_name, field.name)) + else: + setattr(message, field.name, value) + + def _SkipFieldContents(self, tokenizer, field_name, immediate_message_type): + """Skips over contents (value or message) of a field. + + Args: + tokenizer: A tokenizer to parse the field name and values. + field_name: The field name currently being parsed. + immediate_message_type: The type of the message immediately containing + the silent marker. + """ + # Try to guess the type of this field. + # If this field is not a message, there should be a ":" between the + # field name and the field value and also the field value should not + # start with "{" or "<" which indicates the beginning of a message body. + # If there is no ":" or there is a "{" or "<" after ":", this field has + # to be a message or the input is ill-formed. + if tokenizer.TryConsume( + ':') and not tokenizer.LookingAt('{') and not tokenizer.LookingAt('<'): + self._DetectSilentMarker(tokenizer, immediate_message_type, field_name) + if tokenizer.LookingAt('['): + self._SkipRepeatedFieldValue(tokenizer, immediate_message_type) + else: + self._SkipFieldValue(tokenizer) + else: + self._DetectSilentMarker(tokenizer, immediate_message_type, field_name) + self._SkipFieldMessage(tokenizer, immediate_message_type) + + def _SkipField(self, tokenizer, immediate_message_type): + """Skips over a complete field (name and value/message). + + Args: + tokenizer: A tokenizer to parse the field name and values. + immediate_message_type: The type of the message immediately containing + the silent marker. + """ + field_name = '' + if tokenizer.TryConsume('['): + # Consume extension or google.protobuf.Any type URL + field_name += '[' + tokenizer.ConsumeIdentifier() + num_identifiers = 1 + while tokenizer.TryConsume('.'): + field_name += '.' + tokenizer.ConsumeIdentifier() + num_identifiers += 1 + # This is possibly a type URL for an Any message. + if num_identifiers == 3 and tokenizer.TryConsume('/'): + field_name += '/' + tokenizer.ConsumeIdentifier() + while tokenizer.TryConsume('.'): + field_name += '.' + tokenizer.ConsumeIdentifier() + tokenizer.Consume(']') + field_name += ']' + else: + field_name += tokenizer.ConsumeIdentifierOrNumber() + + self._SkipFieldContents(tokenizer, field_name, immediate_message_type) + + # For historical reasons, fields may optionally be separated by commas or + # semicolons. + if not tokenizer.TryConsume(','): + tokenizer.TryConsume(';') + + def _SkipFieldMessage(self, tokenizer, immediate_message_type): + """Skips over a field message. + + Args: + tokenizer: A tokenizer to parse the field name and values. + immediate_message_type: The type of the message immediately containing + the silent marker + """ + if tokenizer.TryConsume('<'): + delimiter = '>' + else: + tokenizer.Consume('{') + delimiter = '}' + + while not tokenizer.LookingAt('>') and not tokenizer.LookingAt('}'): + self._SkipField(tokenizer, immediate_message_type) + + tokenizer.Consume(delimiter) + + def _SkipFieldValue(self, tokenizer): + """Skips over a field value. + + Args: + tokenizer: A tokenizer to parse the field name and values. + + Raises: + ParseError: In case an invalid field value is found. + """ + if (not tokenizer.TryConsumeByteString()and + not tokenizer.TryConsumeIdentifier() and + not _TryConsumeInt64(tokenizer) and + not _TryConsumeUint64(tokenizer) and + not tokenizer.TryConsumeFloat()): + raise ParseError('Invalid field value: ' + tokenizer.token) + + def _SkipRepeatedFieldValue(self, tokenizer, immediate_message_type): + """Skips over a repeated field value. + + Args: + tokenizer: A tokenizer to parse the field value. + """ + tokenizer.Consume('[') + if not tokenizer.TryConsume(']'): + while True: + if tokenizer.LookingAt('<') or tokenizer.LookingAt('{'): + self._SkipFieldMessage(tokenizer, immediate_message_type) + else: + self._SkipFieldValue(tokenizer) + if tokenizer.TryConsume(']'): + break + tokenizer.Consume(',') + + +class Tokenizer(object): + """Protocol buffer text representation tokenizer. + + This class handles the lower level string parsing by splitting it into + meaningful tokens. + + It was directly ported from the Java protocol buffer API. + """ + + _WHITESPACE = re.compile(r'\s+') + _COMMENT = re.compile(r'(\s*#.*$)', re.MULTILINE) + _WHITESPACE_OR_COMMENT = re.compile(r'(\s|(#.*$))+', re.MULTILINE) + _TOKEN = re.compile('|'.join([ + r'[a-zA-Z_][0-9a-zA-Z_+-]*', # an identifier + r'([0-9+-]|(\.[0-9]))[0-9a-zA-Z_.+-]*', # a number + ] + [ # quoted str for each quote mark + # Avoid backtracking! https://stackoverflow.com/a/844267 + r'{qt}[^{qt}\n\\]*((\\.)+[^{qt}\n\\]*)*({qt}|\\?$)'.format(qt=mark) + for mark in _QUOTES + ])) + + _IDENTIFIER = re.compile(r'[^\d\W]\w*') + _IDENTIFIER_OR_NUMBER = re.compile(r'\w+') + + def __init__(self, lines, skip_comments=True): + self._position = 0 + self._line = -1 + self._column = 0 + self._token_start = None + self.token = '' + self._lines = iter(lines) + self._current_line = '' + self._previous_line = 0 + self._previous_column = 0 + self._more_lines = True + self._skip_comments = skip_comments + self._whitespace_pattern = (skip_comments and self._WHITESPACE_OR_COMMENT + or self._WHITESPACE) + self.contains_silent_marker_before_current_token = False + + self._SkipWhitespace() + self.NextToken() + + def LookingAt(self, token): + return self.token == token + + def AtEnd(self): + """Checks the end of the text was reached. + + Returns: + True iff the end was reached. + """ + return not self.token + + def _PopLine(self): + while len(self._current_line) <= self._column: + try: + self._current_line = next(self._lines) + except StopIteration: + self._current_line = '' + self._more_lines = False + return + else: + self._line += 1 + self._column = 0 + + def _SkipWhitespace(self): + while True: + self._PopLine() + match = self._whitespace_pattern.match(self._current_line, self._column) + if not match: + break + self.contains_silent_marker_before_current_token = match.group(0) == ( + ' ' + _DEBUG_STRING_SILENT_MARKER) + length = len(match.group(0)) + self._column += length + + def TryConsume(self, token): + """Tries to consume a given piece of text. + + Args: + token: Text to consume. + + Returns: + True iff the text was consumed. + """ + if self.token == token: + self.NextToken() + return True + return False + + def Consume(self, token): + """Consumes a piece of text. + + Args: + token: Text to consume. + + Raises: + ParseError: If the text couldn't be consumed. + """ + if not self.TryConsume(token): + raise self.ParseError('Expected "%s".' % token) + + def ConsumeComment(self): + result = self.token + if not self._COMMENT.match(result): + raise self.ParseError('Expected comment.') + self.NextToken() + return result + + def ConsumeCommentOrTrailingComment(self): + """Consumes a comment, returns a 2-tuple (trailing bool, comment str).""" + + # Tokenizer initializes _previous_line and _previous_column to 0. As the + # tokenizer starts, it looks like there is a previous token on the line. + just_started = self._line == 0 and self._column == 0 + + before_parsing = self._previous_line + comment = self.ConsumeComment() + + # A trailing comment is a comment on the same line than the previous token. + trailing = (self._previous_line == before_parsing + and not just_started) + + return trailing, comment + + def TryConsumeIdentifier(self): + try: + self.ConsumeIdentifier() + return True + except ParseError: + return False + + def ConsumeIdentifier(self): + """Consumes protocol message field identifier. + + Returns: + Identifier string. + + Raises: + ParseError: If an identifier couldn't be consumed. + """ + result = self.token + if not self._IDENTIFIER.match(result): + raise self.ParseError('Expected identifier.') + self.NextToken() + return result + + def TryConsumeIdentifierOrNumber(self): + try: + self.ConsumeIdentifierOrNumber() + return True + except ParseError: + return False + + def ConsumeIdentifierOrNumber(self): + """Consumes protocol message field identifier. + + Returns: + Identifier string. + + Raises: + ParseError: If an identifier couldn't be consumed. + """ + result = self.token + if not self._IDENTIFIER_OR_NUMBER.match(result): + raise self.ParseError('Expected identifier or number, got %s.' % result) + self.NextToken() + return result + + def TryConsumeInteger(self): + try: + self.ConsumeInteger() + return True + except ParseError: + return False + + def ConsumeInteger(self): + """Consumes an integer number. + + Returns: + The integer parsed. + + Raises: + ParseError: If an integer couldn't be consumed. + """ + try: + result = _ParseAbstractInteger(self.token) + except ValueError as e: + raise self.ParseError(str(e)) + self.NextToken() + return result + + def TryConsumeFloat(self): + try: + self.ConsumeFloat() + return True + except ParseError: + return False + + def ConsumeFloat(self): + """Consumes an floating point number. + + Returns: + The number parsed. + + Raises: + ParseError: If a floating point number couldn't be consumed. + """ + try: + result = ParseFloat(self.token) + except ValueError as e: + raise self.ParseError(str(e)) + self.NextToken() + return result + + def ConsumeBool(self): + """Consumes a boolean value. + + Returns: + The bool parsed. + + Raises: + ParseError: If a boolean value couldn't be consumed. + """ + try: + result = ParseBool(self.token) + except ValueError as e: + raise self.ParseError(str(e)) + self.NextToken() + return result + + def TryConsumeByteString(self): + try: + self.ConsumeByteString() + return True + except ParseError: + return False + + def ConsumeString(self): + """Consumes a string value. + + Returns: + The string parsed. + + Raises: + ParseError: If a string value couldn't be consumed. + """ + the_bytes = self.ConsumeByteString() + try: + return str(the_bytes, 'utf-8') + except UnicodeDecodeError as e: + raise self._StringParseError(e) + + def ConsumeByteString(self): + """Consumes a byte array value. + + Returns: + The array parsed (as a string). + + Raises: + ParseError: If a byte array value couldn't be consumed. + """ + the_list = [self._ConsumeSingleByteString()] + while self.token and self.token[0] in _QUOTES: + the_list.append(self._ConsumeSingleByteString()) + return b''.join(the_list) + + def _ConsumeSingleByteString(self): + """Consume one token of a string literal. + + String literals (whether bytes or text) can come in multiple adjacent + tokens which are automatically concatenated, like in C or Python. This + method only consumes one token. + + Returns: + The token parsed. + Raises: + ParseError: When the wrong format data is found. + """ + text = self.token + if len(text) < 1 or text[0] not in _QUOTES: + raise self.ParseError('Expected string but found: %r' % (text,)) + + if len(text) < 2 or text[-1] != text[0]: + raise self.ParseError('String missing ending quote: %r' % (text,)) + + try: + result = text_encoding.CUnescape(text[1:-1]) + except ValueError as e: + raise self.ParseError(str(e)) + self.NextToken() + return result + + def ConsumeEnum(self, field): + try: + result = ParseEnum(field, self.token) + except ValueError as e: + raise self.ParseError(str(e)) + self.NextToken() + return result + + def ParseErrorPreviousToken(self, message): + """Creates and *returns* a ParseError for the previously read token. + + Args: + message: A message to set for the exception. + + Returns: + A ParseError instance. + """ + return ParseError(message, self._previous_line + 1, + self._previous_column + 1) + + def ParseError(self, message): + """Creates and *returns* a ParseError for the current token.""" + return ParseError('\'' + self._current_line + '\': ' + message, + self._line + 1, self._column + 1) + + def _StringParseError(self, e): + return self.ParseError('Couldn\'t parse string: ' + str(e)) + + def NextToken(self): + """Reads the next meaningful token.""" + self._previous_line = self._line + self._previous_column = self._column + self.contains_silent_marker_before_current_token = False + + self._column += len(self.token) + self._SkipWhitespace() + + if not self._more_lines: + self.token = '' + return + + match = self._TOKEN.match(self._current_line, self._column) + if not match and not self._skip_comments: + match = self._COMMENT.match(self._current_line, self._column) + if match: + token = match.group(0) + self.token = token + else: + self.token = self._current_line[self._column] + +# Aliased so it can still be accessed by current visibility violators. +# TODO: Migrate violators to textformat_tokenizer. +_Tokenizer = Tokenizer # pylint: disable=invalid-name + + +def _ConsumeInt32(tokenizer): + """Consumes a signed 32bit integer number from tokenizer. + + Args: + tokenizer: A tokenizer used to parse the number. + + Returns: + The integer parsed. + + Raises: + ParseError: If a signed 32bit integer couldn't be consumed. + """ + return _ConsumeInteger(tokenizer, is_signed=True, is_long=False) + + +def _ConsumeUint32(tokenizer): + """Consumes an unsigned 32bit integer number from tokenizer. + + Args: + tokenizer: A tokenizer used to parse the number. + + Returns: + The integer parsed. + + Raises: + ParseError: If an unsigned 32bit integer couldn't be consumed. + """ + return _ConsumeInteger(tokenizer, is_signed=False, is_long=False) + + +def _TryConsumeInt64(tokenizer): + try: + _ConsumeInt64(tokenizer) + return True + except ParseError: + return False + + +def _ConsumeInt64(tokenizer): + """Consumes a signed 32bit integer number from tokenizer. + + Args: + tokenizer: A tokenizer used to parse the number. + + Returns: + The integer parsed. + + Raises: + ParseError: If a signed 32bit integer couldn't be consumed. + """ + return _ConsumeInteger(tokenizer, is_signed=True, is_long=True) + + +def _TryConsumeUint64(tokenizer): + try: + _ConsumeUint64(tokenizer) + return True + except ParseError: + return False + + +def _ConsumeUint64(tokenizer): + """Consumes an unsigned 64bit integer number from tokenizer. + + Args: + tokenizer: A tokenizer used to parse the number. + + Returns: + The integer parsed. + + Raises: + ParseError: If an unsigned 64bit integer couldn't be consumed. + """ + return _ConsumeInteger(tokenizer, is_signed=False, is_long=True) + + +def _ConsumeInteger(tokenizer, is_signed=False, is_long=False): + """Consumes an integer number from tokenizer. + + Args: + tokenizer: A tokenizer used to parse the number. + is_signed: True if a signed integer must be parsed. + is_long: True if a long integer must be parsed. + + Returns: + The integer parsed. + + Raises: + ParseError: If an integer with given characteristics couldn't be consumed. + """ + try: + result = ParseInteger(tokenizer.token, is_signed=is_signed, is_long=is_long) + except ValueError as e: + raise tokenizer.ParseError(str(e)) + tokenizer.NextToken() + return result + + +def ParseInteger(text, is_signed=False, is_long=False): + """Parses an integer. + + Args: + text: The text to parse. + is_signed: True if a signed integer must be parsed. + is_long: True if a long integer must be parsed. + + Returns: + The integer value. + + Raises: + ValueError: Thrown Iff the text is not a valid integer. + """ + # Do the actual parsing. Exception handling is propagated to caller. + result = _ParseAbstractInteger(text) + + # Check if the integer is sane. Exceptions handled by callers. + checker = _INTEGER_CHECKERS[2 * int(is_long) + int(is_signed)] + checker.CheckValue(result) + return result + + +def _ParseAbstractInteger(text): + """Parses an integer without checking size/signedness. + + Args: + text: The text to parse. + + Returns: + The integer value. + + Raises: + ValueError: Thrown Iff the text is not a valid integer. + """ + # Do the actual parsing. Exception handling is propagated to caller. + orig_text = text + c_octal_match = re.match(r'(-?)0(\d+)$', text) + if c_octal_match: + # Python 3 no longer supports 0755 octal syntax without the 'o', so + # we always use the '0o' prefix for multi-digit numbers starting with 0. + text = c_octal_match.group(1) + '0o' + c_octal_match.group(2) + try: + return int(text, 0) + except ValueError: + raise ValueError('Couldn\'t parse integer: %s' % orig_text) + + +def ParseFloat(text): + """Parse a floating point number. + + Args: + text: Text to parse. + + Returns: + The number parsed. + + Raises: + ValueError: If a floating point number couldn't be parsed. + """ + if _FLOAT_OCTAL_PREFIX.match(text): + raise ValueError('Invalid octal float: %s' % text) + try: + # Assume Python compatible syntax. + return float(text) + except ValueError: + # Check alternative spellings. + if _FLOAT_INFINITY.match(text): + if text[0] == '-': + return float('-inf') + else: + return float('inf') + elif _FLOAT_NAN.match(text): + return float('nan') + else: + # assume '1.0f' format + try: + return float(text.rstrip('fF')) + except ValueError: + raise ValueError("Couldn't parse float: %s" % text) + + +def ParseBool(text): + """Parse a boolean value. + + Args: + text: Text to parse. + + Returns: + Boolean values parsed + + Raises: + ValueError: If text is not a valid boolean. + """ + if text in ('true', 't', '1', 'True'): + return True + elif text in ('false', 'f', '0', 'False'): + return False + else: + raise ValueError('Expected "true" or "false".') + + +def ParseEnum(field, value): + """Parse an enum value. + + The value can be specified by a number (the enum value), or by + a string literal (the enum name). + + Args: + field: Enum field descriptor. + value: String value. + + Returns: + Enum value number. + + Raises: + ValueError: If the enum value could not be parsed. + """ + enum_descriptor = field.enum_type + try: + number = int(value, 0) + except ValueError: + # Identifier. + enum_value = enum_descriptor.values_by_name.get(value, None) + if enum_value is None: + raise ValueError('Enum type "%s" has no value named %s.' % + (enum_descriptor.full_name, value)) + else: + if not field.enum_type.is_closed: + return number + enum_value = enum_descriptor.values_by_number.get(number, None) + if enum_value is None: + raise ValueError('Enum type "%s" has no value with number %d.' % + (enum_descriptor.full_name, number)) + return enum_value.number diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/timestamp.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/timestamp.py new file mode 100644 index 0000000000000000000000000000000000000000..b23b9f11af02984469f565ae253730c1fdda0c1d --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/timestamp.py @@ -0,0 +1,112 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""Contains the Timestamp helper APIs.""" + +import datetime +from typing import Optional + +from google.protobuf.timestamp_pb2 import Timestamp + + +def from_json_string(value: str) -> Timestamp: + """Parse a RFC 3339 date string format to Timestamp. + + Args: + value: A date string. Any fractional digits (or none) and any offset are + accepted as long as they fit into nano-seconds precision. Example of + accepted format: '1972-01-01T10:00:20.021-05:00' + + Raises: + ValueError: On parsing problems. + """ + timestamp = Timestamp() + timestamp.FromJsonString(value) + return timestamp + + +def from_microseconds(micros: float) -> Timestamp: + """Converts microseconds since epoch to Timestamp.""" + timestamp = Timestamp() + timestamp.FromMicroseconds(micros) + return timestamp + + +def from_milliseconds(millis: float) -> Timestamp: + """Converts milliseconds since epoch to Timestamp.""" + timestamp = Timestamp() + timestamp.FromMilliseconds(millis) + return timestamp + + +def from_nanoseconds(nanos: float) -> Timestamp: + """Converts nanoseconds since epoch to Timestamp.""" + timestamp = Timestamp() + timestamp.FromNanoseconds(nanos) + return timestamp + + +def from_seconds(seconds: float) -> Timestamp: + """Converts seconds since epoch to Timestamp.""" + timestamp = Timestamp() + timestamp.FromSeconds(seconds) + return timestamp + + +def from_current_time() -> Timestamp: + """Converts the current UTC to Timestamp.""" + timestamp = Timestamp() + timestamp.FromDatetime(datetime.datetime.now(tz=datetime.timezone.utc)) + return timestamp + + +def to_json_string(ts: Timestamp) -> str: + """Converts Timestamp to RFC 3339 date string format. + + Returns: + A string converted from timestamp. The string is always Z-normalized + and uses 3, 6 or 9 fractional digits as required to represent the + exact time. Example of the return format: '1972-01-01T10:00:20.021Z' + """ + return ts.ToJsonString() + + +def to_microseconds(ts: Timestamp) -> int: + """Converts Timestamp to microseconds since epoch.""" + return ts.ToMicroseconds() + + +def to_milliseconds(ts: Timestamp) -> int: + """Converts Timestamp to milliseconds since epoch.""" + return ts.ToMilliseconds() + + +def to_nanoseconds(ts: Timestamp) -> int: + """Converts Timestamp to nanoseconds since epoch.""" + return ts.ToNanoseconds() + + +def to_seconds(ts: Timestamp) -> int: + """Converts Timestamp to seconds since epoch.""" + return ts.ToSeconds() + + +def to_datetime( + ts: Timestamp, tz: Optional[datetime.tzinfo] = None +) -> datetime.datetime: + """Converts Timestamp to a datetime. + + Args: + tz: A datetime.tzinfo subclass; defaults to None. + + Returns: + If tzinfo is None, returns a timezone-naive UTC datetime (with no timezone + information, i.e. not aware that it's UTC). + + Otherwise, returns a timezone-aware datetime in the input timezone. + """ + return ts.ToDatetime(tzinfo=tz) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/timestamp_pb2.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/timestamp_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..8c8392236aa04458d838f6b8af9af3ac8d673dd5 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/timestamp_pb2.py @@ -0,0 +1,37 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# NO CHECKED-IN PROTOBUF GENCODE +# source: google/protobuf/timestamp.proto +# Protobuf Python Version: 6.33.6 +"""Generated protocol buffer code.""" +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import runtime_version as _runtime_version +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder +_runtime_version.ValidateProtobufRuntimeVersion( + _runtime_version.Domain.PUBLIC, + 6, + 33, + 6, + '', + 'google/protobuf/timestamp.proto' +) +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1fgoogle/protobuf/timestamp.proto\x12\x0fgoogle.protobuf\";\n\tTimestamp\x12\x18\n\x07seconds\x18\x01 \x01(\x03R\x07seconds\x12\x14\n\x05nanos\x18\x02 \x01(\x05R\x05nanosB\x85\x01\n\x13\x63om.google.protobufB\x0eTimestampProtoP\x01Z2google.golang.org/protobuf/types/known/timestamppb\xf8\x01\x01\xa2\x02\x03GPB\xaa\x02\x1eGoogle.Protobuf.WellKnownTypesb\x06proto3') + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.timestamp_pb2', _globals) +if not _descriptor._USE_C_DESCRIPTORS: + _globals['DESCRIPTOR']._loaded_options = None + _globals['DESCRIPTOR']._serialized_options = b'\n\023com.google.protobufB\016TimestampProtoP\001Z2google.golang.org/protobuf/types/known/timestamppb\370\001\001\242\002\003GPB\252\002\036Google.Protobuf.WellKnownTypes' + _globals['_TIMESTAMP']._serialized_start=52 + _globals['_TIMESTAMP']._serialized_end=111 +# @@protoc_insertion_point(module_scope) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/type_pb2.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/type_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..2050c91de8590a50c2e42622a866b0dfa2f37260 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/type_pb2.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# NO CHECKED-IN PROTOBUF GENCODE +# source: google/protobuf/type.proto +# Protobuf Python Version: 6.33.6 +"""Generated protocol buffer code.""" +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import runtime_version as _runtime_version +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder +_runtime_version.ValidateProtobufRuntimeVersion( + _runtime_version.Domain.PUBLIC, + 6, + 33, + 6, + '', + 'google/protobuf/type.proto' +) +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.protobuf import any_pb2 as google_dot_protobuf_dot_any__pb2 +from google.protobuf import source_context_pb2 as google_dot_protobuf_dot_source__context__pb2 + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1agoogle/protobuf/type.proto\x12\x0fgoogle.protobuf\x1a\x19google/protobuf/any.proto\x1a$google/protobuf/source_context.proto\"\xa7\x02\n\x04Type\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\x12.\n\x06\x66ields\x18\x02 \x03(\x0b\x32\x16.google.protobuf.FieldR\x06\x66ields\x12\x16\n\x06oneofs\x18\x03 \x03(\tR\x06oneofs\x12\x31\n\x07options\x18\x04 \x03(\x0b\x32\x17.google.protobuf.OptionR\x07options\x12\x45\n\x0esource_context\x18\x05 \x01(\x0b\x32\x1e.google.protobuf.SourceContextR\rsourceContext\x12/\n\x06syntax\x18\x06 \x01(\x0e\x32\x17.google.protobuf.SyntaxR\x06syntax\x12\x18\n\x07\x65\x64ition\x18\x07 \x01(\tR\x07\x65\x64ition\"\xb4\x06\n\x05\x46ield\x12/\n\x04kind\x18\x01 \x01(\x0e\x32\x1b.google.protobuf.Field.KindR\x04kind\x12\x44\n\x0b\x63\x61rdinality\x18\x02 \x01(\x0e\x32\".google.protobuf.Field.CardinalityR\x0b\x63\x61rdinality\x12\x16\n\x06number\x18\x03 \x01(\x05R\x06number\x12\x12\n\x04name\x18\x04 \x01(\tR\x04name\x12\x19\n\x08type_url\x18\x06 \x01(\tR\x07typeUrl\x12\x1f\n\x0boneof_index\x18\x07 \x01(\x05R\noneofIndex\x12\x16\n\x06packed\x18\x08 \x01(\x08R\x06packed\x12\x31\n\x07options\x18\t \x03(\x0b\x32\x17.google.protobuf.OptionR\x07options\x12\x1b\n\tjson_name\x18\n \x01(\tR\x08jsonName\x12#\n\rdefault_value\x18\x0b \x01(\tR\x0c\x64\x65\x66\x61ultValue\"\xc8\x02\n\x04Kind\x12\x10\n\x0cTYPE_UNKNOWN\x10\x00\x12\x0f\n\x0bTYPE_DOUBLE\x10\x01\x12\x0e\n\nTYPE_FLOAT\x10\x02\x12\x0e\n\nTYPE_INT64\x10\x03\x12\x0f\n\x0bTYPE_UINT64\x10\x04\x12\x0e\n\nTYPE_INT32\x10\x05\x12\x10\n\x0cTYPE_FIXED64\x10\x06\x12\x10\n\x0cTYPE_FIXED32\x10\x07\x12\r\n\tTYPE_BOOL\x10\x08\x12\x0f\n\x0bTYPE_STRING\x10\t\x12\x0e\n\nTYPE_GROUP\x10\n\x12\x10\n\x0cTYPE_MESSAGE\x10\x0b\x12\x0e\n\nTYPE_BYTES\x10\x0c\x12\x0f\n\x0bTYPE_UINT32\x10\r\x12\r\n\tTYPE_ENUM\x10\x0e\x12\x11\n\rTYPE_SFIXED32\x10\x0f\x12\x11\n\rTYPE_SFIXED64\x10\x10\x12\x0f\n\x0bTYPE_SINT32\x10\x11\x12\x0f\n\x0bTYPE_SINT64\x10\x12\"t\n\x0b\x43\x61rdinality\x12\x17\n\x13\x43\x41RDINALITY_UNKNOWN\x10\x00\x12\x18\n\x14\x43\x41RDINALITY_OPTIONAL\x10\x01\x12\x18\n\x14\x43\x41RDINALITY_REQUIRED\x10\x02\x12\x18\n\x14\x43\x41RDINALITY_REPEATED\x10\x03\"\x99\x02\n\x04\x45num\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\x12\x38\n\tenumvalue\x18\x02 \x03(\x0b\x32\x1a.google.protobuf.EnumValueR\tenumvalue\x12\x31\n\x07options\x18\x03 \x03(\x0b\x32\x17.google.protobuf.OptionR\x07options\x12\x45\n\x0esource_context\x18\x04 \x01(\x0b\x32\x1e.google.protobuf.SourceContextR\rsourceContext\x12/\n\x06syntax\x18\x05 \x01(\x0e\x32\x17.google.protobuf.SyntaxR\x06syntax\x12\x18\n\x07\x65\x64ition\x18\x06 \x01(\tR\x07\x65\x64ition\"j\n\tEnumValue\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\x12\x16\n\x06number\x18\x02 \x01(\x05R\x06number\x12\x31\n\x07options\x18\x03 \x03(\x0b\x32\x17.google.protobuf.OptionR\x07options\"H\n\x06Option\x12\x12\n\x04name\x18\x01 \x01(\tR\x04name\x12*\n\x05value\x18\x02 \x01(\x0b\x32\x14.google.protobuf.AnyR\x05value*C\n\x06Syntax\x12\x11\n\rSYNTAX_PROTO2\x10\x00\x12\x11\n\rSYNTAX_PROTO3\x10\x01\x12\x13\n\x0fSYNTAX_EDITIONS\x10\x02\x42{\n\x13\x63om.google.protobufB\tTypeProtoP\x01Z-google.golang.org/protobuf/types/known/typepb\xf8\x01\x01\xa2\x02\x03GPB\xaa\x02\x1eGoogle.Protobuf.WellKnownTypesb\x06proto3') + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.type_pb2', _globals) +if not _descriptor._USE_C_DESCRIPTORS: + _globals['DESCRIPTOR']._loaded_options = None + _globals['DESCRIPTOR']._serialized_options = b'\n\023com.google.protobufB\tTypeProtoP\001Z-google.golang.org/protobuf/types/known/typepb\370\001\001\242\002\003GPB\252\002\036Google.Protobuf.WellKnownTypes' + _globals['_SYNTAX']._serialized_start=1699 + _globals['_SYNTAX']._serialized_end=1766 + _globals['_TYPE']._serialized_start=113 + _globals['_TYPE']._serialized_end=408 + _globals['_FIELD']._serialized_start=411 + _globals['_FIELD']._serialized_end=1231 + _globals['_FIELD_KIND']._serialized_start=785 + _globals['_FIELD_KIND']._serialized_end=1113 + _globals['_FIELD_CARDINALITY']._serialized_start=1115 + _globals['_FIELD_CARDINALITY']._serialized_end=1231 + _globals['_ENUM']._serialized_start=1234 + _globals['_ENUM']._serialized_end=1515 + _globals['_ENUMVALUE']._serialized_start=1517 + _globals['_ENUMVALUE']._serialized_end=1623 + _globals['_OPTION']._serialized_start=1625 + _globals['_OPTION']._serialized_end=1697 +# @@protoc_insertion_point(module_scope) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/unknown_fields.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/unknown_fields.py new file mode 100644 index 0000000000000000000000000000000000000000..6c16a2d30ced679544f8134812e99118caed8348 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/unknown_fields.py @@ -0,0 +1,96 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file or at +# https://developers.google.com/open-source/licenses/bsd + +"""Contains Unknown Fields APIs. + +Simple usage example: + unknown_field_set = UnknownFieldSet(message) + for unknown_field in unknown_field_set: + wire_type = unknown_field.wire_type + field_number = unknown_field.field_number + data = unknown_field.data +""" + + +from google.protobuf.internal import api_implementation + +if api_implementation._c_module is not None: # pylint: disable=protected-access + UnknownFieldSet = api_implementation._c_module.UnknownFieldSet # pylint: disable=protected-access +else: + from google.protobuf.internal import decoder # pylint: disable=g-import-not-at-top + from google.protobuf.internal import wire_format # pylint: disable=g-import-not-at-top + + class UnknownField: + """A parsed unknown field.""" + + # Disallows assignment to other attributes. + __slots__ = ['_field_number', '_wire_type', '_data'] + + def __init__(self, field_number, wire_type, data): + self._field_number = field_number + self._wire_type = wire_type + self._data = data + return + + @property + def field_number(self): + return self._field_number + + @property + def wire_type(self): + return self._wire_type + + @property + def data(self): + return self._data + + class UnknownFieldSet: + """UnknownField container.""" + + # Disallows assignment to other attributes. + __slots__ = ['_values'] + + def __init__(self, msg): + + def InternalAdd(field_number, wire_type, data): + unknown_field = UnknownField(field_number, wire_type, data) + self._values.append(unknown_field) + + self._values = [] + msg_des = msg.DESCRIPTOR + # pylint: disable=protected-access + unknown_fields = msg._unknown_fields + if (msg_des.has_options and + msg_des.GetOptions().message_set_wire_format): + local_decoder = decoder.UnknownMessageSetItemDecoder() + for _, buffer in unknown_fields: + (field_number, data) = local_decoder(memoryview(buffer)) + InternalAdd(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED, data) + else: + for tag_bytes, buffer in unknown_fields: + field_number, wire_type = decoder.DecodeTag(tag_bytes) + if field_number == 0: + raise RuntimeError('Field number 0 is illegal.') + (data, _) = decoder._DecodeUnknownField( + memoryview(buffer), 0, len(buffer), field_number, wire_type + ) + InternalAdd(field_number, wire_type, data) + + def __getitem__(self, index): + size = len(self._values) + if index < 0: + index += size + if index < 0 or index >= size: + raise IndexError('index %d out of range'.index) + + return self._values[index] + + def __len__(self): + return len(self._values) + + def __iter__(self): + return iter(self._values) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/util/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/util/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/wrappers_pb2.py b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/wrappers_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..88c1e1720c363e1db1d8b472ec14811c3574f526 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/protobuf/wrappers_pb2.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Generated by the protocol buffer compiler. DO NOT EDIT! +# NO CHECKED-IN PROTOBUF GENCODE +# source: google/protobuf/wrappers.proto +# Protobuf Python Version: 6.33.6 +"""Generated protocol buffer code.""" +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import runtime_version as _runtime_version +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder +_runtime_version.ValidateProtobufRuntimeVersion( + _runtime_version.Domain.PUBLIC, + 6, + 33, + 6, + '', + 'google/protobuf/wrappers.proto' +) +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1egoogle/protobuf/wrappers.proto\x12\x0fgoogle.protobuf\"#\n\x0b\x44oubleValue\x12\x14\n\x05value\x18\x01 \x01(\x01R\x05value\"\"\n\nFloatValue\x12\x14\n\x05value\x18\x01 \x01(\x02R\x05value\"\"\n\nInt64Value\x12\x14\n\x05value\x18\x01 \x01(\x03R\x05value\"#\n\x0bUInt64Value\x12\x14\n\x05value\x18\x01 \x01(\x04R\x05value\"\"\n\nInt32Value\x12\x14\n\x05value\x18\x01 \x01(\x05R\x05value\"#\n\x0bUInt32Value\x12\x14\n\x05value\x18\x01 \x01(\rR\x05value\"!\n\tBoolValue\x12\x14\n\x05value\x18\x01 \x01(\x08R\x05value\"#\n\x0bStringValue\x12\x14\n\x05value\x18\x01 \x01(\tR\x05value\"\"\n\nBytesValue\x12\x14\n\x05value\x18\x01 \x01(\x0cR\x05valueB\x83\x01\n\x13\x63om.google.protobufB\rWrappersProtoP\x01Z1google.golang.org/protobuf/types/known/wrapperspb\xf8\x01\x01\xa2\x02\x03GPB\xaa\x02\x1eGoogle.Protobuf.WellKnownTypesb\x06proto3') + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'google.protobuf.wrappers_pb2', _globals) +if not _descriptor._USE_C_DESCRIPTORS: + _globals['DESCRIPTOR']._loaded_options = None + _globals['DESCRIPTOR']._serialized_options = b'\n\023com.google.protobufB\rWrappersProtoP\001Z1google.golang.org/protobuf/types/known/wrapperspb\370\001\001\242\002\003GPB\252\002\036Google.Protobuf.WellKnownTypes' + _globals['_DOUBLEVALUE']._serialized_start=51 + _globals['_DOUBLEVALUE']._serialized_end=86 + _globals['_FLOATVALUE']._serialized_start=88 + _globals['_FLOATVALUE']._serialized_end=122 + _globals['_INT64VALUE']._serialized_start=124 + _globals['_INT64VALUE']._serialized_end=158 + _globals['_UINT64VALUE']._serialized_start=160 + _globals['_UINT64VALUE']._serialized_end=195 + _globals['_INT32VALUE']._serialized_start=197 + _globals['_INT32VALUE']._serialized_end=231 + _globals['_UINT32VALUE']._serialized_start=233 + _globals['_UINT32VALUE']._serialized_end=268 + _globals['_BOOLVALUE']._serialized_start=270 + _globals['_BOOLVALUE']._serialized_end=303 + _globals['_STRINGVALUE']._serialized_start=305 + _globals['_STRINGVALUE']._serialized_end=340 + _globals['_BYTESVALUE']._serialized_start=342 + _globals['_BYTESVALUE']._serialized_end=376 +# @@protoc_insertion_point(module_scope) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..68b6fd4755298ac9eed08808fea464ede9b2e18c --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub/__init__.py @@ -0,0 +1,181 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed 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. +# +from google.pubsub import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.pubsub_v1.services.publisher.async_client import PublisherAsyncClient +from google.pubsub_v1.services.publisher.client import PublisherClient +from google.pubsub_v1.services.schema_service.async_client import ( + SchemaServiceAsyncClient, +) +from google.pubsub_v1.services.schema_service.client import SchemaServiceClient +from google.pubsub_v1.services.subscriber.async_client import SubscriberAsyncClient +from google.pubsub_v1.services.subscriber.client import SubscriberClient +from google.pubsub_v1.types.pubsub import ( + AcknowledgeRequest, + AIInference, + BigQueryConfig, + BigtableConfig, + CloudStorageConfig, + CreateSnapshotRequest, + DeadLetterPolicy, + DeleteSnapshotRequest, + DeleteSubscriptionRequest, + DeleteTopicRequest, + DetachSubscriptionRequest, + DetachSubscriptionResponse, + ExpirationPolicy, + GetSnapshotRequest, + GetSubscriptionRequest, + GetTopicRequest, + IngestionDataSourceSettings, + IngestionFailureEvent, + JavaScriptUDF, + ListSnapshotsRequest, + ListSnapshotsResponse, + ListSubscriptionsRequest, + ListSubscriptionsResponse, + ListTopicSnapshotsRequest, + ListTopicSnapshotsResponse, + ListTopicsRequest, + ListTopicsResponse, + ListTopicSubscriptionsRequest, + ListTopicSubscriptionsResponse, + MessageStoragePolicy, + MessageTransform, + ModifyAckDeadlineRequest, + ModifyPushConfigRequest, + PlatformLogsSettings, + PublishRequest, + PublishResponse, + PubsubMessage, + PullRequest, + PullResponse, + PushConfig, + ReceivedMessage, + RetryPolicy, + SchemaSettings, + SeekRequest, + SeekResponse, + Snapshot, + StreamingPullRequest, + StreamingPullResponse, + Subscription, + Topic, + UpdateSnapshotRequest, + UpdateSubscriptionRequest, + UpdateTopicRequest, +) +from google.pubsub_v1.types.schema import ( + CommitSchemaRequest, + CreateSchemaRequest, + DeleteSchemaRequest, + DeleteSchemaRevisionRequest, + Encoding, + GetSchemaRequest, + ListSchemaRevisionsRequest, + ListSchemaRevisionsResponse, + ListSchemasRequest, + ListSchemasResponse, + RollbackSchemaRequest, + Schema, + SchemaView, + ValidateMessageRequest, + ValidateMessageResponse, + ValidateSchemaRequest, + ValidateSchemaResponse, +) + +__all__ = ( + "PublisherClient", + "PublisherAsyncClient", + "SchemaServiceClient", + "SchemaServiceAsyncClient", + "SubscriberClient", + "SubscriberAsyncClient", + "AcknowledgeRequest", + "AIInference", + "BigQueryConfig", + "BigtableConfig", + "CloudStorageConfig", + "CreateSnapshotRequest", + "DeadLetterPolicy", + "DeleteSnapshotRequest", + "DeleteSubscriptionRequest", + "DeleteTopicRequest", + "DetachSubscriptionRequest", + "DetachSubscriptionResponse", + "ExpirationPolicy", + "GetSnapshotRequest", + "GetSubscriptionRequest", + "GetTopicRequest", + "IngestionDataSourceSettings", + "IngestionFailureEvent", + "JavaScriptUDF", + "ListSnapshotsRequest", + "ListSnapshotsResponse", + "ListSubscriptionsRequest", + "ListSubscriptionsResponse", + "ListTopicSnapshotsRequest", + "ListTopicSnapshotsResponse", + "ListTopicsRequest", + "ListTopicsResponse", + "ListTopicSubscriptionsRequest", + "ListTopicSubscriptionsResponse", + "MessageStoragePolicy", + "MessageTransform", + "ModifyAckDeadlineRequest", + "ModifyPushConfigRequest", + "PlatformLogsSettings", + "PublishRequest", + "PublishResponse", + "PubsubMessage", + "PullRequest", + "PullResponse", + "PushConfig", + "ReceivedMessage", + "RetryPolicy", + "SchemaSettings", + "SeekRequest", + "SeekResponse", + "Snapshot", + "StreamingPullRequest", + "StreamingPullResponse", + "Subscription", + "Topic", + "UpdateSnapshotRequest", + "UpdateSubscriptionRequest", + "UpdateTopicRequest", + "CommitSchemaRequest", + "CreateSchemaRequest", + "DeleteSchemaRequest", + "DeleteSchemaRevisionRequest", + "GetSchemaRequest", + "ListSchemaRevisionsRequest", + "ListSchemaRevisionsResponse", + "ListSchemasRequest", + "ListSchemasResponse", + "RollbackSchemaRequest", + "Schema", + "ValidateMessageRequest", + "ValidateMessageResponse", + "ValidateSchemaRequest", + "ValidateSchemaResponse", + "Encoding", + "SchemaView", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub/gapic_version.py b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub/gapic_version.py new file mode 100644 index 0000000000000000000000000000000000000000..612867825c933cfc4aaf9d871dffa79edd2b8f53 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed 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. +# +__version__ = "2.37.0" # {x-release-please-version} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub/py.typed b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..1cec9a5ba1ab14b50346b52bb8ffee6717579ec4 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-pubsub package uses inline types. diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..27f974a4070d44614319a0ad23b7665fc00fe17a --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/__init__.py @@ -0,0 +1,281 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed 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. +# +import sys + +import google.api_core as api_core + +from google.pubsub_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + +if sys.version_info >= (3, 8): # pragma: NO COVER + from importlib import metadata +else: # pragma: NO COVER + # TODO(https://github.com/googleapis/python-api-core/issues/835): Remove + # this code path once we drop support for Python 3.7 + import importlib_metadata as metadata + + +from .services.publisher import PublisherAsyncClient, PublisherClient +from .services.schema_service import SchemaServiceAsyncClient, SchemaServiceClient +from .services.subscriber import SubscriberAsyncClient, SubscriberClient +from .types.pubsub import ( + AcknowledgeRequest, + AIInference, + BigQueryConfig, + BigtableConfig, + CloudStorageConfig, + CreateSnapshotRequest, + DeadLetterPolicy, + DeleteSnapshotRequest, + DeleteSubscriptionRequest, + DeleteTopicRequest, + DetachSubscriptionRequest, + DetachSubscriptionResponse, + ExpirationPolicy, + GetSnapshotRequest, + GetSubscriptionRequest, + GetTopicRequest, + IngestionDataSourceSettings, + IngestionFailureEvent, + JavaScriptUDF, + ListSnapshotsRequest, + ListSnapshotsResponse, + ListSubscriptionsRequest, + ListSubscriptionsResponse, + ListTopicSnapshotsRequest, + ListTopicSnapshotsResponse, + ListTopicsRequest, + ListTopicsResponse, + ListTopicSubscriptionsRequest, + ListTopicSubscriptionsResponse, + MessageStoragePolicy, + MessageTransform, + ModifyAckDeadlineRequest, + ModifyPushConfigRequest, + PlatformLogsSettings, + PublishRequest, + PublishResponse, + PubsubMessage, + PullRequest, + PullResponse, + PushConfig, + ReceivedMessage, + RetryPolicy, + SchemaSettings, + SeekRequest, + SeekResponse, + Snapshot, + StreamingPullRequest, + StreamingPullResponse, + Subscription, + Topic, + UpdateSnapshotRequest, + UpdateSubscriptionRequest, + UpdateTopicRequest, +) +from .types.schema import ( + CommitSchemaRequest, + CreateSchemaRequest, + DeleteSchemaRequest, + DeleteSchemaRevisionRequest, + Encoding, + GetSchemaRequest, + ListSchemaRevisionsRequest, + ListSchemaRevisionsResponse, + ListSchemasRequest, + ListSchemasResponse, + RollbackSchemaRequest, + Schema, + SchemaView, + ValidateMessageRequest, + ValidateMessageResponse, + ValidateSchemaRequest, + ValidateSchemaResponse, +) + +if hasattr(api_core, "check_python_version") and hasattr( + api_core, "check_dependency_versions" +): # pragma: NO COVER + api_core.check_python_version("google.pubsub_v1") # type: ignore + api_core.check_dependency_versions("google.pubsub_v1") # type: ignore +else: # pragma: NO COVER + # An older version of api_core is installed which does not define the + # functions above. We do equivalent checks manually. + try: + import sys + import warnings + + _py_version_str = sys.version.split()[0] + _package_label = "google.pubsub_v1" + if sys.version_info < (3, 9): + warnings.warn( + "You are using a non-supported Python version " + + f"({_py_version_str}). Google will not post any further " + + f"updates to {_package_label} supporting this Python version. " + + "Please upgrade to the latest Python version, or at " + + f"least to Python 3.9, and then update {_package_label}.", + FutureWarning, + ) + if sys.version_info[:2] == (3, 9): + warnings.warn( + f"You are using a Python version ({_py_version_str}) " + + f"which Google will stop supporting in {_package_label} in " + + "January 2026. Please " + + "upgrade to the latest Python version, or at " + + "least to Python 3.10, before then, and " + + f"then update {_package_label}.", + FutureWarning, + ) + + def parse_version_to_tuple(version_string: str): + """Safely converts a semantic version string to a comparable tuple of integers. + Example: "4.25.8" -> (4, 25, 8) + Ignores non-numeric parts and handles common version formats. + Args: + version_string: Version string in the format "x.y.z" or "x.y.z" + Returns: + Tuple of integers for the parsed version string. + """ + parts = [] + for part in version_string.split("."): + try: + parts.append(int(part)) + except ValueError: + # If it's a non-numeric part (e.g., '1.0.0b1' -> 'b1'), stop here. + # This is a simplification compared to 'packaging.parse_version', but sufficient + # for comparing strictly numeric semantic versions. + break + return tuple(parts) + + def _get_version(dependency_name): + try: + version_string: str = metadata.version(dependency_name) + parsed_version = parse_version_to_tuple(version_string) + return (parsed_version, version_string) + except Exception: + # Catch exceptions from metadata.version() (e.g., PackageNotFoundError) + # or errors during parse_version_to_tuple + return (None, "--") + + _dependency_package = "google.protobuf" + _next_supported_version = "4.25.8" + _next_supported_version_tuple = (4, 25, 8) + _recommendation = " (we recommend 6.x)" + (_version_used, _version_used_string) = _get_version(_dependency_package) + if _version_used and _version_used < _next_supported_version_tuple: + warnings.warn( + f"Package {_package_label} depends on " + + f"{_dependency_package}, currently installed at version " + + f"{_version_used_string}. Future updates to " + + f"{_package_label} will require {_dependency_package} at " + + f"version {_next_supported_version} or higher{_recommendation}." + + " Please ensure " + + "that either (a) your Python environment doesn't pin the " + + f"version of {_dependency_package}, so that updates to " + + f"{_package_label} can require the higher version, or " + + "(b) you manually update your Python environment to use at " + + f"least version {_next_supported_version} of " + + f"{_dependency_package}.", + FutureWarning, + ) + except Exception: + warnings.warn( + "Could not determine the version of Python " + + "currently being used. To continue receiving " + + "updates for {_package_label}, ensure you are " + + "using a supported version of Python; see " + + "https://devguide.python.org/versions/" + ) + +__all__ = ( + "PublisherAsyncClient", + "SchemaServiceAsyncClient", + "SubscriberAsyncClient", + "AIInference", + "AcknowledgeRequest", + "BigQueryConfig", + "BigtableConfig", + "CloudStorageConfig", + "CommitSchemaRequest", + "CreateSchemaRequest", + "CreateSnapshotRequest", + "DeadLetterPolicy", + "DeleteSchemaRequest", + "DeleteSchemaRevisionRequest", + "DeleteSnapshotRequest", + "DeleteSubscriptionRequest", + "DeleteTopicRequest", + "DetachSubscriptionRequest", + "DetachSubscriptionResponse", + "Encoding", + "ExpirationPolicy", + "GetSchemaRequest", + "GetSnapshotRequest", + "GetSubscriptionRequest", + "GetTopicRequest", + "IngestionDataSourceSettings", + "IngestionFailureEvent", + "JavaScriptUDF", + "ListSchemaRevisionsRequest", + "ListSchemaRevisionsResponse", + "ListSchemasRequest", + "ListSchemasResponse", + "ListSnapshotsRequest", + "ListSnapshotsResponse", + "ListSubscriptionsRequest", + "ListSubscriptionsResponse", + "ListTopicSnapshotsRequest", + "ListTopicSnapshotsResponse", + "ListTopicSubscriptionsRequest", + "ListTopicSubscriptionsResponse", + "ListTopicsRequest", + "ListTopicsResponse", + "MessageStoragePolicy", + "MessageTransform", + "ModifyAckDeadlineRequest", + "ModifyPushConfigRequest", + "PlatformLogsSettings", + "PublishRequest", + "PublishResponse", + "PublisherClient", + "PubsubMessage", + "PullRequest", + "PullResponse", + "PushConfig", + "ReceivedMessage", + "RetryPolicy", + "RollbackSchemaRequest", + "Schema", + "SchemaServiceClient", + "SchemaSettings", + "SchemaView", + "SeekRequest", + "SeekResponse", + "Snapshot", + "StreamingPullRequest", + "StreamingPullResponse", + "SubscriberClient", + "Subscription", + "Topic", + "UpdateSnapshotRequest", + "UpdateSubscriptionRequest", + "UpdateTopicRequest", + "ValidateMessageRequest", + "ValidateMessageResponse", + "ValidateSchemaRequest", + "ValidateSchemaResponse", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/gapic_metadata.json b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/gapic_metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..4a8f51a516edc6bf38d99534d9f44482245bd487 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/gapic_metadata.json @@ -0,0 +1,591 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.pubsub_v1", + "protoPackage": "google.pubsub.v1", + "schema": "1.0", + "services": { + "Publisher": { + "clients": { + "grpc": { + "libraryClient": "PublisherClient", + "rpcs": { + "CreateTopic": { + "methods": [ + "create_topic" + ] + }, + "DeleteTopic": { + "methods": [ + "delete_topic" + ] + }, + "DetachSubscription": { + "methods": [ + "detach_subscription" + ] + }, + "GetTopic": { + "methods": [ + "get_topic" + ] + }, + "ListTopicSnapshots": { + "methods": [ + "list_topic_snapshots" + ] + }, + "ListTopicSubscriptions": { + "methods": [ + "list_topic_subscriptions" + ] + }, + "ListTopics": { + "methods": [ + "list_topics" + ] + }, + "Publish": { + "methods": [ + "publish" + ] + }, + "UpdateTopic": { + "methods": [ + "update_topic" + ] + } + } + }, + "grpc-async": { + "libraryClient": "PublisherAsyncClient", + "rpcs": { + "CreateTopic": { + "methods": [ + "create_topic" + ] + }, + "DeleteTopic": { + "methods": [ + "delete_topic" + ] + }, + "DetachSubscription": { + "methods": [ + "detach_subscription" + ] + }, + "GetTopic": { + "methods": [ + "get_topic" + ] + }, + "ListTopicSnapshots": { + "methods": [ + "list_topic_snapshots" + ] + }, + "ListTopicSubscriptions": { + "methods": [ + "list_topic_subscriptions" + ] + }, + "ListTopics": { + "methods": [ + "list_topics" + ] + }, + "Publish": { + "methods": [ + "publish" + ] + }, + "UpdateTopic": { + "methods": [ + "update_topic" + ] + } + } + }, + "rest": { + "libraryClient": "PublisherClient", + "rpcs": { + "CreateTopic": { + "methods": [ + "create_topic" + ] + }, + "DeleteTopic": { + "methods": [ + "delete_topic" + ] + }, + "DetachSubscription": { + "methods": [ + "detach_subscription" + ] + }, + "GetTopic": { + "methods": [ + "get_topic" + ] + }, + "ListTopicSnapshots": { + "methods": [ + "list_topic_snapshots" + ] + }, + "ListTopicSubscriptions": { + "methods": [ + "list_topic_subscriptions" + ] + }, + "ListTopics": { + "methods": [ + "list_topics" + ] + }, + "Publish": { + "methods": [ + "publish" + ] + }, + "UpdateTopic": { + "methods": [ + "update_topic" + ] + } + } + } + } + }, + "SchemaService": { + "clients": { + "grpc": { + "libraryClient": "SchemaServiceClient", + "rpcs": { + "CommitSchema": { + "methods": [ + "commit_schema" + ] + }, + "CreateSchema": { + "methods": [ + "create_schema" + ] + }, + "DeleteSchema": { + "methods": [ + "delete_schema" + ] + }, + "DeleteSchemaRevision": { + "methods": [ + "delete_schema_revision" + ] + }, + "GetSchema": { + "methods": [ + "get_schema" + ] + }, + "ListSchemaRevisions": { + "methods": [ + "list_schema_revisions" + ] + }, + "ListSchemas": { + "methods": [ + "list_schemas" + ] + }, + "RollbackSchema": { + "methods": [ + "rollback_schema" + ] + }, + "ValidateMessage": { + "methods": [ + "validate_message" + ] + }, + "ValidateSchema": { + "methods": [ + "validate_schema" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SchemaServiceAsyncClient", + "rpcs": { + "CommitSchema": { + "methods": [ + "commit_schema" + ] + }, + "CreateSchema": { + "methods": [ + "create_schema" + ] + }, + "DeleteSchema": { + "methods": [ + "delete_schema" + ] + }, + "DeleteSchemaRevision": { + "methods": [ + "delete_schema_revision" + ] + }, + "GetSchema": { + "methods": [ + "get_schema" + ] + }, + "ListSchemaRevisions": { + "methods": [ + "list_schema_revisions" + ] + }, + "ListSchemas": { + "methods": [ + "list_schemas" + ] + }, + "RollbackSchema": { + "methods": [ + "rollback_schema" + ] + }, + "ValidateMessage": { + "methods": [ + "validate_message" + ] + }, + "ValidateSchema": { + "methods": [ + "validate_schema" + ] + } + } + }, + "rest": { + "libraryClient": "SchemaServiceClient", + "rpcs": { + "CommitSchema": { + "methods": [ + "commit_schema" + ] + }, + "CreateSchema": { + "methods": [ + "create_schema" + ] + }, + "DeleteSchema": { + "methods": [ + "delete_schema" + ] + }, + "DeleteSchemaRevision": { + "methods": [ + "delete_schema_revision" + ] + }, + "GetSchema": { + "methods": [ + "get_schema" + ] + }, + "ListSchemaRevisions": { + "methods": [ + "list_schema_revisions" + ] + }, + "ListSchemas": { + "methods": [ + "list_schemas" + ] + }, + "RollbackSchema": { + "methods": [ + "rollback_schema" + ] + }, + "ValidateMessage": { + "methods": [ + "validate_message" + ] + }, + "ValidateSchema": { + "methods": [ + "validate_schema" + ] + } + } + } + } + }, + "Subscriber": { + "clients": { + "grpc": { + "libraryClient": "SubscriberClient", + "rpcs": { + "Acknowledge": { + "methods": [ + "acknowledge" + ] + }, + "CreateSnapshot": { + "methods": [ + "create_snapshot" + ] + }, + "CreateSubscription": { + "methods": [ + "create_subscription" + ] + }, + "DeleteSnapshot": { + "methods": [ + "delete_snapshot" + ] + }, + "DeleteSubscription": { + "methods": [ + "delete_subscription" + ] + }, + "GetSnapshot": { + "methods": [ + "get_snapshot" + ] + }, + "GetSubscription": { + "methods": [ + "get_subscription" + ] + }, + "ListSnapshots": { + "methods": [ + "list_snapshots" + ] + }, + "ListSubscriptions": { + "methods": [ + "list_subscriptions" + ] + }, + "ModifyAckDeadline": { + "methods": [ + "modify_ack_deadline" + ] + }, + "ModifyPushConfig": { + "methods": [ + "modify_push_config" + ] + }, + "Pull": { + "methods": [ + "pull" + ] + }, + "Seek": { + "methods": [ + "seek" + ] + }, + "StreamingPull": { + "methods": [ + "streaming_pull" + ] + }, + "UpdateSnapshot": { + "methods": [ + "update_snapshot" + ] + }, + "UpdateSubscription": { + "methods": [ + "update_subscription" + ] + } + } + }, + "grpc-async": { + "libraryClient": "SubscriberAsyncClient", + "rpcs": { + "Acknowledge": { + "methods": [ + "acknowledge" + ] + }, + "CreateSnapshot": { + "methods": [ + "create_snapshot" + ] + }, + "CreateSubscription": { + "methods": [ + "create_subscription" + ] + }, + "DeleteSnapshot": { + "methods": [ + "delete_snapshot" + ] + }, + "DeleteSubscription": { + "methods": [ + "delete_subscription" + ] + }, + "GetSnapshot": { + "methods": [ + "get_snapshot" + ] + }, + "GetSubscription": { + "methods": [ + "get_subscription" + ] + }, + "ListSnapshots": { + "methods": [ + "list_snapshots" + ] + }, + "ListSubscriptions": { + "methods": [ + "list_subscriptions" + ] + }, + "ModifyAckDeadline": { + "methods": [ + "modify_ack_deadline" + ] + }, + "ModifyPushConfig": { + "methods": [ + "modify_push_config" + ] + }, + "Pull": { + "methods": [ + "pull" + ] + }, + "Seek": { + "methods": [ + "seek" + ] + }, + "StreamingPull": { + "methods": [ + "streaming_pull" + ] + }, + "UpdateSnapshot": { + "methods": [ + "update_snapshot" + ] + }, + "UpdateSubscription": { + "methods": [ + "update_subscription" + ] + } + } + }, + "rest": { + "libraryClient": "SubscriberClient", + "rpcs": { + "Acknowledge": { + "methods": [ + "acknowledge" + ] + }, + "CreateSnapshot": { + "methods": [ + "create_snapshot" + ] + }, + "CreateSubscription": { + "methods": [ + "create_subscription" + ] + }, + "DeleteSnapshot": { + "methods": [ + "delete_snapshot" + ] + }, + "DeleteSubscription": { + "methods": [ + "delete_subscription" + ] + }, + "GetSnapshot": { + "methods": [ + "get_snapshot" + ] + }, + "GetSubscription": { + "methods": [ + "get_subscription" + ] + }, + "ListSnapshots": { + "methods": [ + "list_snapshots" + ] + }, + "ListSubscriptions": { + "methods": [ + "list_subscriptions" + ] + }, + "ModifyAckDeadline": { + "methods": [ + "modify_ack_deadline" + ] + }, + "ModifyPushConfig": { + "methods": [ + "modify_push_config" + ] + }, + "Pull": { + "methods": [ + "pull" + ] + }, + "Seek": { + "methods": [ + "seek" + ] + }, + "StreamingPull": { + "methods": [ + "streaming_pull" + ] + }, + "UpdateSnapshot": { + "methods": [ + "update_snapshot" + ] + }, + "UpdateSubscription": { + "methods": [ + "update_subscription" + ] + } + } + } + } + } + } +} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/gapic_version.py b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/gapic_version.py new file mode 100644 index 0000000000000000000000000000000000000000..612867825c933cfc4aaf9d871dffa79edd2b8f53 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed 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. +# +__version__ = "2.37.0" # {x-release-please-version} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/py.typed b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..1cec9a5ba1ab14b50346b52bb8ffee6717579ec4 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-pubsub package uses inline types. diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cbf94b283c704417a5e2701bd2aa9bb5519e82e3 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed 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. +# diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/publisher/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/publisher/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2a07616f9028310520b4c7058cf855704da75dd2 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/publisher/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed 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. +# +from .async_client import PublisherAsyncClient +from .client import PublisherClient + +__all__ = ( + "PublisherClient", + "PublisherAsyncClient", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/publisher/async_client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/publisher/async_client.py new file mode 100644 index 0000000000000000000000000000000000000000..b08e134b6f4a111af3c5513c67dc945dfa3eb49c --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/publisher/async_client.py @@ -0,0 +1,1700 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed 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. +# +import logging as std_logging +import re +from collections import OrderedDict +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.pubsub_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) + +from google.pubsub_v1.services.publisher import pagers +from google.pubsub_v1.types import TimeoutType, pubsub + +from .client import PublisherClient +from .transports.base import DEFAULT_CLIENT_INFO, PublisherTransport +from .transports.grpc_asyncio import PublisherGrpcAsyncIOTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class PublisherAsyncClient: + """The service that an application uses to manipulate topics, + and to send messages to a topic. + """ + + _client: PublisherClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = PublisherClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = PublisherClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = PublisherClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = PublisherClient._DEFAULT_UNIVERSE + + crypto_key_path = staticmethod(PublisherClient.crypto_key_path) + parse_crypto_key_path = staticmethod(PublisherClient.parse_crypto_key_path) + schema_path = staticmethod(PublisherClient.schema_path) + parse_schema_path = staticmethod(PublisherClient.parse_schema_path) + snapshot_path = staticmethod(PublisherClient.snapshot_path) + parse_snapshot_path = staticmethod(PublisherClient.parse_snapshot_path) + subscription_path = staticmethod(PublisherClient.subscription_path) + parse_subscription_path = staticmethod(PublisherClient.parse_subscription_path) + topic_path = staticmethod(PublisherClient.topic_path) + parse_topic_path = staticmethod(PublisherClient.parse_topic_path) + common_billing_account_path = staticmethod( + PublisherClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + PublisherClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(PublisherClient.common_folder_path) + parse_common_folder_path = staticmethod(PublisherClient.parse_common_folder_path) + common_organization_path = staticmethod(PublisherClient.common_organization_path) + parse_common_organization_path = staticmethod( + PublisherClient.parse_common_organization_path + ) + common_project_path = staticmethod(PublisherClient.common_project_path) + parse_common_project_path = staticmethod(PublisherClient.parse_common_project_path) + common_location_path = staticmethod(PublisherClient.common_location_path) + parse_common_location_path = staticmethod( + PublisherClient.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PublisherAsyncClient: The constructed client. + """ + sa_info_func = ( + PublisherClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(PublisherAsyncClient, info, *args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PublisherAsyncClient: The constructed client. + """ + sa_file_func = ( + PublisherClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(PublisherAsyncClient, filename, *args, **kwargs) + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return PublisherClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> PublisherTransport: + """Returns the transport used by the client instance. + + Returns: + PublisherTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = PublisherClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, PublisherTransport, Callable[..., PublisherTransport]] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the publisher async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,PublisherTransport,Callable[..., PublisherTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the PublisherTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = PublisherClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.pubsub_v1.PublisherAsyncClient`.", + extra={ + "serviceName": "google.pubsub.v1.Publisher", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.pubsub.v1.Publisher", + "credentialsType": None, + }, + ) + + async def create_topic( + self, + request: Optional[Union[pubsub.Topic, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: TimeoutType = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.Topic: + r"""Creates the given topic with the given name. See the [resource + name rules] + (https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names). + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + async def sample_create_topic(): + # Create a client + client = pubsub_v1.PublisherAsyncClient() + + # Initialize request argument(s) + request = pubsub_v1.Topic( + name="name_value", + ) + + # Make the request + response = await client.create_topic(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.pubsub_v1.types.Topic, dict]]): + The request object. A topic resource. + name (:class:`str`): + Required. Identifier. The name of the topic. It must + have the format ``"projects/{project}/topics/{topic}"``. + ``{topic}`` must start with a letter, and contain only + letters (``[A-Za-z]``), numbers (``[0-9]``), dashes + (``-``), underscores (``_``), periods (``.``), tildes + (``~``), plus (``+``) or percent signs (``%``). It must + be between 3 and 255 characters in length, and it must + not start with ``"goog"``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (TimeoutType): + The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.types.Topic: + A topic resource. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.Topic): + request = pubsub.Topic(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_topic + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_topic( + self, + request: Optional[Union[pubsub.UpdateTopicRequest, dict]] = None, + *, + topic: Optional[pubsub.Topic] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: TimeoutType = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.Topic: + r"""Updates an existing topic by updating the fields + specified in the update mask. Note that certain + properties of a topic are not modifiable. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + async def sample_update_topic(): + # Create a client + client = pubsub_v1.PublisherAsyncClient() + + # Initialize request argument(s) + topic = pubsub_v1.Topic() + topic.name = "name_value" + + request = pubsub_v1.UpdateTopicRequest( + topic=topic, + ) + + # Make the request + response = await client.update_topic(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.pubsub_v1.types.UpdateTopicRequest, dict]]): + The request object. Request for the UpdateTopic method. + topic (:class:`google.pubsub_v1.types.Topic`): + Required. The updated topic object. + This corresponds to the ``topic`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Indicates which fields in the provided topic + to update. Must be specified and non-empty. Note that if + ``update_mask`` contains "message_storage_policy" but + the ``message_storage_policy`` is not set in the + ``topic`` provided above, then the updated value is + determined by the policy configured at the project or + organization level. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (TimeoutType): + The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.types.Topic: + A topic resource. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [topic, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.UpdateTopicRequest): + request = pubsub.UpdateTopicRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if topic is not None: + request.topic = topic + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_topic + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("topic.name", request.topic.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def publish( + self, + request: Optional[Union[pubsub.PublishRequest, dict]] = None, + *, + topic: Optional[str] = None, + messages: Optional[MutableSequence[pubsub.PubsubMessage]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: TimeoutType = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.PublishResponse: + r"""Adds one or more messages to the topic. Returns ``NOT_FOUND`` if + the topic does not exist. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + async def sample_publish(): + # Create a client + client = pubsub_v1.PublisherAsyncClient() + + # Initialize request argument(s) + request = pubsub_v1.PublishRequest( + topic="topic_value", + ) + + # Make the request + response = await client.publish(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.pubsub_v1.types.PublishRequest, dict]]): + The request object. Request for the Publish method. + topic (:class:`str`): + Required. The messages in the request will be published + on this topic. Format is + ``projects/{project}/topics/{topic}``. + + This corresponds to the ``topic`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + messages (:class:`MutableSequence[google.pubsub_v1.types.PubsubMessage]`): + Required. The messages to publish. + This corresponds to the ``messages`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (TimeoutType): + The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.types.PublishResponse: + Response for the Publish method. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [topic, messages] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.PublishRequest): + request = pubsub.PublishRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if topic is not None: + request.topic = topic + if messages: + request.messages.extend(messages) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.publish] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("topic", request.topic),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_topic( + self, + request: Optional[Union[pubsub.GetTopicRequest, dict]] = None, + *, + topic: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: TimeoutType = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.Topic: + r"""Gets the configuration of a topic. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + async def sample_get_topic(): + # Create a client + client = pubsub_v1.PublisherAsyncClient() + + # Initialize request argument(s) + request = pubsub_v1.GetTopicRequest( + topic="topic_value", + ) + + # Make the request + response = await client.get_topic(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.pubsub_v1.types.GetTopicRequest, dict]]): + The request object. Request for the GetTopic method. + topic (:class:`str`): + Required. The name of the topic to get. Format is + ``projects/{project}/topics/{topic}``. + + This corresponds to the ``topic`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (TimeoutType): + The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.types.Topic: + A topic resource. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [topic] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.GetTopicRequest): + request = pubsub.GetTopicRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if topic is not None: + request.topic = topic + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_topic + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("topic", request.topic),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_topics( + self, + request: Optional[Union[pubsub.ListTopicsRequest, dict]] = None, + *, + project: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: TimeoutType = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListTopicsAsyncPager: + r"""Lists matching topics. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + async def sample_list_topics(): + # Create a client + client = pubsub_v1.PublisherAsyncClient() + + # Initialize request argument(s) + request = pubsub_v1.ListTopicsRequest( + project="project_value", + ) + + # Make the request + page_result = client.list_topics(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.pubsub_v1.types.ListTopicsRequest, dict]]): + The request object. Request for the ``ListTopics`` method. + project (:class:`str`): + Required. The name of the project in which to list + topics. Format is ``projects/{project-id}``. + + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (TimeoutType): + The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.services.publisher.pagers.ListTopicsAsyncPager: + Response for the ListTopics method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [project] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.ListTopicsRequest): + request = pubsub.ListTopicsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_topics + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("project", request.project),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListTopicsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_topic_subscriptions( + self, + request: Optional[Union[pubsub.ListTopicSubscriptionsRequest, dict]] = None, + *, + topic: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: TimeoutType = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListTopicSubscriptionsAsyncPager: + r"""Lists the names of the attached subscriptions on this + topic. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + async def sample_list_topic_subscriptions(): + # Create a client + client = pubsub_v1.PublisherAsyncClient() + + # Initialize request argument(s) + request = pubsub_v1.ListTopicSubscriptionsRequest( + topic="topic_value", + ) + + # Make the request + page_result = client.list_topic_subscriptions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.pubsub_v1.types.ListTopicSubscriptionsRequest, dict]]): + The request object. Request for the ``ListTopicSubscriptions`` method. + topic (:class:`str`): + Required. The name of the topic that subscriptions are + attached to. Format is + ``projects/{project}/topics/{topic}``. + + This corresponds to the ``topic`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (TimeoutType): + The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.services.publisher.pagers.ListTopicSubscriptionsAsyncPager: + Response for the ListTopicSubscriptions method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [topic] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.ListTopicSubscriptionsRequest): + request = pubsub.ListTopicSubscriptionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if topic is not None: + request.topic = topic + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_topic_subscriptions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("topic", request.topic),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListTopicSubscriptionsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_topic_snapshots( + self, + request: Optional[Union[pubsub.ListTopicSnapshotsRequest, dict]] = None, + *, + topic: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: TimeoutType = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListTopicSnapshotsAsyncPager: + r"""Lists the names of the snapshots on this topic. Snapshots are + used in + `Seek `__ + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + async def sample_list_topic_snapshots(): + # Create a client + client = pubsub_v1.PublisherAsyncClient() + + # Initialize request argument(s) + request = pubsub_v1.ListTopicSnapshotsRequest( + topic="topic_value", + ) + + # Make the request + page_result = client.list_topic_snapshots(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.pubsub_v1.types.ListTopicSnapshotsRequest, dict]]): + The request object. Request for the ``ListTopicSnapshots`` method. + topic (:class:`str`): + Required. The name of the topic that snapshots are + attached to. Format is + ``projects/{project}/topics/{topic}``. + + This corresponds to the ``topic`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (TimeoutType): + The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.services.publisher.pagers.ListTopicSnapshotsAsyncPager: + Response for the ListTopicSnapshots method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [topic] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.ListTopicSnapshotsRequest): + request = pubsub.ListTopicSnapshotsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if topic is not None: + request.topic = topic + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_topic_snapshots + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("topic", request.topic),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListTopicSnapshotsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_topic( + self, + request: Optional[Union[pubsub.DeleteTopicRequest, dict]] = None, + *, + topic: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: TimeoutType = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the topic with the given name. Returns ``NOT_FOUND`` if + the topic does not exist. After a topic is deleted, a new topic + may be created with the same name; this is an entirely new topic + with none of the old configuration or subscriptions. Existing + subscriptions to this topic are not deleted, but their ``topic`` + field is set to ``_deleted-topic_``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + async def sample_delete_topic(): + # Create a client + client = pubsub_v1.PublisherAsyncClient() + + # Initialize request argument(s) + request = pubsub_v1.DeleteTopicRequest( + topic="topic_value", + ) + + # Make the request + await client.delete_topic(request=request) + + Args: + request (Optional[Union[google.pubsub_v1.types.DeleteTopicRequest, dict]]): + The request object. Request for the ``DeleteTopic`` method. + topic (:class:`str`): + Required. Name of the topic to delete. Format is + ``projects/{project}/topics/{topic}``. + + This corresponds to the ``topic`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (TimeoutType): + The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [topic] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.DeleteTopicRequest): + request = pubsub.DeleteTopicRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if topic is not None: + request.topic = topic + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_topic + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("topic", request.topic),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def detach_subscription( + self, + request: Optional[Union[pubsub.DetachSubscriptionRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: TimeoutType = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.DetachSubscriptionResponse: + r"""Detaches a subscription from this topic. All messages retained + in the subscription are dropped. Subsequent ``Pull`` and + ``StreamingPull`` requests will return FAILED_PRECONDITION. If + the subscription is a push subscription, pushes to the endpoint + will stop. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + async def sample_detach_subscription(): + # Create a client + client = pubsub_v1.PublisherAsyncClient() + + # Initialize request argument(s) + request = pubsub_v1.DetachSubscriptionRequest( + subscription="subscription_value", + ) + + # Make the request + response = await client.detach_subscription(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.pubsub_v1.types.DetachSubscriptionRequest, dict]]): + The request object. Request for the DetachSubscription + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (TimeoutType): + The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.types.DetachSubscriptionResponse: + Response for the DetachSubscription + method. Reserved for future use. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.DetachSubscriptionRequest): + request = pubsub.DetachSubscriptionRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.detach_subscription + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("subscription", request.subscription),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: TimeoutType = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (TimeoutType): + The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: TimeoutType = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if + any, should be retried. + timeout (TimeoutType): + The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: TimeoutType = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (TimeoutType): + The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[ + self._client._transport.test_iam_permissions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "PublisherAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + client_library_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("PublisherAsyncClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/publisher/client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/publisher/client.py new file mode 100644 index 0000000000000000000000000000000000000000..51dc1fdd13aa7c567741bb180b79c6d4de91e5a6 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/publisher/client.py @@ -0,0 +1,2208 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed 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. +# +import json +import functools +import grpc +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.pubsub_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) + +from google.pubsub_v1.services.publisher import pagers +from google.pubsub_v1.types import TimeoutType, pubsub + +from .transports.base import DEFAULT_CLIENT_INFO, PublisherTransport +from .transports.grpc import PublisherGrpcTransport +from .transports.grpc_asyncio import PublisherGrpcAsyncIOTransport +from .transports.rest import PublisherRestTransport + + +class PublisherClientMeta(type): + """Metaclass for the Publisher client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[PublisherTransport]] + _transport_registry["grpc"] = PublisherGrpcTransport + _transport_registry["grpc_asyncio"] = PublisherGrpcAsyncIOTransport + _transport_registry["rest"] = PublisherRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[PublisherTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class PublisherClient(metaclass=PublisherClientMeta): + """The service that an application uses to manipulate topics, + and to send messages to a topic. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + Optional[str]: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # Could not parse api_endpoint; return as-is. + return api_endpoint + + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + _DEFAULT_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/pubsub", + ) + SERVICE_ADDRESS = "pubsub.googleapis.com:443" + """The default address of the service.""" + DEFAULT_ENDPOINT = "pubsub.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "pubsub.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PublisherClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + PublisherClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> PublisherTransport: + """Returns the transport used by the client instance. + + Returns: + PublisherTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def crypto_key_path( + project: str, + location: str, + key_ring: str, + crypto_key: str, + ) -> str: + """Returns a fully-qualified crypto_key string.""" + return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format( + project=project, + location=location, + key_ring=key_ring, + crypto_key=crypto_key, + ) + + @staticmethod + def parse_crypto_key_path(path: str) -> Dict[str, str]: + """Parses a crypto_key path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def schema_path( + project: str, + schema: str, + ) -> str: + """Returns a fully-qualified schema string.""" + return "projects/{project}/schemas/{schema}".format( + project=project, + schema=schema, + ) + + @staticmethod + def parse_schema_path(path: str) -> Dict[str, str]: + """Parses a schema path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/schemas/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def snapshot_path( + project: str, + snapshot: str, + ) -> str: + """Returns a fully-qualified snapshot string.""" + return "projects/{project}/snapshots/{snapshot}".format( + project=project, + snapshot=snapshot, + ) + + @staticmethod + def parse_snapshot_path(path: str) -> Dict[str, str]: + """Parses a snapshot path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/snapshots/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def subscription_path( + project: str, + subscription: str, + ) -> str: + """Returns a fully-qualified subscription string.""" + return "projects/{project}/subscriptions/{subscription}".format( + project=project, + subscription=subscription, + ) + + @staticmethod + def parse_subscription_path(path: str) -> Dict[str, str]: + """Parses a subscription path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/subscriptions/(?P.+?)$", path + ) + return m.groupdict() if m else {} + + @staticmethod + def topic_path( + project: str, + topic: str, + ) -> str: + """Returns a fully-qualified topic string.""" + return "projects/{project}/topics/{topic}".format( + project=project, + topic=topic, + ) + + @staticmethod + def parse_topic_path(path: str) -> Dict[str, str]: + """Parses a topic path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/topics/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = PublisherClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = PublisherClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ) -> str: + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = PublisherClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = PublisherClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = PublisherClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = PublisherClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, PublisherTransport, Callable[..., PublisherTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the publisher client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,PublisherTransport,Callable[..., PublisherTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the PublisherTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + PublisherClient._read_environment_variables() + ) + self._client_cert_source = PublisherClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = PublisherClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, PublisherTransport) + if transport_provided: + # transport is a PublisherTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(PublisherTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = self._api_endpoint or PublisherClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[PublisherTransport], Callable[..., PublisherTransport] + ] = ( + PublisherClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., PublisherTransport], transport) + ) + # initialize with the provided callable or the passed in class + emulator_host = os.environ.get("PUBSUB_EMULATOR_HOST") + if emulator_host: + if issubclass(transport_init, type(self)._transport_registry["grpc"]): # type: ignore + channel = grpc.insecure_channel(target=emulator_host) + else: + channel = grpc.aio.insecure_channel(target=emulator_host) + transport_init = functools.partial(transport_init, channel=channel) + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.pubsub_v1.PublisherClient`.", + extra={ + "serviceName": "google.pubsub.v1.Publisher", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.pubsub.v1.Publisher", + "credentialsType": None, + }, + ) + + def create_topic( + self, + request: Optional[Union[pubsub.Topic, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: TimeoutType = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.Topic: + r"""Creates the given topic with the given name. See the [resource + name rules] + (https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names). + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + def sample_create_topic(): + # Create a client + client = pubsub_v1.PublisherClient() + + # Initialize request argument(s) + request = pubsub_v1.Topic( + name="name_value", + ) + + # Make the request + response = client.create_topic(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.pubsub_v1.types.Topic, dict]): + The request object. A topic resource. + name (str): + Required. Identifier. The name of the topic. It must + have the format ``"projects/{project}/topics/{topic}"``. + ``{topic}`` must start with a letter, and contain only + letters (``[A-Za-z]``), numbers (``[0-9]``), dashes + (``-``), underscores (``_``), periods (``.``), tildes + (``~``), plus (``+``) or percent signs (``%``). It must + be between 3 and 255 characters in length, and it must + not start with ``"goog"``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (TimeoutType): + The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.types.Topic: + A topic resource. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.Topic): + request = pubsub.Topic(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_topic] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_topic( + self, + request: Optional[Union[pubsub.UpdateTopicRequest, dict]] = None, + *, + topic: Optional[pubsub.Topic] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: TimeoutType = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.Topic: + r"""Updates an existing topic by updating the fields + specified in the update mask. Note that certain + properties of a topic are not modifiable. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + def sample_update_topic(): + # Create a client + client = pubsub_v1.PublisherClient() + + # Initialize request argument(s) + topic = pubsub_v1.Topic() + topic.name = "name_value" + + request = pubsub_v1.UpdateTopicRequest( + topic=topic, + ) + + # Make the request + response = client.update_topic(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.pubsub_v1.types.UpdateTopicRequest, dict]): + The request object. Request for the UpdateTopic method. + topic (google.pubsub_v1.types.Topic): + Required. The updated topic object. + This corresponds to the ``topic`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Indicates which fields in the provided topic + to update. Must be specified and non-empty. Note that if + ``update_mask`` contains "message_storage_policy" but + the ``message_storage_policy`` is not set in the + ``topic`` provided above, then the updated value is + determined by the policy configured at the project or + organization level. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (TimeoutType): + The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.types.Topic: + A topic resource. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [topic, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.UpdateTopicRequest): + request = pubsub.UpdateTopicRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if topic is not None: + request.topic = topic + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_topic] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("topic.name", request.topic.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def publish( + self, + request: Optional[Union[pubsub.PublishRequest, dict]] = None, + *, + topic: Optional[str] = None, + messages: Optional[MutableSequence[pubsub.PubsubMessage]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: TimeoutType = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.PublishResponse: + r"""Adds one or more messages to the topic. Returns ``NOT_FOUND`` if + the topic does not exist. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + def sample_publish(): + # Create a client + client = pubsub_v1.PublisherClient() + + # Initialize request argument(s) + request = pubsub_v1.PublishRequest( + topic="topic_value", + ) + + # Make the request + response = client.publish(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.pubsub_v1.types.PublishRequest, dict]): + The request object. Request for the Publish method. + topic (str): + Required. The messages in the request will be published + on this topic. Format is + ``projects/{project}/topics/{topic}``. + + This corresponds to the ``topic`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + messages (MutableSequence[google.pubsub_v1.types.PubsubMessage]): + Required. The messages to publish. + This corresponds to the ``messages`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (TimeoutType): + The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.types.PublishResponse: + Response for the Publish method. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [topic, messages] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.PublishRequest): + request = pubsub.PublishRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if topic is not None: + request.topic = topic + if messages is not None: + request.messages = messages + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.publish] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("topic", request.topic),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_topic( + self, + request: Optional[Union[pubsub.GetTopicRequest, dict]] = None, + *, + topic: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: TimeoutType = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.Topic: + r"""Gets the configuration of a topic. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + def sample_get_topic(): + # Create a client + client = pubsub_v1.PublisherClient() + + # Initialize request argument(s) + request = pubsub_v1.GetTopicRequest( + topic="topic_value", + ) + + # Make the request + response = client.get_topic(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.pubsub_v1.types.GetTopicRequest, dict]): + The request object. Request for the GetTopic method. + topic (str): + Required. The name of the topic to get. Format is + ``projects/{project}/topics/{topic}``. + + This corresponds to the ``topic`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (TimeoutType): + The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.types.Topic: + A topic resource. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [topic] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.GetTopicRequest): + request = pubsub.GetTopicRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if topic is not None: + request.topic = topic + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_topic] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("topic", request.topic),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_topics( + self, + request: Optional[Union[pubsub.ListTopicsRequest, dict]] = None, + *, + project: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: TimeoutType = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListTopicsPager: + r"""Lists matching topics. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + def sample_list_topics(): + # Create a client + client = pubsub_v1.PublisherClient() + + # Initialize request argument(s) + request = pubsub_v1.ListTopicsRequest( + project="project_value", + ) + + # Make the request + page_result = client.list_topics(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.pubsub_v1.types.ListTopicsRequest, dict]): + The request object. Request for the ``ListTopics`` method. + project (str): + Required. The name of the project in which to list + topics. Format is ``projects/{project-id}``. + + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (TimeoutType): + The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.services.publisher.pagers.ListTopicsPager: + Response for the ListTopics method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [project] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.ListTopicsRequest): + request = pubsub.ListTopicsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_topics] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("project", request.project),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListTopicsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_topic_subscriptions( + self, + request: Optional[Union[pubsub.ListTopicSubscriptionsRequest, dict]] = None, + *, + topic: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: TimeoutType = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListTopicSubscriptionsPager: + r"""Lists the names of the attached subscriptions on this + topic. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + def sample_list_topic_subscriptions(): + # Create a client + client = pubsub_v1.PublisherClient() + + # Initialize request argument(s) + request = pubsub_v1.ListTopicSubscriptionsRequest( + topic="topic_value", + ) + + # Make the request + page_result = client.list_topic_subscriptions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.pubsub_v1.types.ListTopicSubscriptionsRequest, dict]): + The request object. Request for the ``ListTopicSubscriptions`` method. + topic (str): + Required. The name of the topic that subscriptions are + attached to. Format is + ``projects/{project}/topics/{topic}``. + + This corresponds to the ``topic`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (TimeoutType): + The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.services.publisher.pagers.ListTopicSubscriptionsPager: + Response for the ListTopicSubscriptions method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [topic] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.ListTopicSubscriptionsRequest): + request = pubsub.ListTopicSubscriptionsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if topic is not None: + request.topic = topic + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_topic_subscriptions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("topic", request.topic),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListTopicSubscriptionsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_topic_snapshots( + self, + request: Optional[Union[pubsub.ListTopicSnapshotsRequest, dict]] = None, + *, + topic: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: TimeoutType = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListTopicSnapshotsPager: + r"""Lists the names of the snapshots on this topic. Snapshots are + used in + `Seek `__ + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + def sample_list_topic_snapshots(): + # Create a client + client = pubsub_v1.PublisherClient() + + # Initialize request argument(s) + request = pubsub_v1.ListTopicSnapshotsRequest( + topic="topic_value", + ) + + # Make the request + page_result = client.list_topic_snapshots(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.pubsub_v1.types.ListTopicSnapshotsRequest, dict]): + The request object. Request for the ``ListTopicSnapshots`` method. + topic (str): + Required. The name of the topic that snapshots are + attached to. Format is + ``projects/{project}/topics/{topic}``. + + This corresponds to the ``topic`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (TimeoutType): + The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.services.publisher.pagers.ListTopicSnapshotsPager: + Response for the ListTopicSnapshots method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [topic] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.ListTopicSnapshotsRequest): + request = pubsub.ListTopicSnapshotsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if topic is not None: + request.topic = topic + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_topic_snapshots] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("topic", request.topic),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListTopicSnapshotsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_topic( + self, + request: Optional[Union[pubsub.DeleteTopicRequest, dict]] = None, + *, + topic: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: TimeoutType = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes the topic with the given name. Returns ``NOT_FOUND`` if + the topic does not exist. After a topic is deleted, a new topic + may be created with the same name; this is an entirely new topic + with none of the old configuration or subscriptions. Existing + subscriptions to this topic are not deleted, but their ``topic`` + field is set to ``_deleted-topic_``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + def sample_delete_topic(): + # Create a client + client = pubsub_v1.PublisherClient() + + # Initialize request argument(s) + request = pubsub_v1.DeleteTopicRequest( + topic="topic_value", + ) + + # Make the request + client.delete_topic(request=request) + + Args: + request (Union[google.pubsub_v1.types.DeleteTopicRequest, dict]): + The request object. Request for the ``DeleteTopic`` method. + topic (str): + Required. Name of the topic to delete. Format is + ``projects/{project}/topics/{topic}``. + + This corresponds to the ``topic`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (TimeoutType): + The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [topic] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.DeleteTopicRequest): + request = pubsub.DeleteTopicRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if topic is not None: + request.topic = topic + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_topic] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("topic", request.topic),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def detach_subscription( + self, + request: Optional[Union[pubsub.DetachSubscriptionRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: TimeoutType = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.DetachSubscriptionResponse: + r"""Detaches a subscription from this topic. All messages retained + in the subscription are dropped. Subsequent ``Pull`` and + ``StreamingPull`` requests will return FAILED_PRECONDITION. If + the subscription is a push subscription, pushes to the endpoint + will stop. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + def sample_detach_subscription(): + # Create a client + client = pubsub_v1.PublisherClient() + + # Initialize request argument(s) + request = pubsub_v1.DetachSubscriptionRequest( + subscription="subscription_value", + ) + + # Make the request + response = client.detach_subscription(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.pubsub_v1.types.DetachSubscriptionRequest, dict]): + The request object. Request for the DetachSubscription + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (TimeoutType): + The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.types.DetachSubscriptionResponse: + Response for the DetachSubscription + method. Reserved for future use. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.DetachSubscriptionRequest): + request = pubsub.DetachSubscriptionRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.detach_subscription] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("subscription", request.subscription),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "PublisherClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: TimeoutType = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (TimeoutType): + The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: TimeoutType = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (TimeoutType): + The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def test_iam_permissions( + self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: TimeoutType = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (TimeoutType): + The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + client_library_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("PublisherClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/publisher/pagers.py b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/publisher/pagers.py new file mode 100644 index 0000000000000000000000000000000000000000..b84c862aa83f7d9636e46877910dfaa92ace3218 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/publisher/pagers.py @@ -0,0 +1,509 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed 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. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[ + retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None + ] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.pubsub_v1.types import pubsub + + +class ListTopicsPager: + """A pager for iterating through ``list_topics`` requests. + + This class thinly wraps an initial + :class:`google.pubsub_v1.types.ListTopicsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``topics`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListTopics`` requests and continue to iterate + through the ``topics`` field on the + corresponding responses. + + All the usual :class:`google.pubsub_v1.types.ListTopicsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., pubsub.ListTopicsResponse], + request: pubsub.ListTopicsRequest, + response: pubsub.ListTopicsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.pubsub_v1.types.ListTopicsRequest): + The initial request object. + response (google.pubsub_v1.types.ListTopicsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = pubsub.ListTopicsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[pubsub.ListTopicsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[pubsub.Topic]: + for page in self.pages: + yield from page.topics + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListTopicsAsyncPager: + """A pager for iterating through ``list_topics`` requests. + + This class thinly wraps an initial + :class:`google.pubsub_v1.types.ListTopicsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``topics`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListTopics`` requests and continue to iterate + through the ``topics`` field on the + corresponding responses. + + All the usual :class:`google.pubsub_v1.types.ListTopicsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[pubsub.ListTopicsResponse]], + request: pubsub.ListTopicsRequest, + response: pubsub.ListTopicsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.pubsub_v1.types.ListTopicsRequest): + The initial request object. + response (google.pubsub_v1.types.ListTopicsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = pubsub.ListTopicsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[pubsub.ListTopicsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[pubsub.Topic]: + async def async_generator(): + async for page in self.pages: + for response in page.topics: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListTopicSubscriptionsPager: + """A pager for iterating through ``list_topic_subscriptions`` requests. + + This class thinly wraps an initial + :class:`google.pubsub_v1.types.ListTopicSubscriptionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``subscriptions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListTopicSubscriptions`` requests and continue to iterate + through the ``subscriptions`` field on the + corresponding responses. + + All the usual :class:`google.pubsub_v1.types.ListTopicSubscriptionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., pubsub.ListTopicSubscriptionsResponse], + request: pubsub.ListTopicSubscriptionsRequest, + response: pubsub.ListTopicSubscriptionsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.pubsub_v1.types.ListTopicSubscriptionsRequest): + The initial request object. + response (google.pubsub_v1.types.ListTopicSubscriptionsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = pubsub.ListTopicSubscriptionsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[pubsub.ListTopicSubscriptionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[str]: + for page in self.pages: + yield from page.subscriptions + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListTopicSubscriptionsAsyncPager: + """A pager for iterating through ``list_topic_subscriptions`` requests. + + This class thinly wraps an initial + :class:`google.pubsub_v1.types.ListTopicSubscriptionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``subscriptions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListTopicSubscriptions`` requests and continue to iterate + through the ``subscriptions`` field on the + corresponding responses. + + All the usual :class:`google.pubsub_v1.types.ListTopicSubscriptionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[pubsub.ListTopicSubscriptionsResponse]], + request: pubsub.ListTopicSubscriptionsRequest, + response: pubsub.ListTopicSubscriptionsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.pubsub_v1.types.ListTopicSubscriptionsRequest): + The initial request object. + response (google.pubsub_v1.types.ListTopicSubscriptionsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = pubsub.ListTopicSubscriptionsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[pubsub.ListTopicSubscriptionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[str]: + async def async_generator(): + async for page in self.pages: + for response in page.subscriptions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListTopicSnapshotsPager: + """A pager for iterating through ``list_topic_snapshots`` requests. + + This class thinly wraps an initial + :class:`google.pubsub_v1.types.ListTopicSnapshotsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``snapshots`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListTopicSnapshots`` requests and continue to iterate + through the ``snapshots`` field on the + corresponding responses. + + All the usual :class:`google.pubsub_v1.types.ListTopicSnapshotsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., pubsub.ListTopicSnapshotsResponse], + request: pubsub.ListTopicSnapshotsRequest, + response: pubsub.ListTopicSnapshotsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.pubsub_v1.types.ListTopicSnapshotsRequest): + The initial request object. + response (google.pubsub_v1.types.ListTopicSnapshotsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = pubsub.ListTopicSnapshotsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[pubsub.ListTopicSnapshotsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[str]: + for page in self.pages: + yield from page.snapshots + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListTopicSnapshotsAsyncPager: + """A pager for iterating through ``list_topic_snapshots`` requests. + + This class thinly wraps an initial + :class:`google.pubsub_v1.types.ListTopicSnapshotsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``snapshots`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListTopicSnapshots`` requests and continue to iterate + through the ``snapshots`` field on the + corresponding responses. + + All the usual :class:`google.pubsub_v1.types.ListTopicSnapshotsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[pubsub.ListTopicSnapshotsResponse]], + request: pubsub.ListTopicSnapshotsRequest, + response: pubsub.ListTopicSnapshotsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.pubsub_v1.types.ListTopicSnapshotsRequest): + The initial request object. + response (google.pubsub_v1.types.ListTopicSnapshotsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = pubsub.ListTopicSnapshotsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[pubsub.ListTopicSnapshotsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[str]: + async def async_generator(): + async for page in self.pages: + for response in page.snapshots: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/publisher/transports/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/publisher/transports/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..76c1b93050303d2673f86d2d59e5916a2ea5b15d --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/publisher/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed 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. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import PublisherTransport +from .grpc import PublisherGrpcTransport +from .grpc_asyncio import PublisherGrpcAsyncIOTransport +from .rest import PublisherRestInterceptor, PublisherRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[PublisherTransport]] +_transport_registry["grpc"] = PublisherGrpcTransport +_transport_registry["grpc_asyncio"] = PublisherGrpcAsyncIOTransport +_transport_registry["rest"] = PublisherRestTransport + +__all__ = ( + "PublisherTransport", + "PublisherGrpcTransport", + "PublisherGrpcAsyncIOTransport", + "PublisherRestTransport", + "PublisherRestInterceptor", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/publisher/transports/base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/publisher/transports/base.py new file mode 100644 index 0000000000000000000000000000000000000000..f7631739d4be3737ffa1495d66cabea788f14f26 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/publisher/transports/base.py @@ -0,0 +1,438 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed 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. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +import google.auth # type: ignore +import google.protobuf +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.oauth2 import service_account # type: ignore + +from google.pubsub_v1 import gapic_version as package_version +from google.pubsub_v1.types import pubsub + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + client_library_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class PublisherTransport(abc.ABC): + """Abstract transport class for Publisher.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/pubsub", + ) + + DEFAULT_HOST: str = "pubsub.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'pubsub.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_topic: gapic_v1.method.wrap_method( + self.create_topic, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_topic: gapic_v1.method.wrap_method( + self.update_topic, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.publish: gapic_v1.method.wrap_method( + self.publish, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=4, + predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=600.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_topic: gapic_v1.method.wrap_method( + self.get_topic, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=600.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_topics: gapic_v1.method.wrap_method( + self.list_topics, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=600.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_topic_subscriptions: gapic_v1.method.wrap_method( + self.list_topic_subscriptions, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=600.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_topic_snapshots: gapic_v1.method.wrap_method( + self.list_topic_snapshots, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=600.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_topic: gapic_v1.method.wrap_method( + self.delete_topic, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.detach_subscription: gapic_v1.method.wrap_method( + self.detach_subscription, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def create_topic( + self, + ) -> Callable[[pubsub.Topic], Union[pubsub.Topic, Awaitable[pubsub.Topic]]]: + raise NotImplementedError() + + @property + def update_topic( + self, + ) -> Callable[ + [pubsub.UpdateTopicRequest], Union[pubsub.Topic, Awaitable[pubsub.Topic]] + ]: + raise NotImplementedError() + + @property + def publish( + self, + ) -> Callable[ + [pubsub.PublishRequest], + Union[pubsub.PublishResponse, Awaitable[pubsub.PublishResponse]], + ]: + raise NotImplementedError() + + @property + def get_topic( + self, + ) -> Callable[ + [pubsub.GetTopicRequest], Union[pubsub.Topic, Awaitable[pubsub.Topic]] + ]: + raise NotImplementedError() + + @property + def list_topics( + self, + ) -> Callable[ + [pubsub.ListTopicsRequest], + Union[pubsub.ListTopicsResponse, Awaitable[pubsub.ListTopicsResponse]], + ]: + raise NotImplementedError() + + @property + def list_topic_subscriptions( + self, + ) -> Callable[ + [pubsub.ListTopicSubscriptionsRequest], + Union[ + pubsub.ListTopicSubscriptionsResponse, + Awaitable[pubsub.ListTopicSubscriptionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_topic_snapshots( + self, + ) -> Callable[ + [pubsub.ListTopicSnapshotsRequest], + Union[ + pubsub.ListTopicSnapshotsResponse, + Awaitable[pubsub.ListTopicSnapshotsResponse], + ], + ]: + raise NotImplementedError() + + @property + def delete_topic( + self, + ) -> Callable[ + [pubsub.DeleteTopicRequest], Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]] + ]: + raise NotImplementedError() + + @property + def detach_subscription( + self, + ) -> Callable[ + [pubsub.DetachSubscriptionRequest], + Union[ + pubsub.DetachSubscriptionResponse, + Awaitable[pubsub.DetachSubscriptionResponse], + ], + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("PublisherTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/publisher/transports/grpc.py b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/publisher/transports/grpc.py new file mode 100644 index 0000000000000000000000000000000000000000..82ffa17b4c085aa34fc9d5c4ff02cea2e05ab57a --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/publisher/transports/grpc.py @@ -0,0 +1,674 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed 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. +# +import json +import logging as std_logging +import pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +import google.auth # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.protobuf.json_format import MessageToJson + +from google.pubsub_v1.types import pubsub + +from .base import DEFAULT_CLIENT_INFO, PublisherTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.pubsub.v1.Publisher", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.pubsub.v1.Publisher", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class PublisherGrpcTransport(PublisherTransport): + """gRPC backend transport for Publisher. + + The service that an application uses to manipulate topics, + and to send messages to a topic. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "pubsub.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'pubsub.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ("grpc.max_metadata_size", 4 * 1024 * 1024), + ("grpc.keepalive_time_ms", 30000), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "pubsub.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def create_topic(self) -> Callable[[pubsub.Topic], pubsub.Topic]: + r"""Return a callable for the create topic method over gRPC. + + Creates the given topic with the given name. See the [resource + name rules] + (https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names). + + Returns: + Callable[[~.Topic], + ~.Topic]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_topic" not in self._stubs: + self._stubs["create_topic"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Publisher/CreateTopic", + request_serializer=pubsub.Topic.serialize, + response_deserializer=pubsub.Topic.deserialize, + ) + return self._stubs["create_topic"] + + @property + def update_topic(self) -> Callable[[pubsub.UpdateTopicRequest], pubsub.Topic]: + r"""Return a callable for the update topic method over gRPC. + + Updates an existing topic by updating the fields + specified in the update mask. Note that certain + properties of a topic are not modifiable. + + Returns: + Callable[[~.UpdateTopicRequest], + ~.Topic]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_topic" not in self._stubs: + self._stubs["update_topic"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Publisher/UpdateTopic", + request_serializer=pubsub.UpdateTopicRequest.serialize, + response_deserializer=pubsub.Topic.deserialize, + ) + return self._stubs["update_topic"] + + @property + def publish(self) -> Callable[[pubsub.PublishRequest], pubsub.PublishResponse]: + r"""Return a callable for the publish method over gRPC. + + Adds one or more messages to the topic. Returns ``NOT_FOUND`` if + the topic does not exist. + + Returns: + Callable[[~.PublishRequest], + ~.PublishResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "publish" not in self._stubs: + self._stubs["publish"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Publisher/Publish", + request_serializer=pubsub.PublishRequest.serialize, + response_deserializer=pubsub.PublishResponse.deserialize, + ) + return self._stubs["publish"] + + @property + def get_topic(self) -> Callable[[pubsub.GetTopicRequest], pubsub.Topic]: + r"""Return a callable for the get topic method over gRPC. + + Gets the configuration of a topic. + + Returns: + Callable[[~.GetTopicRequest], + ~.Topic]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_topic" not in self._stubs: + self._stubs["get_topic"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Publisher/GetTopic", + request_serializer=pubsub.GetTopicRequest.serialize, + response_deserializer=pubsub.Topic.deserialize, + ) + return self._stubs["get_topic"] + + @property + def list_topics( + self, + ) -> Callable[[pubsub.ListTopicsRequest], pubsub.ListTopicsResponse]: + r"""Return a callable for the list topics method over gRPC. + + Lists matching topics. + + Returns: + Callable[[~.ListTopicsRequest], + ~.ListTopicsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_topics" not in self._stubs: + self._stubs["list_topics"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Publisher/ListTopics", + request_serializer=pubsub.ListTopicsRequest.serialize, + response_deserializer=pubsub.ListTopicsResponse.deserialize, + ) + return self._stubs["list_topics"] + + @property + def list_topic_subscriptions( + self, + ) -> Callable[ + [pubsub.ListTopicSubscriptionsRequest], pubsub.ListTopicSubscriptionsResponse + ]: + r"""Return a callable for the list topic subscriptions method over gRPC. + + Lists the names of the attached subscriptions on this + topic. + + Returns: + Callable[[~.ListTopicSubscriptionsRequest], + ~.ListTopicSubscriptionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_topic_subscriptions" not in self._stubs: + self._stubs["list_topic_subscriptions"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Publisher/ListTopicSubscriptions", + request_serializer=pubsub.ListTopicSubscriptionsRequest.serialize, + response_deserializer=pubsub.ListTopicSubscriptionsResponse.deserialize, + ) + return self._stubs["list_topic_subscriptions"] + + @property + def list_topic_snapshots( + self, + ) -> Callable[ + [pubsub.ListTopicSnapshotsRequest], pubsub.ListTopicSnapshotsResponse + ]: + r"""Return a callable for the list topic snapshots method over gRPC. + + Lists the names of the snapshots on this topic. Snapshots are + used in + `Seek `__ + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + + Returns: + Callable[[~.ListTopicSnapshotsRequest], + ~.ListTopicSnapshotsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_topic_snapshots" not in self._stubs: + self._stubs["list_topic_snapshots"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Publisher/ListTopicSnapshots", + request_serializer=pubsub.ListTopicSnapshotsRequest.serialize, + response_deserializer=pubsub.ListTopicSnapshotsResponse.deserialize, + ) + return self._stubs["list_topic_snapshots"] + + @property + def delete_topic(self) -> Callable[[pubsub.DeleteTopicRequest], empty_pb2.Empty]: + r"""Return a callable for the delete topic method over gRPC. + + Deletes the topic with the given name. Returns ``NOT_FOUND`` if + the topic does not exist. After a topic is deleted, a new topic + may be created with the same name; this is an entirely new topic + with none of the old configuration or subscriptions. Existing + subscriptions to this topic are not deleted, but their ``topic`` + field is set to ``_deleted-topic_``. + + Returns: + Callable[[~.DeleteTopicRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_topic" not in self._stubs: + self._stubs["delete_topic"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Publisher/DeleteTopic", + request_serializer=pubsub.DeleteTopicRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_topic"] + + @property + def detach_subscription( + self, + ) -> Callable[ + [pubsub.DetachSubscriptionRequest], pubsub.DetachSubscriptionResponse + ]: + r"""Return a callable for the detach subscription method over gRPC. + + Detaches a subscription from this topic. All messages retained + in the subscription are dropped. Subsequent ``Pull`` and + ``StreamingPull`` requests will return FAILED_PRECONDITION. If + the subscription is a push subscription, pushes to the endpoint + will stop. + + Returns: + Callable[[~.DetachSubscriptionRequest], + ~.DetachSubscriptionResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "detach_subscription" not in self._stubs: + self._stubs["detach_subscription"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Publisher/DetachSubscription", + request_serializer=pubsub.DetachSubscriptionRequest.serialize, + response_deserializer=pubsub.DetachSubscriptionResponse.deserialize, + ) + return self._stubs["detach_subscription"] + + def close(self): + self._logged_channel.close() + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("PublisherGrpcTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..296d2f6a3743f20d6ea6bcf52626d3b2ceab89e8 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/publisher/transports/grpc_asyncio.py @@ -0,0 +1,854 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed 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. +# +import inspect +import json +import logging as std_logging +import pickle +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.protobuf.json_format import MessageToJson +from grpc.experimental import aio # type: ignore + +from google.pubsub_v1.types import pubsub + +from .base import DEFAULT_CLIENT_INFO, PublisherTransport +from .grpc import PublisherGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.pubsub.v1.Publisher", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.pubsub.v1.Publisher", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class PublisherGrpcAsyncIOTransport(PublisherTransport): + """gRPC AsyncIO backend transport for Publisher. + + The service that an application uses to manipulate topics, + and to send messages to a topic. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "pubsub.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "pubsub.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'pubsub.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ("grpc.max_metadata_size", 4 * 1024 * 1024), + ("grpc.keepalive_time_ms", 30000), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_topic(self) -> Callable[[pubsub.Topic], Awaitable[pubsub.Topic]]: + r"""Return a callable for the create topic method over gRPC. + + Creates the given topic with the given name. See the [resource + name rules] + (https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names). + + Returns: + Callable[[~.Topic], + Awaitable[~.Topic]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_topic" not in self._stubs: + self._stubs["create_topic"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Publisher/CreateTopic", + request_serializer=pubsub.Topic.serialize, + response_deserializer=pubsub.Topic.deserialize, + ) + return self._stubs["create_topic"] + + @property + def update_topic( + self, + ) -> Callable[[pubsub.UpdateTopicRequest], Awaitable[pubsub.Topic]]: + r"""Return a callable for the update topic method over gRPC. + + Updates an existing topic by updating the fields + specified in the update mask. Note that certain + properties of a topic are not modifiable. + + Returns: + Callable[[~.UpdateTopicRequest], + Awaitable[~.Topic]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_topic" not in self._stubs: + self._stubs["update_topic"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Publisher/UpdateTopic", + request_serializer=pubsub.UpdateTopicRequest.serialize, + response_deserializer=pubsub.Topic.deserialize, + ) + return self._stubs["update_topic"] + + @property + def publish( + self, + ) -> Callable[[pubsub.PublishRequest], Awaitable[pubsub.PublishResponse]]: + r"""Return a callable for the publish method over gRPC. + + Adds one or more messages to the topic. Returns ``NOT_FOUND`` if + the topic does not exist. + + Returns: + Callable[[~.PublishRequest], + Awaitable[~.PublishResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "publish" not in self._stubs: + self._stubs["publish"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Publisher/Publish", + request_serializer=pubsub.PublishRequest.serialize, + response_deserializer=pubsub.PublishResponse.deserialize, + ) + return self._stubs["publish"] + + @property + def get_topic(self) -> Callable[[pubsub.GetTopicRequest], Awaitable[pubsub.Topic]]: + r"""Return a callable for the get topic method over gRPC. + + Gets the configuration of a topic. + + Returns: + Callable[[~.GetTopicRequest], + Awaitable[~.Topic]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_topic" not in self._stubs: + self._stubs["get_topic"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Publisher/GetTopic", + request_serializer=pubsub.GetTopicRequest.serialize, + response_deserializer=pubsub.Topic.deserialize, + ) + return self._stubs["get_topic"] + + @property + def list_topics( + self, + ) -> Callable[[pubsub.ListTopicsRequest], Awaitable[pubsub.ListTopicsResponse]]: + r"""Return a callable for the list topics method over gRPC. + + Lists matching topics. + + Returns: + Callable[[~.ListTopicsRequest], + Awaitable[~.ListTopicsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_topics" not in self._stubs: + self._stubs["list_topics"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Publisher/ListTopics", + request_serializer=pubsub.ListTopicsRequest.serialize, + response_deserializer=pubsub.ListTopicsResponse.deserialize, + ) + return self._stubs["list_topics"] + + @property + def list_topic_subscriptions( + self, + ) -> Callable[ + [pubsub.ListTopicSubscriptionsRequest], + Awaitable[pubsub.ListTopicSubscriptionsResponse], + ]: + r"""Return a callable for the list topic subscriptions method over gRPC. + + Lists the names of the attached subscriptions on this + topic. + + Returns: + Callable[[~.ListTopicSubscriptionsRequest], + Awaitable[~.ListTopicSubscriptionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_topic_subscriptions" not in self._stubs: + self._stubs["list_topic_subscriptions"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Publisher/ListTopicSubscriptions", + request_serializer=pubsub.ListTopicSubscriptionsRequest.serialize, + response_deserializer=pubsub.ListTopicSubscriptionsResponse.deserialize, + ) + return self._stubs["list_topic_subscriptions"] + + @property + def list_topic_snapshots( + self, + ) -> Callable[ + [pubsub.ListTopicSnapshotsRequest], Awaitable[pubsub.ListTopicSnapshotsResponse] + ]: + r"""Return a callable for the list topic snapshots method over gRPC. + + Lists the names of the snapshots on this topic. Snapshots are + used in + `Seek `__ + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + + Returns: + Callable[[~.ListTopicSnapshotsRequest], + Awaitable[~.ListTopicSnapshotsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_topic_snapshots" not in self._stubs: + self._stubs["list_topic_snapshots"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Publisher/ListTopicSnapshots", + request_serializer=pubsub.ListTopicSnapshotsRequest.serialize, + response_deserializer=pubsub.ListTopicSnapshotsResponse.deserialize, + ) + return self._stubs["list_topic_snapshots"] + + @property + def delete_topic( + self, + ) -> Callable[[pubsub.DeleteTopicRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete topic method over gRPC. + + Deletes the topic with the given name. Returns ``NOT_FOUND`` if + the topic does not exist. After a topic is deleted, a new topic + may be created with the same name; this is an entirely new topic + with none of the old configuration or subscriptions. Existing + subscriptions to this topic are not deleted, but their ``topic`` + field is set to ``_deleted-topic_``. + + Returns: + Callable[[~.DeleteTopicRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_topic" not in self._stubs: + self._stubs["delete_topic"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Publisher/DeleteTopic", + request_serializer=pubsub.DeleteTopicRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_topic"] + + @property + def detach_subscription( + self, + ) -> Callable[ + [pubsub.DetachSubscriptionRequest], Awaitable[pubsub.DetachSubscriptionResponse] + ]: + r"""Return a callable for the detach subscription method over gRPC. + + Detaches a subscription from this topic. All messages retained + in the subscription are dropped. Subsequent ``Pull`` and + ``StreamingPull`` requests will return FAILED_PRECONDITION. If + the subscription is a push subscription, pushes to the endpoint + will stop. + + Returns: + Callable[[~.DetachSubscriptionRequest], + Awaitable[~.DetachSubscriptionResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "detach_subscription" not in self._stubs: + self._stubs["detach_subscription"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Publisher/DetachSubscription", + request_serializer=pubsub.DetachSubscriptionRequest.serialize, + response_deserializer=pubsub.DetachSubscriptionResponse.deserialize, + ) + return self._stubs["detach_subscription"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.create_topic: self._wrap_method( + self.create_topic, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_topic: self._wrap_method( + self.update_topic, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.publish: self._wrap_method( + self.publish, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=4, + predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.Cancelled, + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_topic: self._wrap_method( + self.get_topic, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_topics: self._wrap_method( + self.list_topics, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_topic_subscriptions: self._wrap_method( + self.list_topic_subscriptions, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_topic_snapshots: self._wrap_method( + self.list_topic_snapshots, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_topic: self._wrap_method( + self.delete_topic, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.detach_subscription: self._wrap_method( + self.detach_subscription, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_iam_policy: self._wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: self._wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: self._wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ("PublisherGrpcAsyncIOTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/publisher/transports/rest.py b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/publisher/transports/rest.py new file mode 100644 index 0000000000000000000000000000000000000000..f0dbb663bab3802cc12ab5e97ac8e01cfdf885ba --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/publisher/transports/rest.py @@ -0,0 +1,2514 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed 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. +# +import dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.pubsub_v1.types import pubsub + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BasePublisherRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class PublisherRestInterceptor: + """Interceptor for Publisher. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the PublisherRestTransport. + + .. code-block:: python + class MyCustomPublisherInterceptor(PublisherRestInterceptor): + def pre_create_topic(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_topic(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_topic(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_detach_subscription(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_detach_subscription(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_topic(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_topic(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_topics(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_topics(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_topic_snapshots(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_topic_snapshots(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_topic_subscriptions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_topic_subscriptions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_publish(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_publish(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_topic(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_topic(self, response): + logging.log(f"Received response: {response}") + return response + + transport = PublisherRestTransport(interceptor=MyCustomPublisherInterceptor()) + client = PublisherClient(transport=transport) + + + """ + + def pre_create_topic( + self, request: pubsub.Topic, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[pubsub.Topic, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_topic + + Override in a subclass to manipulate the request or metadata + before they are sent to the Publisher server. + """ + return request, metadata + + def post_create_topic(self, response: pubsub.Topic) -> pubsub.Topic: + """Post-rpc interceptor for create_topic + + DEPRECATED. Please use the `post_create_topic_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Publisher server but before + it is returned to user code. This `post_create_topic` interceptor runs + before the `post_create_topic_with_metadata` interceptor. + """ + return response + + def post_create_topic_with_metadata( + self, response: pubsub.Topic, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[pubsub.Topic, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_topic + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Publisher server but before it is returned to user code. + + We recommend only using this `post_create_topic_with_metadata` + interceptor in new development instead of the `post_create_topic` interceptor. + When both interceptors are used, this `post_create_topic_with_metadata` interceptor runs after the + `post_create_topic` interceptor. The (possibly modified) response returned by + `post_create_topic` will be passed to + `post_create_topic_with_metadata`. + """ + return response, metadata + + def pre_delete_topic( + self, + request: pubsub.DeleteTopicRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[pubsub.DeleteTopicRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_topic + + Override in a subclass to manipulate the request or metadata + before they are sent to the Publisher server. + """ + return request, metadata + + def pre_detach_subscription( + self, + request: pubsub.DetachSubscriptionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + pubsub.DetachSubscriptionRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for detach_subscription + + Override in a subclass to manipulate the request or metadata + before they are sent to the Publisher server. + """ + return request, metadata + + def post_detach_subscription( + self, response: pubsub.DetachSubscriptionResponse + ) -> pubsub.DetachSubscriptionResponse: + """Post-rpc interceptor for detach_subscription + + DEPRECATED. Please use the `post_detach_subscription_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Publisher server but before + it is returned to user code. This `post_detach_subscription` interceptor runs + before the `post_detach_subscription_with_metadata` interceptor. + """ + return response + + def post_detach_subscription_with_metadata( + self, + response: pubsub.DetachSubscriptionResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + pubsub.DetachSubscriptionResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for detach_subscription + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Publisher server but before it is returned to user code. + + We recommend only using this `post_detach_subscription_with_metadata` + interceptor in new development instead of the `post_detach_subscription` interceptor. + When both interceptors are used, this `post_detach_subscription_with_metadata` interceptor runs after the + `post_detach_subscription` interceptor. The (possibly modified) response returned by + `post_detach_subscription` will be passed to + `post_detach_subscription_with_metadata`. + """ + return response, metadata + + def pre_get_topic( + self, + request: pubsub.GetTopicRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[pubsub.GetTopicRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_topic + + Override in a subclass to manipulate the request or metadata + before they are sent to the Publisher server. + """ + return request, metadata + + def post_get_topic(self, response: pubsub.Topic) -> pubsub.Topic: + """Post-rpc interceptor for get_topic + + DEPRECATED. Please use the `post_get_topic_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Publisher server but before + it is returned to user code. This `post_get_topic` interceptor runs + before the `post_get_topic_with_metadata` interceptor. + """ + return response + + def post_get_topic_with_metadata( + self, response: pubsub.Topic, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[pubsub.Topic, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_topic + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Publisher server but before it is returned to user code. + + We recommend only using this `post_get_topic_with_metadata` + interceptor in new development instead of the `post_get_topic` interceptor. + When both interceptors are used, this `post_get_topic_with_metadata` interceptor runs after the + `post_get_topic` interceptor. The (possibly modified) response returned by + `post_get_topic` will be passed to + `post_get_topic_with_metadata`. + """ + return response, metadata + + def pre_list_topics( + self, + request: pubsub.ListTopicsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[pubsub.ListTopicsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_topics + + Override in a subclass to manipulate the request or metadata + before they are sent to the Publisher server. + """ + return request, metadata + + def post_list_topics( + self, response: pubsub.ListTopicsResponse + ) -> pubsub.ListTopicsResponse: + """Post-rpc interceptor for list_topics + + DEPRECATED. Please use the `post_list_topics_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Publisher server but before + it is returned to user code. This `post_list_topics` interceptor runs + before the `post_list_topics_with_metadata` interceptor. + """ + return response + + def post_list_topics_with_metadata( + self, + response: pubsub.ListTopicsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[pubsub.ListTopicsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_topics + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Publisher server but before it is returned to user code. + + We recommend only using this `post_list_topics_with_metadata` + interceptor in new development instead of the `post_list_topics` interceptor. + When both interceptors are used, this `post_list_topics_with_metadata` interceptor runs after the + `post_list_topics` interceptor. The (possibly modified) response returned by + `post_list_topics` will be passed to + `post_list_topics_with_metadata`. + """ + return response, metadata + + def pre_list_topic_snapshots( + self, + request: pubsub.ListTopicSnapshotsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + pubsub.ListTopicSnapshotsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_topic_snapshots + + Override in a subclass to manipulate the request or metadata + before they are sent to the Publisher server. + """ + return request, metadata + + def post_list_topic_snapshots( + self, response: pubsub.ListTopicSnapshotsResponse + ) -> pubsub.ListTopicSnapshotsResponse: + """Post-rpc interceptor for list_topic_snapshots + + DEPRECATED. Please use the `post_list_topic_snapshots_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Publisher server but before + it is returned to user code. This `post_list_topic_snapshots` interceptor runs + before the `post_list_topic_snapshots_with_metadata` interceptor. + """ + return response + + def post_list_topic_snapshots_with_metadata( + self, + response: pubsub.ListTopicSnapshotsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + pubsub.ListTopicSnapshotsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_topic_snapshots + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Publisher server but before it is returned to user code. + + We recommend only using this `post_list_topic_snapshots_with_metadata` + interceptor in new development instead of the `post_list_topic_snapshots` interceptor. + When both interceptors are used, this `post_list_topic_snapshots_with_metadata` interceptor runs after the + `post_list_topic_snapshots` interceptor. The (possibly modified) response returned by + `post_list_topic_snapshots` will be passed to + `post_list_topic_snapshots_with_metadata`. + """ + return response, metadata + + def pre_list_topic_subscriptions( + self, + request: pubsub.ListTopicSubscriptionsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + pubsub.ListTopicSubscriptionsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_topic_subscriptions + + Override in a subclass to manipulate the request or metadata + before they are sent to the Publisher server. + """ + return request, metadata + + def post_list_topic_subscriptions( + self, response: pubsub.ListTopicSubscriptionsResponse + ) -> pubsub.ListTopicSubscriptionsResponse: + """Post-rpc interceptor for list_topic_subscriptions + + DEPRECATED. Please use the `post_list_topic_subscriptions_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Publisher server but before + it is returned to user code. This `post_list_topic_subscriptions` interceptor runs + before the `post_list_topic_subscriptions_with_metadata` interceptor. + """ + return response + + def post_list_topic_subscriptions_with_metadata( + self, + response: pubsub.ListTopicSubscriptionsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + pubsub.ListTopicSubscriptionsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_topic_subscriptions + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Publisher server but before it is returned to user code. + + We recommend only using this `post_list_topic_subscriptions_with_metadata` + interceptor in new development instead of the `post_list_topic_subscriptions` interceptor. + When both interceptors are used, this `post_list_topic_subscriptions_with_metadata` interceptor runs after the + `post_list_topic_subscriptions` interceptor. The (possibly modified) response returned by + `post_list_topic_subscriptions` will be passed to + `post_list_topic_subscriptions_with_metadata`. + """ + return response, metadata + + def pre_publish( + self, + request: pubsub.PublishRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[pubsub.PublishRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for publish + + Override in a subclass to manipulate the request or metadata + before they are sent to the Publisher server. + """ + return request, metadata + + def post_publish(self, response: pubsub.PublishResponse) -> pubsub.PublishResponse: + """Post-rpc interceptor for publish + + DEPRECATED. Please use the `post_publish_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Publisher server but before + it is returned to user code. This `post_publish` interceptor runs + before the `post_publish_with_metadata` interceptor. + """ + return response + + def post_publish_with_metadata( + self, + response: pubsub.PublishResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[pubsub.PublishResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for publish + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Publisher server but before it is returned to user code. + + We recommend only using this `post_publish_with_metadata` + interceptor in new development instead of the `post_publish` interceptor. + When both interceptors are used, this `post_publish_with_metadata` interceptor runs after the + `post_publish` interceptor. The (possibly modified) response returned by + `post_publish` will be passed to + `post_publish_with_metadata`. + """ + return response, metadata + + def pre_update_topic( + self, + request: pubsub.UpdateTopicRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[pubsub.UpdateTopicRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_topic + + Override in a subclass to manipulate the request or metadata + before they are sent to the Publisher server. + """ + return request, metadata + + def post_update_topic(self, response: pubsub.Topic) -> pubsub.Topic: + """Post-rpc interceptor for update_topic + + DEPRECATED. Please use the `post_update_topic_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Publisher server but before + it is returned to user code. This `post_update_topic` interceptor runs + before the `post_update_topic_with_metadata` interceptor. + """ + return response + + def post_update_topic_with_metadata( + self, response: pubsub.Topic, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[pubsub.Topic, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_topic + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Publisher server but before it is returned to user code. + + We recommend only using this `post_update_topic_with_metadata` + interceptor in new development instead of the `post_update_topic` interceptor. + When both interceptors are used, this `post_update_topic_with_metadata` interceptor runs after the + `post_update_topic` interceptor. The (possibly modified) response returned by + `post_update_topic` will be passed to + `post_update_topic_with_metadata`. + """ + return response, metadata + + def pre_get_iam_policy( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the Publisher server. + """ + return request, metadata + + def post_get_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the Publisher server but before + it is returned to user code. + """ + return response + + def pre_set_iam_policy( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the Publisher server. + """ + return request, metadata + + def post_set_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the Publisher server but before + it is returned to user code. + """ + return response + + def pre_test_iam_permissions( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.TestIamPermissionsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the Publisher server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsResponse + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the Publisher server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class PublisherRestStub: + _session: AuthorizedSession + _host: str + _interceptor: PublisherRestInterceptor + + +class PublisherRestTransport(_BasePublisherRestTransport): + """REST backend synchronous transport for Publisher. + + The service that an application uses to manipulate topics, + and to send messages to a topic. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "pubsub.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[PublisherRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'pubsub.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[PublisherRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or PublisherRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateTopic(_BasePublisherRestTransport._BaseCreateTopic, PublisherRestStub): + def __hash__(self): + return hash("PublisherRestTransport.CreateTopic") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: pubsub.Topic, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.Topic: + r"""Call the create topic method over HTTP. + + Args: + request (~.pubsub.Topic): + The request object. A topic resource. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.pubsub.Topic: + A topic resource. + """ + + http_options = ( + _BasePublisherRestTransport._BaseCreateTopic._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_topic(request, metadata) + transcoded_request = ( + _BasePublisherRestTransport._BaseCreateTopic._get_transcoded_request( + http_options, request + ) + ) + + body = _BasePublisherRestTransport._BaseCreateTopic._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BasePublisherRestTransport._BaseCreateTopic._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.PublisherClient.CreateTopic", + extra={ + "serviceName": "google.pubsub.v1.Publisher", + "rpcName": "CreateTopic", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PublisherRestTransport._CreateTopic._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = pubsub.Topic() + pb_resp = pubsub.Topic.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_topic(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_topic_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = pubsub.Topic.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.pubsub_v1.PublisherClient.create_topic", + extra={ + "serviceName": "google.pubsub.v1.Publisher", + "rpcName": "CreateTopic", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteTopic(_BasePublisherRestTransport._BaseDeleteTopic, PublisherRestStub): + def __hash__(self): + return hash("PublisherRestTransport.DeleteTopic") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: pubsub.DeleteTopicRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete topic method over HTTP. + + Args: + request (~.pubsub.DeleteTopicRequest): + The request object. Request for the ``DeleteTopic`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BasePublisherRestTransport._BaseDeleteTopic._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_topic(request, metadata) + transcoded_request = ( + _BasePublisherRestTransport._BaseDeleteTopic._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BasePublisherRestTransport._BaseDeleteTopic._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.PublisherClient.DeleteTopic", + extra={ + "serviceName": "google.pubsub.v1.Publisher", + "rpcName": "DeleteTopic", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PublisherRestTransport._DeleteTopic._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DetachSubscription( + _BasePublisherRestTransport._BaseDetachSubscription, PublisherRestStub + ): + def __hash__(self): + return hash("PublisherRestTransport.DetachSubscription") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: pubsub.DetachSubscriptionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.DetachSubscriptionResponse: + r"""Call the detach subscription method over HTTP. + + Args: + request (~.pubsub.DetachSubscriptionRequest): + The request object. Request for the DetachSubscription + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.pubsub.DetachSubscriptionResponse: + Response for the DetachSubscription + method. Reserved for future use. + + """ + + http_options = ( + _BasePublisherRestTransport._BaseDetachSubscription._get_http_options() + ) + + request, metadata = self._interceptor.pre_detach_subscription( + request, metadata + ) + transcoded_request = _BasePublisherRestTransport._BaseDetachSubscription._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BasePublisherRestTransport._BaseDetachSubscription._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.PublisherClient.DetachSubscription", + extra={ + "serviceName": "google.pubsub.v1.Publisher", + "rpcName": "DetachSubscription", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PublisherRestTransport._DetachSubscription._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = pubsub.DetachSubscriptionResponse() + pb_resp = pubsub.DetachSubscriptionResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_detach_subscription(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_detach_subscription_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = pubsub.DetachSubscriptionResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.pubsub_v1.PublisherClient.detach_subscription", + extra={ + "serviceName": "google.pubsub.v1.Publisher", + "rpcName": "DetachSubscription", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetTopic(_BasePublisherRestTransport._BaseGetTopic, PublisherRestStub): + def __hash__(self): + return hash("PublisherRestTransport.GetTopic") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: pubsub.GetTopicRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.Topic: + r"""Call the get topic method over HTTP. + + Args: + request (~.pubsub.GetTopicRequest): + The request object. Request for the GetTopic method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.pubsub.Topic: + A topic resource. + """ + + http_options = _BasePublisherRestTransport._BaseGetTopic._get_http_options() + + request, metadata = self._interceptor.pre_get_topic(request, metadata) + transcoded_request = ( + _BasePublisherRestTransport._BaseGetTopic._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BasePublisherRestTransport._BaseGetTopic._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.PublisherClient.GetTopic", + extra={ + "serviceName": "google.pubsub.v1.Publisher", + "rpcName": "GetTopic", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PublisherRestTransport._GetTopic._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = pubsub.Topic() + pb_resp = pubsub.Topic.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_topic(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_topic_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = pubsub.Topic.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.pubsub_v1.PublisherClient.get_topic", + extra={ + "serviceName": "google.pubsub.v1.Publisher", + "rpcName": "GetTopic", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListTopics(_BasePublisherRestTransport._BaseListTopics, PublisherRestStub): + def __hash__(self): + return hash("PublisherRestTransport.ListTopics") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: pubsub.ListTopicsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.ListTopicsResponse: + r"""Call the list topics method over HTTP. + + Args: + request (~.pubsub.ListTopicsRequest): + The request object. Request for the ``ListTopics`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.pubsub.ListTopicsResponse: + Response for the ``ListTopics`` method. + """ + + http_options = ( + _BasePublisherRestTransport._BaseListTopics._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_topics(request, metadata) + transcoded_request = ( + _BasePublisherRestTransport._BaseListTopics._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BasePublisherRestTransport._BaseListTopics._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.PublisherClient.ListTopics", + extra={ + "serviceName": "google.pubsub.v1.Publisher", + "rpcName": "ListTopics", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PublisherRestTransport._ListTopics._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = pubsub.ListTopicsResponse() + pb_resp = pubsub.ListTopicsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_topics(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_topics_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = pubsub.ListTopicsResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.pubsub_v1.PublisherClient.list_topics", + extra={ + "serviceName": "google.pubsub.v1.Publisher", + "rpcName": "ListTopics", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListTopicSnapshots( + _BasePublisherRestTransport._BaseListTopicSnapshots, PublisherRestStub + ): + def __hash__(self): + return hash("PublisherRestTransport.ListTopicSnapshots") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: pubsub.ListTopicSnapshotsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.ListTopicSnapshotsResponse: + r"""Call the list topic snapshots method over HTTP. + + Args: + request (~.pubsub.ListTopicSnapshotsRequest): + The request object. Request for the ``ListTopicSnapshots`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.pubsub.ListTopicSnapshotsResponse: + Response for the ``ListTopicSnapshots`` method. + """ + + http_options = ( + _BasePublisherRestTransport._BaseListTopicSnapshots._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_topic_snapshots( + request, metadata + ) + transcoded_request = _BasePublisherRestTransport._BaseListTopicSnapshots._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BasePublisherRestTransport._BaseListTopicSnapshots._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.PublisherClient.ListTopicSnapshots", + extra={ + "serviceName": "google.pubsub.v1.Publisher", + "rpcName": "ListTopicSnapshots", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PublisherRestTransport._ListTopicSnapshots._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = pubsub.ListTopicSnapshotsResponse() + pb_resp = pubsub.ListTopicSnapshotsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_topic_snapshots(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_topic_snapshots_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = pubsub.ListTopicSnapshotsResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.pubsub_v1.PublisherClient.list_topic_snapshots", + extra={ + "serviceName": "google.pubsub.v1.Publisher", + "rpcName": "ListTopicSnapshots", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListTopicSubscriptions( + _BasePublisherRestTransport._BaseListTopicSubscriptions, PublisherRestStub + ): + def __hash__(self): + return hash("PublisherRestTransport.ListTopicSubscriptions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: pubsub.ListTopicSubscriptionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.ListTopicSubscriptionsResponse: + r"""Call the list topic subscriptions method over HTTP. + + Args: + request (~.pubsub.ListTopicSubscriptionsRequest): + The request object. Request for the ``ListTopicSubscriptions`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.pubsub.ListTopicSubscriptionsResponse: + Response for the ``ListTopicSubscriptions`` method. + """ + + http_options = _BasePublisherRestTransport._BaseListTopicSubscriptions._get_http_options() + + request, metadata = self._interceptor.pre_list_topic_subscriptions( + request, metadata + ) + transcoded_request = _BasePublisherRestTransport._BaseListTopicSubscriptions._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BasePublisherRestTransport._BaseListTopicSubscriptions._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.PublisherClient.ListTopicSubscriptions", + extra={ + "serviceName": "google.pubsub.v1.Publisher", + "rpcName": "ListTopicSubscriptions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PublisherRestTransport._ListTopicSubscriptions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = pubsub.ListTopicSubscriptionsResponse() + pb_resp = pubsub.ListTopicSubscriptionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_topic_subscriptions(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_topic_subscriptions_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = pubsub.ListTopicSubscriptionsResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.pubsub_v1.PublisherClient.list_topic_subscriptions", + extra={ + "serviceName": "google.pubsub.v1.Publisher", + "rpcName": "ListTopicSubscriptions", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _Publish(_BasePublisherRestTransport._BasePublish, PublisherRestStub): + def __hash__(self): + return hash("PublisherRestTransport.Publish") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: pubsub.PublishRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.PublishResponse: + r"""Call the publish method over HTTP. + + Args: + request (~.pubsub.PublishRequest): + The request object. Request for the Publish method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.pubsub.PublishResponse: + Response for the ``Publish`` method. + """ + + http_options = _BasePublisherRestTransport._BasePublish._get_http_options() + + request, metadata = self._interceptor.pre_publish(request, metadata) + transcoded_request = ( + _BasePublisherRestTransport._BasePublish._get_transcoded_request( + http_options, request + ) + ) + + body = _BasePublisherRestTransport._BasePublish._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BasePublisherRestTransport._BasePublish._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.PublisherClient.Publish", + extra={ + "serviceName": "google.pubsub.v1.Publisher", + "rpcName": "Publish", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PublisherRestTransport._Publish._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = pubsub.PublishResponse() + pb_resp = pubsub.PublishResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_publish(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_publish_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = pubsub.PublishResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.pubsub_v1.PublisherClient.publish", + extra={ + "serviceName": "google.pubsub.v1.Publisher", + "rpcName": "Publish", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateTopic(_BasePublisherRestTransport._BaseUpdateTopic, PublisherRestStub): + def __hash__(self): + return hash("PublisherRestTransport.UpdateTopic") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: pubsub.UpdateTopicRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.Topic: + r"""Call the update topic method over HTTP. + + Args: + request (~.pubsub.UpdateTopicRequest): + The request object. Request for the UpdateTopic method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.pubsub.Topic: + A topic resource. + """ + + http_options = ( + _BasePublisherRestTransport._BaseUpdateTopic._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_topic(request, metadata) + transcoded_request = ( + _BasePublisherRestTransport._BaseUpdateTopic._get_transcoded_request( + http_options, request + ) + ) + + body = _BasePublisherRestTransport._BaseUpdateTopic._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BasePublisherRestTransport._BaseUpdateTopic._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.PublisherClient.UpdateTopic", + extra={ + "serviceName": "google.pubsub.v1.Publisher", + "rpcName": "UpdateTopic", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PublisherRestTransport._UpdateTopic._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = pubsub.Topic() + pb_resp = pubsub.Topic.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_topic(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_topic_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = pubsub.Topic.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.pubsub_v1.PublisherClient.update_topic", + extra={ + "serviceName": "google.pubsub.v1.Publisher", + "rpcName": "UpdateTopic", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_topic(self) -> Callable[[pubsub.Topic], pubsub.Topic]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateTopic(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_topic(self) -> Callable[[pubsub.DeleteTopicRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteTopic(self._session, self._host, self._interceptor) # type: ignore + + @property + def detach_subscription( + self, + ) -> Callable[ + [pubsub.DetachSubscriptionRequest], pubsub.DetachSubscriptionResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DetachSubscription(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_topic(self) -> Callable[[pubsub.GetTopicRequest], pubsub.Topic]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetTopic(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_topics( + self, + ) -> Callable[[pubsub.ListTopicsRequest], pubsub.ListTopicsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListTopics(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_topic_snapshots( + self, + ) -> Callable[ + [pubsub.ListTopicSnapshotsRequest], pubsub.ListTopicSnapshotsResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListTopicSnapshots(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_topic_subscriptions( + self, + ) -> Callable[ + [pubsub.ListTopicSubscriptionsRequest], pubsub.ListTopicSubscriptionsResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListTopicSubscriptions( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def publish(self) -> Callable[[pubsub.PublishRequest], pubsub.PublishResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Publish(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_topic(self) -> Callable[[pubsub.UpdateTopicRequest], pubsub.Topic]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateTopic(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy( + _BasePublisherRestTransport._BaseGetIamPolicy, PublisherRestStub + ): + def __hash__(self): + return hash("PublisherRestTransport.GetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options = ( + _BasePublisherRestTransport._BaseGetIamPolicy._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + transcoded_request = ( + _BasePublisherRestTransport._BaseGetIamPolicy._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BasePublisherRestTransport._BaseGetIamPolicy._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.PublisherClient.GetIamPolicy", + extra={ + "serviceName": "google.pubsub.v1.Publisher", + "rpcName": "GetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PublisherRestTransport._GetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.pubsub_v1.PublisherAsyncClient.GetIamPolicy", + extra={ + "serviceName": "google.pubsub.v1.Publisher", + "rpcName": "GetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy( + _BasePublisherRestTransport._BaseSetIamPolicy, PublisherRestStub + ): + def __hash__(self): + return hash("PublisherRestTransport.SetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options = ( + _BasePublisherRestTransport._BaseSetIamPolicy._get_http_options() + ) + + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + transcoded_request = ( + _BasePublisherRestTransport._BaseSetIamPolicy._get_transcoded_request( + http_options, request + ) + ) + + body = _BasePublisherRestTransport._BaseSetIamPolicy._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BasePublisherRestTransport._BaseSetIamPolicy._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.PublisherClient.SetIamPolicy", + extra={ + "serviceName": "google.pubsub.v1.Publisher", + "rpcName": "SetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PublisherRestTransport._SetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_set_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.pubsub_v1.PublisherAsyncClient.SetIamPolicy", + extra={ + "serviceName": "google.pubsub.v1.Publisher", + "rpcName": "SetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions( + _BasePublisherRestTransport._BaseTestIamPermissions, PublisherRestStub + ): + def __hash__(self): + return hash("PublisherRestTransport.TestIamPermissions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options = ( + _BasePublisherRestTransport._BaseTestIamPermissions._get_http_options() + ) + + request, metadata = self._interceptor.pre_test_iam_permissions( + request, metadata + ) + transcoded_request = _BasePublisherRestTransport._BaseTestIamPermissions._get_transcoded_request( + http_options, request + ) + + body = _BasePublisherRestTransport._BaseTestIamPermissions._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BasePublisherRestTransport._BaseTestIamPermissions._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.PublisherClient.TestIamPermissions", + extra={ + "serviceName": "google.pubsub.v1.Publisher", + "rpcName": "TestIamPermissions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = PublisherRestTransport._TestIamPermissions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_test_iam_permissions(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.pubsub_v1.PublisherAsyncClient.TestIamPermissions", + extra={ + "serviceName": "google.pubsub.v1.Publisher", + "rpcName": "TestIamPermissions", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("PublisherRestTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/publisher/transports/rest_base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/publisher/transports/rest_base.py new file mode 100644 index 0000000000000000000000000000000000000000..e3db35dacb1f1ac43c8899c669d79d1d4017b9b7 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/publisher/transports/rest_base.py @@ -0,0 +1,678 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed 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. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.api_core import gapic_v1, path_template +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.protobuf import json_format + +from google.pubsub_v1.types import pubsub + +from .base import DEFAULT_CLIENT_INFO, PublisherTransport + + +class _BasePublisherRestTransport(PublisherTransport): + """Base REST backend transport for Publisher. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "pubsub.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'pubsub.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseCreateTopic: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "put", + "uri": "/v1/{name=projects/*/topics/*}", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = pubsub.Topic.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePublisherRestTransport._BaseCreateTopic._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteTopic: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{topic=projects/*/topics/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = pubsub.DeleteTopicRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePublisherRestTransport._BaseDeleteTopic._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDetachSubscription: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{subscription=projects/*/subscriptions/*}:detach", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = pubsub.DetachSubscriptionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePublisherRestTransport._BaseDetachSubscription._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetTopic: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{topic=projects/*/topics/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = pubsub.GetTopicRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePublisherRestTransport._BaseGetTopic._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListTopics: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{project=projects/*}/topics", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = pubsub.ListTopicsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePublisherRestTransport._BaseListTopics._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListTopicSnapshots: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{topic=projects/*/topics/*}/snapshots", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = pubsub.ListTopicSnapshotsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePublisherRestTransport._BaseListTopicSnapshots._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListTopicSubscriptions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{topic=projects/*/topics/*}/subscriptions", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = pubsub.ListTopicSubscriptionsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePublisherRestTransport._BaseListTopicSubscriptions._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BasePublish: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{topic=projects/*/topics/*}:publish", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = pubsub.PublishRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePublisherRestTransport._BasePublish._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateTopic: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{topic.name=projects/*/topics/*}", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = pubsub.UpdateTopicRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BasePublisherRestTransport._BaseUpdateTopic._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{resource=projects/*/topics/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/subscriptions/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/snapshots/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/schemas/*}:getIamPolicy", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseSetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{resource=projects/*/topics/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/subscriptions/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/snapshots/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/schemas/*}:setIamPolicy", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseTestIamPermissions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{resource=projects/*/subscriptions/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/topics/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/snapshots/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/schemas/*}:testIamPermissions", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BasePublisherRestTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/schema_service/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/schema_service/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f95513aefa30647cb58dda647bf8fb6280397838 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/schema_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed 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. +# +from .async_client import SchemaServiceAsyncClient +from .client import SchemaServiceClient + +__all__ = ( + "SchemaServiceClient", + "SchemaServiceAsyncClient", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/schema_service/async_client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/schema_service/async_client.py new file mode 100644 index 0000000000000000000000000000000000000000..190911e8786da362413677d1221735e962f3a43e --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/schema_service/async_client.py @@ -0,0 +1,1810 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed 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. +# +import logging as std_logging +import re +from collections import OrderedDict +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.pubsub_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) + +from google.pubsub_v1.services.schema_service import pagers +from google.pubsub_v1.types import schema +from google.pubsub_v1.types import schema as gp_schema + +from .client import SchemaServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, SchemaServiceTransport +from .transports.grpc_asyncio import SchemaServiceGrpcAsyncIOTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class SchemaServiceAsyncClient: + """Service for doing schema-related operations.""" + + _client: SchemaServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = SchemaServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SchemaServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = SchemaServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = SchemaServiceClient._DEFAULT_UNIVERSE + + schema_path = staticmethod(SchemaServiceClient.schema_path) + parse_schema_path = staticmethod(SchemaServiceClient.parse_schema_path) + common_billing_account_path = staticmethod( + SchemaServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + SchemaServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(SchemaServiceClient.common_folder_path) + parse_common_folder_path = staticmethod( + SchemaServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + SchemaServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + SchemaServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod(SchemaServiceClient.common_project_path) + parse_common_project_path = staticmethod( + SchemaServiceClient.parse_common_project_path + ) + common_location_path = staticmethod(SchemaServiceClient.common_location_path) + parse_common_location_path = staticmethod( + SchemaServiceClient.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SchemaServiceAsyncClient: The constructed client. + """ + sa_info_func = ( + SchemaServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(SchemaServiceAsyncClient, info, *args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SchemaServiceAsyncClient: The constructed client. + """ + sa_file_func = ( + SchemaServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(SchemaServiceAsyncClient, filename, *args, **kwargs) + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return SchemaServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> SchemaServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SchemaServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = SchemaServiceClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, SchemaServiceTransport, Callable[..., SchemaServiceTransport]] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the schema service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,SchemaServiceTransport,Callable[..., SchemaServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the SchemaServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = SchemaServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.pubsub_v1.SchemaServiceAsyncClient`.", + extra={ + "serviceName": "google.pubsub.v1.SchemaService", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.pubsub.v1.SchemaService", + "credentialsType": None, + }, + ) + + async def create_schema( + self, + request: Optional[Union[gp_schema.CreateSchemaRequest, dict]] = None, + *, + parent: Optional[str] = None, + schema: Optional[gp_schema.Schema] = None, + schema_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gp_schema.Schema: + r"""Creates a schema. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + async def sample_create_schema(): + # Create a client + client = pubsub_v1.SchemaServiceAsyncClient() + + # Initialize request argument(s) + schema = pubsub_v1.Schema() + schema.name = "name_value" + + request = pubsub_v1.CreateSchemaRequest( + parent="parent_value", + schema=schema, + ) + + # Make the request + response = await client.create_schema(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.pubsub_v1.types.CreateSchemaRequest, dict]]): + The request object. Request for the CreateSchema method. + parent (:class:`str`): + Required. The name of the project in which to create the + schema. Format is ``projects/{project-id}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + schema (:class:`google.pubsub_v1.types.Schema`): + Required. The schema object to create. + + This schema's ``name`` parameter is ignored. The schema + object returned by CreateSchema will have a ``name`` + made using the given ``parent`` and ``schema_id``. + + This corresponds to the ``schema`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + schema_id (:class:`str`): + The ID to use for the schema, which will become the + final component of the schema's resource name. + + See + https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names + for resource name constraints. + + This corresponds to the ``schema_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.types.Schema: + A schema resource. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, schema, schema_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gp_schema.CreateSchemaRequest): + request = gp_schema.CreateSchemaRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if schema is not None: + request.schema = schema + if schema_id is not None: + request.schema_id = schema_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_schema + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_schema( + self, + request: Optional[Union[schema.GetSchemaRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> schema.Schema: + r"""Gets a schema. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + async def sample_get_schema(): + # Create a client + client = pubsub_v1.SchemaServiceAsyncClient() + + # Initialize request argument(s) + request = pubsub_v1.GetSchemaRequest( + name="name_value", + ) + + # Make the request + response = await client.get_schema(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.pubsub_v1.types.GetSchemaRequest, dict]]): + The request object. Request for the GetSchema method. + name (:class:`str`): + Required. The name of the schema to get. Format is + ``projects/{project}/schemas/{schema}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.types.Schema: + A schema resource. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, schema.GetSchemaRequest): + request = schema.GetSchemaRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_schema + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_schemas( + self, + request: Optional[Union[schema.ListSchemasRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListSchemasAsyncPager: + r"""Lists schemas in a project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + async def sample_list_schemas(): + # Create a client + client = pubsub_v1.SchemaServiceAsyncClient() + + # Initialize request argument(s) + request = pubsub_v1.ListSchemasRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_schemas(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.pubsub_v1.types.ListSchemasRequest, dict]]): + The request object. Request for the ``ListSchemas`` method. + parent (:class:`str`): + Required. The name of the project in which to list + schemas. Format is ``projects/{project-id}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.services.schema_service.pagers.ListSchemasAsyncPager: + Response for the ListSchemas method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, schema.ListSchemasRequest): + request = schema.ListSchemasRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_schemas + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListSchemasAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_schema_revisions( + self, + request: Optional[Union[schema.ListSchemaRevisionsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListSchemaRevisionsAsyncPager: + r"""Lists all schema revisions for the named schema. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + async def sample_list_schema_revisions(): + # Create a client + client = pubsub_v1.SchemaServiceAsyncClient() + + # Initialize request argument(s) + request = pubsub_v1.ListSchemaRevisionsRequest( + name="name_value", + ) + + # Make the request + page_result = client.list_schema_revisions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.pubsub_v1.types.ListSchemaRevisionsRequest, dict]]): + The request object. Request for the ``ListSchemaRevisions`` method. + name (:class:`str`): + Required. The name of the schema to + list revisions for. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.services.schema_service.pagers.ListSchemaRevisionsAsyncPager: + Response for the ListSchemaRevisions method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, schema.ListSchemaRevisionsRequest): + request = schema.ListSchemaRevisionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_schema_revisions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListSchemaRevisionsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def commit_schema( + self, + request: Optional[Union[gp_schema.CommitSchemaRequest, dict]] = None, + *, + name: Optional[str] = None, + schema: Optional[gp_schema.Schema] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gp_schema.Schema: + r"""Commits a new schema revision to an existing schema. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + async def sample_commit_schema(): + # Create a client + client = pubsub_v1.SchemaServiceAsyncClient() + + # Initialize request argument(s) + schema = pubsub_v1.Schema() + schema.name = "name_value" + + request = pubsub_v1.CommitSchemaRequest( + name="name_value", + schema=schema, + ) + + # Make the request + response = await client.commit_schema(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.pubsub_v1.types.CommitSchemaRequest, dict]]): + The request object. Request for CommitSchema method. + name (:class:`str`): + Required. The name of the schema we are revising. Format + is ``projects/{project}/schemas/{schema}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + schema (:class:`google.pubsub_v1.types.Schema`): + Required. The schema revision to + commit. + + This corresponds to the ``schema`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.types.Schema: + A schema resource. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, schema] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gp_schema.CommitSchemaRequest): + request = gp_schema.CommitSchemaRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if schema is not None: + request.schema = schema + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.commit_schema + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def rollback_schema( + self, + request: Optional[Union[schema.RollbackSchemaRequest, dict]] = None, + *, + name: Optional[str] = None, + revision_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> schema.Schema: + r"""Creates a new schema revision that is a copy of the provided + revision_id. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + async def sample_rollback_schema(): + # Create a client + client = pubsub_v1.SchemaServiceAsyncClient() + + # Initialize request argument(s) + request = pubsub_v1.RollbackSchemaRequest( + name="name_value", + revision_id="revision_id_value", + ) + + # Make the request + response = await client.rollback_schema(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.pubsub_v1.types.RollbackSchemaRequest, dict]]): + The request object. Request for the ``RollbackSchema`` method. + name (:class:`str`): + Required. The schema being rolled + back with revision id. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + revision_id (:class:`str`): + Required. The revision ID to roll + back to. It must be a revision of the + same schema. + + Example: c7cfa2a8 + + This corresponds to the ``revision_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.types.Schema: + A schema resource. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, revision_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, schema.RollbackSchemaRequest): + request = schema.RollbackSchemaRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if revision_id is not None: + request.revision_id = revision_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.rollback_schema + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_schema_revision( + self, + request: Optional[Union[schema.DeleteSchemaRevisionRequest, dict]] = None, + *, + name: Optional[str] = None, + revision_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> schema.Schema: + r"""Deletes a specific schema revision. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + async def sample_delete_schema_revision(): + # Create a client + client = pubsub_v1.SchemaServiceAsyncClient() + + # Initialize request argument(s) + request = pubsub_v1.DeleteSchemaRevisionRequest( + name="name_value", + ) + + # Make the request + response = await client.delete_schema_revision(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.pubsub_v1.types.DeleteSchemaRevisionRequest, dict]]): + The request object. Request for the ``DeleteSchemaRevision`` method. + name (:class:`str`): + Required. The name of the schema revision to be deleted, + with a revision ID explicitly included. + + Example: ``projects/123/schemas/my-schema@c7cfa2a8`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + revision_id (:class:`str`): + Optional. This field is deprecated and should not be + used for specifying the revision ID. The revision ID + should be specified via the ``name`` parameter. + + This corresponds to the ``revision_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.types.Schema: + A schema resource. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, revision_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, schema.DeleteSchemaRevisionRequest): + request = schema.DeleteSchemaRevisionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if revision_id is not None: + request.revision_id = revision_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_schema_revision + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_schema( + self, + request: Optional[Union[schema.DeleteSchemaRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a schema. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + async def sample_delete_schema(): + # Create a client + client = pubsub_v1.SchemaServiceAsyncClient() + + # Initialize request argument(s) + request = pubsub_v1.DeleteSchemaRequest( + name="name_value", + ) + + # Make the request + await client.delete_schema(request=request) + + Args: + request (Optional[Union[google.pubsub_v1.types.DeleteSchemaRequest, dict]]): + The request object. Request for the ``DeleteSchema`` method. + name (:class:`str`): + Required. Name of the schema to delete. Format is + ``projects/{project}/schemas/{schema}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, schema.DeleteSchemaRequest): + request = schema.DeleteSchemaRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_schema + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def validate_schema( + self, + request: Optional[Union[gp_schema.ValidateSchemaRequest, dict]] = None, + *, + parent: Optional[str] = None, + schema: Optional[gp_schema.Schema] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gp_schema.ValidateSchemaResponse: + r"""Validates a schema. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + async def sample_validate_schema(): + # Create a client + client = pubsub_v1.SchemaServiceAsyncClient() + + # Initialize request argument(s) + schema = pubsub_v1.Schema() + schema.name = "name_value" + + request = pubsub_v1.ValidateSchemaRequest( + parent="parent_value", + schema=schema, + ) + + # Make the request + response = await client.validate_schema(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.pubsub_v1.types.ValidateSchemaRequest, dict]]): + The request object. Request for the ``ValidateSchema`` method. + parent (:class:`str`): + Required. The name of the project in which to validate + schemas. Format is ``projects/{project-id}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + schema (:class:`google.pubsub_v1.types.Schema`): + Required. The schema object to + validate. + + This corresponds to the ``schema`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.types.ValidateSchemaResponse: + Response for the ValidateSchema method. + Empty for now. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, schema] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gp_schema.ValidateSchemaRequest): + request = gp_schema.ValidateSchemaRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if schema is not None: + request.schema = schema + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.validate_schema + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def validate_message( + self, + request: Optional[Union[schema.ValidateMessageRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> schema.ValidateMessageResponse: + r"""Validates a message against a schema. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + async def sample_validate_message(): + # Create a client + client = pubsub_v1.SchemaServiceAsyncClient() + + # Initialize request argument(s) + request = pubsub_v1.ValidateMessageRequest( + name="name_value", + parent="parent_value", + ) + + # Make the request + response = await client.validate_message(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.pubsub_v1.types.ValidateMessageRequest, dict]]): + The request object. Request for the ``ValidateMessage`` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.types.ValidateMessageResponse: + Response for the ValidateMessage method. + Empty for now. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, schema.ValidateMessageRequest): + request = schema.ValidateMessageRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.validate_message + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[ + self._client._transport.test_iam_permissions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "SchemaServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + client_library_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("SchemaServiceAsyncClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/schema_service/client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/schema_service/client.py new file mode 100644 index 0000000000000000000000000000000000000000..b658add6b91c70df270d21cd720462e9529b62af --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/schema_service/client.py @@ -0,0 +1,2241 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed 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. +# +import json +import functools +import grpc +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.pubsub_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) + +from google.pubsub_v1.services.schema_service import pagers +from google.pubsub_v1.types import schema +from google.pubsub_v1.types import schema as gp_schema + +from .transports.base import DEFAULT_CLIENT_INFO, SchemaServiceTransport +from .transports.grpc import SchemaServiceGrpcTransport +from .transports.grpc_asyncio import SchemaServiceGrpcAsyncIOTransport +from .transports.rest import SchemaServiceRestTransport + + +class SchemaServiceClientMeta(type): + """Metaclass for the SchemaService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[SchemaServiceTransport]] + _transport_registry["grpc"] = SchemaServiceGrpcTransport + _transport_registry["grpc_asyncio"] = SchemaServiceGrpcAsyncIOTransport + _transport_registry["rest"] = SchemaServiceRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[SchemaServiceTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class SchemaServiceClient(metaclass=SchemaServiceClientMeta): + """Service for doing schema-related operations.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + Optional[str]: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # Could not parse api_endpoint; return as-is. + return api_endpoint + + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + _DEFAULT_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/pubsub", + ) + SERVICE_ADDRESS = "pubsub.googleapis.com:443" + """The default address of the service.""" + DEFAULT_ENDPOINT = "pubsub.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "pubsub.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SchemaServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SchemaServiceClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> SchemaServiceTransport: + """Returns the transport used by the client instance. + + Returns: + SchemaServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def schema_path( + project: str, + schema: str, + ) -> str: + """Returns a fully-qualified schema string.""" + return "projects/{project}/schemas/{schema}".format( + project=project, + schema=schema, + ) + + @staticmethod + def parse_schema_path(path: str) -> Dict[str, str]: + """Parses a schema path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/schemas/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = SchemaServiceClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = SchemaServiceClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ) -> str: + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = SchemaServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = SchemaServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = SchemaServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = SchemaServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, SchemaServiceTransport, Callable[..., SchemaServiceTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the schema service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,SchemaServiceTransport,Callable[..., SchemaServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the SchemaServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + SchemaServiceClient._read_environment_variables() + ) + self._client_cert_source = SchemaServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = SchemaServiceClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, SchemaServiceTransport) + if transport_provided: + # transport is a SchemaServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(SchemaServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or SchemaServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[SchemaServiceTransport], Callable[..., SchemaServiceTransport] + ] = ( + SchemaServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., SchemaServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + emulator_host = os.environ.get("PUBSUB_EMULATOR_HOST") + if emulator_host: + if issubclass(transport_init, type(self)._transport_registry["grpc"]): # type: ignore + channel = grpc.insecure_channel(target=emulator_host) + else: + channel = grpc.aio.insecure_channel(target=emulator_host) + transport_init = functools.partial(transport_init, channel=channel) + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.pubsub_v1.SchemaServiceClient`.", + extra={ + "serviceName": "google.pubsub.v1.SchemaService", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.pubsub.v1.SchemaService", + "credentialsType": None, + }, + ) + + def create_schema( + self, + request: Optional[Union[gp_schema.CreateSchemaRequest, dict]] = None, + *, + parent: Optional[str] = None, + schema: Optional[gp_schema.Schema] = None, + schema_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gp_schema.Schema: + r"""Creates a schema. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + def sample_create_schema(): + # Create a client + client = pubsub_v1.SchemaServiceClient() + + # Initialize request argument(s) + schema = pubsub_v1.Schema() + schema.name = "name_value" + + request = pubsub_v1.CreateSchemaRequest( + parent="parent_value", + schema=schema, + ) + + # Make the request + response = client.create_schema(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.pubsub_v1.types.CreateSchemaRequest, dict]): + The request object. Request for the CreateSchema method. + parent (str): + Required. The name of the project in which to create the + schema. Format is ``projects/{project-id}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + schema (google.pubsub_v1.types.Schema): + Required. The schema object to create. + + This schema's ``name`` parameter is ignored. The schema + object returned by CreateSchema will have a ``name`` + made using the given ``parent`` and ``schema_id``. + + This corresponds to the ``schema`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + schema_id (str): + The ID to use for the schema, which will become the + final component of the schema's resource name. + + See + https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names + for resource name constraints. + + This corresponds to the ``schema_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.types.Schema: + A schema resource. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, schema, schema_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gp_schema.CreateSchemaRequest): + request = gp_schema.CreateSchemaRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if schema is not None: + request.schema = schema + if schema_id is not None: + request.schema_id = schema_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_schema] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_schema( + self, + request: Optional[Union[schema.GetSchemaRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> schema.Schema: + r"""Gets a schema. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + def sample_get_schema(): + # Create a client + client = pubsub_v1.SchemaServiceClient() + + # Initialize request argument(s) + request = pubsub_v1.GetSchemaRequest( + name="name_value", + ) + + # Make the request + response = client.get_schema(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.pubsub_v1.types.GetSchemaRequest, dict]): + The request object. Request for the GetSchema method. + name (str): + Required. The name of the schema to get. Format is + ``projects/{project}/schemas/{schema}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.types.Schema: + A schema resource. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, schema.GetSchemaRequest): + request = schema.GetSchemaRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_schema] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_schemas( + self, + request: Optional[Union[schema.ListSchemasRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListSchemasPager: + r"""Lists schemas in a project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + def sample_list_schemas(): + # Create a client + client = pubsub_v1.SchemaServiceClient() + + # Initialize request argument(s) + request = pubsub_v1.ListSchemasRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_schemas(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.pubsub_v1.types.ListSchemasRequest, dict]): + The request object. Request for the ``ListSchemas`` method. + parent (str): + Required. The name of the project in which to list + schemas. Format is ``projects/{project-id}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.services.schema_service.pagers.ListSchemasPager: + Response for the ListSchemas method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, schema.ListSchemasRequest): + request = schema.ListSchemasRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_schemas] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListSchemasPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_schema_revisions( + self, + request: Optional[Union[schema.ListSchemaRevisionsRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListSchemaRevisionsPager: + r"""Lists all schema revisions for the named schema. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + def sample_list_schema_revisions(): + # Create a client + client = pubsub_v1.SchemaServiceClient() + + # Initialize request argument(s) + request = pubsub_v1.ListSchemaRevisionsRequest( + name="name_value", + ) + + # Make the request + page_result = client.list_schema_revisions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.pubsub_v1.types.ListSchemaRevisionsRequest, dict]): + The request object. Request for the ``ListSchemaRevisions`` method. + name (str): + Required. The name of the schema to + list revisions for. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.services.schema_service.pagers.ListSchemaRevisionsPager: + Response for the ListSchemaRevisions method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, schema.ListSchemaRevisionsRequest): + request = schema.ListSchemaRevisionsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_schema_revisions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListSchemaRevisionsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def commit_schema( + self, + request: Optional[Union[gp_schema.CommitSchemaRequest, dict]] = None, + *, + name: Optional[str] = None, + schema: Optional[gp_schema.Schema] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gp_schema.Schema: + r"""Commits a new schema revision to an existing schema. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + def sample_commit_schema(): + # Create a client + client = pubsub_v1.SchemaServiceClient() + + # Initialize request argument(s) + schema = pubsub_v1.Schema() + schema.name = "name_value" + + request = pubsub_v1.CommitSchemaRequest( + name="name_value", + schema=schema, + ) + + # Make the request + response = client.commit_schema(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.pubsub_v1.types.CommitSchemaRequest, dict]): + The request object. Request for CommitSchema method. + name (str): + Required. The name of the schema we are revising. Format + is ``projects/{project}/schemas/{schema}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + schema (google.pubsub_v1.types.Schema): + Required. The schema revision to + commit. + + This corresponds to the ``schema`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.types.Schema: + A schema resource. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, schema] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gp_schema.CommitSchemaRequest): + request = gp_schema.CommitSchemaRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if schema is not None: + request.schema = schema + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.commit_schema] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def rollback_schema( + self, + request: Optional[Union[schema.RollbackSchemaRequest, dict]] = None, + *, + name: Optional[str] = None, + revision_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> schema.Schema: + r"""Creates a new schema revision that is a copy of the provided + revision_id. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + def sample_rollback_schema(): + # Create a client + client = pubsub_v1.SchemaServiceClient() + + # Initialize request argument(s) + request = pubsub_v1.RollbackSchemaRequest( + name="name_value", + revision_id="revision_id_value", + ) + + # Make the request + response = client.rollback_schema(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.pubsub_v1.types.RollbackSchemaRequest, dict]): + The request object. Request for the ``RollbackSchema`` method. + name (str): + Required. The schema being rolled + back with revision id. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + revision_id (str): + Required. The revision ID to roll + back to. It must be a revision of the + same schema. + + Example: c7cfa2a8 + + This corresponds to the ``revision_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.types.Schema: + A schema resource. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, revision_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, schema.RollbackSchemaRequest): + request = schema.RollbackSchemaRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if revision_id is not None: + request.revision_id = revision_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.rollback_schema] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_schema_revision( + self, + request: Optional[Union[schema.DeleteSchemaRevisionRequest, dict]] = None, + *, + name: Optional[str] = None, + revision_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> schema.Schema: + r"""Deletes a specific schema revision. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + def sample_delete_schema_revision(): + # Create a client + client = pubsub_v1.SchemaServiceClient() + + # Initialize request argument(s) + request = pubsub_v1.DeleteSchemaRevisionRequest( + name="name_value", + ) + + # Make the request + response = client.delete_schema_revision(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.pubsub_v1.types.DeleteSchemaRevisionRequest, dict]): + The request object. Request for the ``DeleteSchemaRevision`` method. + name (str): + Required. The name of the schema revision to be deleted, + with a revision ID explicitly included. + + Example: ``projects/123/schemas/my-schema@c7cfa2a8`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + revision_id (str): + Optional. This field is deprecated and should not be + used for specifying the revision ID. The revision ID + should be specified via the ``name`` parameter. + + This corresponds to the ``revision_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.types.Schema: + A schema resource. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, revision_id] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, schema.DeleteSchemaRevisionRequest): + request = schema.DeleteSchemaRevisionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if revision_id is not None: + request.revision_id = revision_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_schema_revision] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_schema( + self, + request: Optional[Union[schema.DeleteSchemaRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes a schema. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + def sample_delete_schema(): + # Create a client + client = pubsub_v1.SchemaServiceClient() + + # Initialize request argument(s) + request = pubsub_v1.DeleteSchemaRequest( + name="name_value", + ) + + # Make the request + client.delete_schema(request=request) + + Args: + request (Union[google.pubsub_v1.types.DeleteSchemaRequest, dict]): + The request object. Request for the ``DeleteSchema`` method. + name (str): + Required. Name of the schema to delete. Format is + ``projects/{project}/schemas/{schema}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, schema.DeleteSchemaRequest): + request = schema.DeleteSchemaRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_schema] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def validate_schema( + self, + request: Optional[Union[gp_schema.ValidateSchemaRequest, dict]] = None, + *, + parent: Optional[str] = None, + schema: Optional[gp_schema.Schema] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gp_schema.ValidateSchemaResponse: + r"""Validates a schema. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + def sample_validate_schema(): + # Create a client + client = pubsub_v1.SchemaServiceClient() + + # Initialize request argument(s) + schema = pubsub_v1.Schema() + schema.name = "name_value" + + request = pubsub_v1.ValidateSchemaRequest( + parent="parent_value", + schema=schema, + ) + + # Make the request + response = client.validate_schema(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.pubsub_v1.types.ValidateSchemaRequest, dict]): + The request object. Request for the ``ValidateSchema`` method. + parent (str): + Required. The name of the project in which to validate + schemas. Format is ``projects/{project-id}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + schema (google.pubsub_v1.types.Schema): + Required. The schema object to + validate. + + This corresponds to the ``schema`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.types.ValidateSchemaResponse: + Response for the ValidateSchema method. + Empty for now. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [parent, schema] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, gp_schema.ValidateSchemaRequest): + request = gp_schema.ValidateSchemaRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if schema is not None: + request.schema = schema + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.validate_schema] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def validate_message( + self, + request: Optional[Union[schema.ValidateMessageRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> schema.ValidateMessageResponse: + r"""Validates a message against a schema. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + def sample_validate_message(): + # Create a client + client = pubsub_v1.SchemaServiceClient() + + # Initialize request argument(s) + request = pubsub_v1.ValidateMessageRequest( + name="name_value", + parent="parent_value", + ) + + # Make the request + response = client.validate_message(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.pubsub_v1.types.ValidateMessageRequest, dict]): + The request object. Request for the ``ValidateMessage`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.types.ValidateMessageResponse: + Response for the ValidateMessage method. + Empty for now. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, schema.ValidateMessageRequest): + request = schema.ValidateMessageRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.validate_message] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "SchemaServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def test_iam_permissions( + self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + client_library_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("SchemaServiceClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/schema_service/pagers.py b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/schema_service/pagers.py new file mode 100644 index 0000000000000000000000000000000000000000..729b5c6e92c57dd4c537ccd42e7eae76c4d07187 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/schema_service/pagers.py @@ -0,0 +1,353 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed 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. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[ + retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None + ] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.pubsub_v1.types import schema + + +class ListSchemasPager: + """A pager for iterating through ``list_schemas`` requests. + + This class thinly wraps an initial + :class:`google.pubsub_v1.types.ListSchemasResponse` object, and + provides an ``__iter__`` method to iterate through its + ``schemas`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSchemas`` requests and continue to iterate + through the ``schemas`` field on the + corresponding responses. + + All the usual :class:`google.pubsub_v1.types.ListSchemasResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., schema.ListSchemasResponse], + request: schema.ListSchemasRequest, + response: schema.ListSchemasResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.pubsub_v1.types.ListSchemasRequest): + The initial request object. + response (google.pubsub_v1.types.ListSchemasResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = schema.ListSchemasRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[schema.ListSchemasResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[schema.Schema]: + for page in self.pages: + yield from page.schemas + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSchemasAsyncPager: + """A pager for iterating through ``list_schemas`` requests. + + This class thinly wraps an initial + :class:`google.pubsub_v1.types.ListSchemasResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``schemas`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSchemas`` requests and continue to iterate + through the ``schemas`` field on the + corresponding responses. + + All the usual :class:`google.pubsub_v1.types.ListSchemasResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[schema.ListSchemasResponse]], + request: schema.ListSchemasRequest, + response: schema.ListSchemasResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.pubsub_v1.types.ListSchemasRequest): + The initial request object. + response (google.pubsub_v1.types.ListSchemasResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = schema.ListSchemasRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[schema.ListSchemasResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[schema.Schema]: + async def async_generator(): + async for page in self.pages: + for response in page.schemas: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSchemaRevisionsPager: + """A pager for iterating through ``list_schema_revisions`` requests. + + This class thinly wraps an initial + :class:`google.pubsub_v1.types.ListSchemaRevisionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``schemas`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSchemaRevisions`` requests and continue to iterate + through the ``schemas`` field on the + corresponding responses. + + All the usual :class:`google.pubsub_v1.types.ListSchemaRevisionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., schema.ListSchemaRevisionsResponse], + request: schema.ListSchemaRevisionsRequest, + response: schema.ListSchemaRevisionsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.pubsub_v1.types.ListSchemaRevisionsRequest): + The initial request object. + response (google.pubsub_v1.types.ListSchemaRevisionsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = schema.ListSchemaRevisionsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[schema.ListSchemaRevisionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[schema.Schema]: + for page in self.pages: + yield from page.schemas + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSchemaRevisionsAsyncPager: + """A pager for iterating through ``list_schema_revisions`` requests. + + This class thinly wraps an initial + :class:`google.pubsub_v1.types.ListSchemaRevisionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``schemas`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSchemaRevisions`` requests and continue to iterate + through the ``schemas`` field on the + corresponding responses. + + All the usual :class:`google.pubsub_v1.types.ListSchemaRevisionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[schema.ListSchemaRevisionsResponse]], + request: schema.ListSchemaRevisionsRequest, + response: schema.ListSchemaRevisionsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.pubsub_v1.types.ListSchemaRevisionsRequest): + The initial request object. + response (google.pubsub_v1.types.ListSchemaRevisionsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = schema.ListSchemaRevisionsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[schema.ListSchemaRevisionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[schema.Schema]: + async def async_generator(): + async for page in self.pages: + for response in page.schemas: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/schema_service/transports/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/schema_service/transports/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d21d5baa6100d9cd65db3b9af5ced37122a7baa4 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/schema_service/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed 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. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import SchemaServiceTransport +from .grpc import SchemaServiceGrpcTransport +from .grpc_asyncio import SchemaServiceGrpcAsyncIOTransport +from .rest import SchemaServiceRestInterceptor, SchemaServiceRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SchemaServiceTransport]] +_transport_registry["grpc"] = SchemaServiceGrpcTransport +_transport_registry["grpc_asyncio"] = SchemaServiceGrpcAsyncIOTransport +_transport_registry["rest"] = SchemaServiceRestTransport + +__all__ = ( + "SchemaServiceTransport", + "SchemaServiceGrpcTransport", + "SchemaServiceGrpcAsyncIOTransport", + "SchemaServiceRestTransport", + "SchemaServiceRestInterceptor", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/schema_service/transports/base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/schema_service/transports/base.py new file mode 100644 index 0000000000000000000000000000000000000000..8467673376725c5d6ca25ade4f12d58370b553d2 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/schema_service/transports/base.py @@ -0,0 +1,450 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed 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. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +import google.auth # type: ignore +import google.protobuf +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.oauth2 import service_account # type: ignore + +from google.pubsub_v1 import gapic_version as package_version +from google.pubsub_v1.types import schema +from google.pubsub_v1.types import schema as gp_schema + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + client_library_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class SchemaServiceTransport(abc.ABC): + """Abstract transport class for SchemaService.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/pubsub", + ) + + DEFAULT_HOST: str = "pubsub.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'pubsub.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_schema: gapic_v1.method.wrap_method( + self.create_schema, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_schema: gapic_v1.method.wrap_method( + self.get_schema, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_schemas: gapic_v1.method.wrap_method( + self.list_schemas, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_schema_revisions: gapic_v1.method.wrap_method( + self.list_schema_revisions, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.commit_schema: gapic_v1.method.wrap_method( + self.commit_schema, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.rollback_schema: gapic_v1.method.wrap_method( + self.rollback_schema, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_schema_revision: gapic_v1.method.wrap_method( + self.delete_schema_revision, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_schema: gapic_v1.method.wrap_method( + self.delete_schema, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.validate_schema: gapic_v1.method.wrap_method( + self.validate_schema, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.validate_message: gapic_v1.method.wrap_method( + self.validate_message, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def create_schema( + self, + ) -> Callable[ + [gp_schema.CreateSchemaRequest], + Union[gp_schema.Schema, Awaitable[gp_schema.Schema]], + ]: + raise NotImplementedError() + + @property + def get_schema( + self, + ) -> Callable[ + [schema.GetSchemaRequest], Union[schema.Schema, Awaitable[schema.Schema]] + ]: + raise NotImplementedError() + + @property + def list_schemas( + self, + ) -> Callable[ + [schema.ListSchemasRequest], + Union[schema.ListSchemasResponse, Awaitable[schema.ListSchemasResponse]], + ]: + raise NotImplementedError() + + @property + def list_schema_revisions( + self, + ) -> Callable[ + [schema.ListSchemaRevisionsRequest], + Union[ + schema.ListSchemaRevisionsResponse, + Awaitable[schema.ListSchemaRevisionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def commit_schema( + self, + ) -> Callable[ + [gp_schema.CommitSchemaRequest], + Union[gp_schema.Schema, Awaitable[gp_schema.Schema]], + ]: + raise NotImplementedError() + + @property + def rollback_schema( + self, + ) -> Callable[ + [schema.RollbackSchemaRequest], Union[schema.Schema, Awaitable[schema.Schema]] + ]: + raise NotImplementedError() + + @property + def delete_schema_revision( + self, + ) -> Callable[ + [schema.DeleteSchemaRevisionRequest], + Union[schema.Schema, Awaitable[schema.Schema]], + ]: + raise NotImplementedError() + + @property + def delete_schema( + self, + ) -> Callable[ + [schema.DeleteSchemaRequest], Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]] + ]: + raise NotImplementedError() + + @property + def validate_schema( + self, + ) -> Callable[ + [gp_schema.ValidateSchemaRequest], + Union[ + gp_schema.ValidateSchemaResponse, + Awaitable[gp_schema.ValidateSchemaResponse], + ], + ]: + raise NotImplementedError() + + @property + def validate_message( + self, + ) -> Callable[ + [schema.ValidateMessageRequest], + Union[ + schema.ValidateMessageResponse, Awaitable[schema.ValidateMessageResponse] + ], + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("SchemaServiceTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/schema_service/transports/grpc.py b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/schema_service/transports/grpc.py new file mode 100644 index 0000000000000000000000000000000000000000..7a13cfcbd14ea6670b3b12e731b41e44da7df114 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/schema_service/transports/grpc.py @@ -0,0 +1,683 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed 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. +# +import json +import logging as std_logging +import pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +import google.auth # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.protobuf.json_format import MessageToJson + +from google.pubsub_v1.types import schema +from google.pubsub_v1.types import schema as gp_schema + +from .base import DEFAULT_CLIENT_INFO, SchemaServiceTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.pubsub.v1.SchemaService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.pubsub.v1.SchemaService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class SchemaServiceGrpcTransport(SchemaServiceTransport): + """gRPC backend transport for SchemaService. + + Service for doing schema-related operations. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "pubsub.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'pubsub.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ("grpc.max_metadata_size", 4 * 1024 * 1024), + ("grpc.keepalive_time_ms", 30000), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "pubsub.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def create_schema( + self, + ) -> Callable[[gp_schema.CreateSchemaRequest], gp_schema.Schema]: + r"""Return a callable for the create schema method over gRPC. + + Creates a schema. + + Returns: + Callable[[~.CreateSchemaRequest], + ~.Schema]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_schema" not in self._stubs: + self._stubs["create_schema"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.SchemaService/CreateSchema", + request_serializer=gp_schema.CreateSchemaRequest.serialize, + response_deserializer=gp_schema.Schema.deserialize, + ) + return self._stubs["create_schema"] + + @property + def get_schema(self) -> Callable[[schema.GetSchemaRequest], schema.Schema]: + r"""Return a callable for the get schema method over gRPC. + + Gets a schema. + + Returns: + Callable[[~.GetSchemaRequest], + ~.Schema]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_schema" not in self._stubs: + self._stubs["get_schema"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.SchemaService/GetSchema", + request_serializer=schema.GetSchemaRequest.serialize, + response_deserializer=schema.Schema.deserialize, + ) + return self._stubs["get_schema"] + + @property + def list_schemas( + self, + ) -> Callable[[schema.ListSchemasRequest], schema.ListSchemasResponse]: + r"""Return a callable for the list schemas method over gRPC. + + Lists schemas in a project. + + Returns: + Callable[[~.ListSchemasRequest], + ~.ListSchemasResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_schemas" not in self._stubs: + self._stubs["list_schemas"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.SchemaService/ListSchemas", + request_serializer=schema.ListSchemasRequest.serialize, + response_deserializer=schema.ListSchemasResponse.deserialize, + ) + return self._stubs["list_schemas"] + + @property + def list_schema_revisions( + self, + ) -> Callable[ + [schema.ListSchemaRevisionsRequest], schema.ListSchemaRevisionsResponse + ]: + r"""Return a callable for the list schema revisions method over gRPC. + + Lists all schema revisions for the named schema. + + Returns: + Callable[[~.ListSchemaRevisionsRequest], + ~.ListSchemaRevisionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_schema_revisions" not in self._stubs: + self._stubs["list_schema_revisions"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.SchemaService/ListSchemaRevisions", + request_serializer=schema.ListSchemaRevisionsRequest.serialize, + response_deserializer=schema.ListSchemaRevisionsResponse.deserialize, + ) + return self._stubs["list_schema_revisions"] + + @property + def commit_schema( + self, + ) -> Callable[[gp_schema.CommitSchemaRequest], gp_schema.Schema]: + r"""Return a callable for the commit schema method over gRPC. + + Commits a new schema revision to an existing schema. + + Returns: + Callable[[~.CommitSchemaRequest], + ~.Schema]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "commit_schema" not in self._stubs: + self._stubs["commit_schema"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.SchemaService/CommitSchema", + request_serializer=gp_schema.CommitSchemaRequest.serialize, + response_deserializer=gp_schema.Schema.deserialize, + ) + return self._stubs["commit_schema"] + + @property + def rollback_schema( + self, + ) -> Callable[[schema.RollbackSchemaRequest], schema.Schema]: + r"""Return a callable for the rollback schema method over gRPC. + + Creates a new schema revision that is a copy of the provided + revision_id. + + Returns: + Callable[[~.RollbackSchemaRequest], + ~.Schema]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "rollback_schema" not in self._stubs: + self._stubs["rollback_schema"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.SchemaService/RollbackSchema", + request_serializer=schema.RollbackSchemaRequest.serialize, + response_deserializer=schema.Schema.deserialize, + ) + return self._stubs["rollback_schema"] + + @property + def delete_schema_revision( + self, + ) -> Callable[[schema.DeleteSchemaRevisionRequest], schema.Schema]: + r"""Return a callable for the delete schema revision method over gRPC. + + Deletes a specific schema revision. + + Returns: + Callable[[~.DeleteSchemaRevisionRequest], + ~.Schema]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_schema_revision" not in self._stubs: + self._stubs["delete_schema_revision"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.SchemaService/DeleteSchemaRevision", + request_serializer=schema.DeleteSchemaRevisionRequest.serialize, + response_deserializer=schema.Schema.deserialize, + ) + return self._stubs["delete_schema_revision"] + + @property + def delete_schema(self) -> Callable[[schema.DeleteSchemaRequest], empty_pb2.Empty]: + r"""Return a callable for the delete schema method over gRPC. + + Deletes a schema. + + Returns: + Callable[[~.DeleteSchemaRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_schema" not in self._stubs: + self._stubs["delete_schema"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.SchemaService/DeleteSchema", + request_serializer=schema.DeleteSchemaRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_schema"] + + @property + def validate_schema( + self, + ) -> Callable[[gp_schema.ValidateSchemaRequest], gp_schema.ValidateSchemaResponse]: + r"""Return a callable for the validate schema method over gRPC. + + Validates a schema. + + Returns: + Callable[[~.ValidateSchemaRequest], + ~.ValidateSchemaResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "validate_schema" not in self._stubs: + self._stubs["validate_schema"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.SchemaService/ValidateSchema", + request_serializer=gp_schema.ValidateSchemaRequest.serialize, + response_deserializer=gp_schema.ValidateSchemaResponse.deserialize, + ) + return self._stubs["validate_schema"] + + @property + def validate_message( + self, + ) -> Callable[[schema.ValidateMessageRequest], schema.ValidateMessageResponse]: + r"""Return a callable for the validate message method over gRPC. + + Validates a message against a schema. + + Returns: + Callable[[~.ValidateMessageRequest], + ~.ValidateMessageResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "validate_message" not in self._stubs: + self._stubs["validate_message"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.SchemaService/ValidateMessage", + request_serializer=schema.ValidateMessageRequest.serialize, + response_deserializer=schema.ValidateMessageResponse.deserialize, + ) + return self._stubs["validate_message"] + + def close(self): + self._logged_channel.close() + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("SchemaServiceGrpcTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..ee9c0fd90c232e9aa0b01aaebbb6ab39b926f519 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/schema_service/transports/grpc_asyncio.py @@ -0,0 +1,865 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed 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. +# +import inspect +import json +import logging as std_logging +import pickle +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.protobuf.json_format import MessageToJson +from grpc.experimental import aio # type: ignore + +from google.pubsub_v1.types import schema +from google.pubsub_v1.types import schema as gp_schema + +from .base import DEFAULT_CLIENT_INFO, SchemaServiceTransport +from .grpc import SchemaServiceGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.pubsub.v1.SchemaService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.pubsub.v1.SchemaService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class SchemaServiceGrpcAsyncIOTransport(SchemaServiceTransport): + """gRPC AsyncIO backend transport for SchemaService. + + Service for doing schema-related operations. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "pubsub.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "pubsub.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'pubsub.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ("grpc.max_metadata_size", 4 * 1024 * 1024), + ("grpc.keepalive_time_ms", 30000), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_schema( + self, + ) -> Callable[[gp_schema.CreateSchemaRequest], Awaitable[gp_schema.Schema]]: + r"""Return a callable for the create schema method over gRPC. + + Creates a schema. + + Returns: + Callable[[~.CreateSchemaRequest], + Awaitable[~.Schema]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_schema" not in self._stubs: + self._stubs["create_schema"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.SchemaService/CreateSchema", + request_serializer=gp_schema.CreateSchemaRequest.serialize, + response_deserializer=gp_schema.Schema.deserialize, + ) + return self._stubs["create_schema"] + + @property + def get_schema( + self, + ) -> Callable[[schema.GetSchemaRequest], Awaitable[schema.Schema]]: + r"""Return a callable for the get schema method over gRPC. + + Gets a schema. + + Returns: + Callable[[~.GetSchemaRequest], + Awaitable[~.Schema]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_schema" not in self._stubs: + self._stubs["get_schema"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.SchemaService/GetSchema", + request_serializer=schema.GetSchemaRequest.serialize, + response_deserializer=schema.Schema.deserialize, + ) + return self._stubs["get_schema"] + + @property + def list_schemas( + self, + ) -> Callable[[schema.ListSchemasRequest], Awaitable[schema.ListSchemasResponse]]: + r"""Return a callable for the list schemas method over gRPC. + + Lists schemas in a project. + + Returns: + Callable[[~.ListSchemasRequest], + Awaitable[~.ListSchemasResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_schemas" not in self._stubs: + self._stubs["list_schemas"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.SchemaService/ListSchemas", + request_serializer=schema.ListSchemasRequest.serialize, + response_deserializer=schema.ListSchemasResponse.deserialize, + ) + return self._stubs["list_schemas"] + + @property + def list_schema_revisions( + self, + ) -> Callable[ + [schema.ListSchemaRevisionsRequest], + Awaitable[schema.ListSchemaRevisionsResponse], + ]: + r"""Return a callable for the list schema revisions method over gRPC. + + Lists all schema revisions for the named schema. + + Returns: + Callable[[~.ListSchemaRevisionsRequest], + Awaitable[~.ListSchemaRevisionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_schema_revisions" not in self._stubs: + self._stubs["list_schema_revisions"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.SchemaService/ListSchemaRevisions", + request_serializer=schema.ListSchemaRevisionsRequest.serialize, + response_deserializer=schema.ListSchemaRevisionsResponse.deserialize, + ) + return self._stubs["list_schema_revisions"] + + @property + def commit_schema( + self, + ) -> Callable[[gp_schema.CommitSchemaRequest], Awaitable[gp_schema.Schema]]: + r"""Return a callable for the commit schema method over gRPC. + + Commits a new schema revision to an existing schema. + + Returns: + Callable[[~.CommitSchemaRequest], + Awaitable[~.Schema]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "commit_schema" not in self._stubs: + self._stubs["commit_schema"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.SchemaService/CommitSchema", + request_serializer=gp_schema.CommitSchemaRequest.serialize, + response_deserializer=gp_schema.Schema.deserialize, + ) + return self._stubs["commit_schema"] + + @property + def rollback_schema( + self, + ) -> Callable[[schema.RollbackSchemaRequest], Awaitable[schema.Schema]]: + r"""Return a callable for the rollback schema method over gRPC. + + Creates a new schema revision that is a copy of the provided + revision_id. + + Returns: + Callable[[~.RollbackSchemaRequest], + Awaitable[~.Schema]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "rollback_schema" not in self._stubs: + self._stubs["rollback_schema"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.SchemaService/RollbackSchema", + request_serializer=schema.RollbackSchemaRequest.serialize, + response_deserializer=schema.Schema.deserialize, + ) + return self._stubs["rollback_schema"] + + @property + def delete_schema_revision( + self, + ) -> Callable[[schema.DeleteSchemaRevisionRequest], Awaitable[schema.Schema]]: + r"""Return a callable for the delete schema revision method over gRPC. + + Deletes a specific schema revision. + + Returns: + Callable[[~.DeleteSchemaRevisionRequest], + Awaitable[~.Schema]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_schema_revision" not in self._stubs: + self._stubs["delete_schema_revision"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.SchemaService/DeleteSchemaRevision", + request_serializer=schema.DeleteSchemaRevisionRequest.serialize, + response_deserializer=schema.Schema.deserialize, + ) + return self._stubs["delete_schema_revision"] + + @property + def delete_schema( + self, + ) -> Callable[[schema.DeleteSchemaRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete schema method over gRPC. + + Deletes a schema. + + Returns: + Callable[[~.DeleteSchemaRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_schema" not in self._stubs: + self._stubs["delete_schema"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.SchemaService/DeleteSchema", + request_serializer=schema.DeleteSchemaRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_schema"] + + @property + def validate_schema( + self, + ) -> Callable[ + [gp_schema.ValidateSchemaRequest], Awaitable[gp_schema.ValidateSchemaResponse] + ]: + r"""Return a callable for the validate schema method over gRPC. + + Validates a schema. + + Returns: + Callable[[~.ValidateSchemaRequest], + Awaitable[~.ValidateSchemaResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "validate_schema" not in self._stubs: + self._stubs["validate_schema"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.SchemaService/ValidateSchema", + request_serializer=gp_schema.ValidateSchemaRequest.serialize, + response_deserializer=gp_schema.ValidateSchemaResponse.deserialize, + ) + return self._stubs["validate_schema"] + + @property + def validate_message( + self, + ) -> Callable[ + [schema.ValidateMessageRequest], Awaitable[schema.ValidateMessageResponse] + ]: + r"""Return a callable for the validate message method over gRPC. + + Validates a message against a schema. + + Returns: + Callable[[~.ValidateMessageRequest], + Awaitable[~.ValidateMessageResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "validate_message" not in self._stubs: + self._stubs["validate_message"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.SchemaService/ValidateMessage", + request_serializer=schema.ValidateMessageRequest.serialize, + response_deserializer=schema.ValidateMessageResponse.deserialize, + ) + return self._stubs["validate_message"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.create_schema: self._wrap_method( + self.create_schema, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_schema: self._wrap_method( + self.get_schema, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_schemas: self._wrap_method( + self.list_schemas, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_schema_revisions: self._wrap_method( + self.list_schema_revisions, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.commit_schema: self._wrap_method( + self.commit_schema, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.rollback_schema: self._wrap_method( + self.rollback_schema, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_schema_revision: self._wrap_method( + self.delete_schema_revision, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_schema: self._wrap_method( + self.delete_schema, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.validate_schema: self._wrap_method( + self.validate_schema, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.validate_message: self._wrap_method( + self.validate_message, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_iam_policy: self._wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: self._wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: self._wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ("SchemaServiceGrpcAsyncIOTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/schema_service/transports/rest.py b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/schema_service/transports/rest.py new file mode 100644 index 0000000000000000000000000000000000000000..b9c1e03620c18e558422d8dc9fae59949cfee7f1 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/schema_service/transports/rest.py @@ -0,0 +1,2715 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed 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. +# +import dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.pubsub_v1.types import schema +from google.pubsub_v1.types import schema as gp_schema + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseSchemaServiceRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class SchemaServiceRestInterceptor: + """Interceptor for SchemaService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the SchemaServiceRestTransport. + + .. code-block:: python + class MyCustomSchemaServiceInterceptor(SchemaServiceRestInterceptor): + def pre_commit_schema(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_commit_schema(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_schema(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_schema(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_schema(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_schema_revision(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_schema_revision(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_schema(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_schema(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_schema_revisions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_schema_revisions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_schemas(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_schemas(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_rollback_schema(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_rollback_schema(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_validate_message(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_validate_message(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_validate_schema(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_validate_schema(self, response): + logging.log(f"Received response: {response}") + return response + + transport = SchemaServiceRestTransport(interceptor=MyCustomSchemaServiceInterceptor()) + client = SchemaServiceClient(transport=transport) + + + """ + + def pre_commit_schema( + self, + request: gp_schema.CommitSchemaRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gp_schema.CommitSchemaRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for commit_schema + + Override in a subclass to manipulate the request or metadata + before they are sent to the SchemaService server. + """ + return request, metadata + + def post_commit_schema(self, response: gp_schema.Schema) -> gp_schema.Schema: + """Post-rpc interceptor for commit_schema + + DEPRECATED. Please use the `post_commit_schema_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SchemaService server but before + it is returned to user code. This `post_commit_schema` interceptor runs + before the `post_commit_schema_with_metadata` interceptor. + """ + return response + + def post_commit_schema_with_metadata( + self, + response: gp_schema.Schema, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gp_schema.Schema, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for commit_schema + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SchemaService server but before it is returned to user code. + + We recommend only using this `post_commit_schema_with_metadata` + interceptor in new development instead of the `post_commit_schema` interceptor. + When both interceptors are used, this `post_commit_schema_with_metadata` interceptor runs after the + `post_commit_schema` interceptor. The (possibly modified) response returned by + `post_commit_schema` will be passed to + `post_commit_schema_with_metadata`. + """ + return response, metadata + + def pre_create_schema( + self, + request: gp_schema.CreateSchemaRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gp_schema.CreateSchemaRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_schema + + Override in a subclass to manipulate the request or metadata + before they are sent to the SchemaService server. + """ + return request, metadata + + def post_create_schema(self, response: gp_schema.Schema) -> gp_schema.Schema: + """Post-rpc interceptor for create_schema + + DEPRECATED. Please use the `post_create_schema_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SchemaService server but before + it is returned to user code. This `post_create_schema` interceptor runs + before the `post_create_schema_with_metadata` interceptor. + """ + return response + + def post_create_schema_with_metadata( + self, + response: gp_schema.Schema, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[gp_schema.Schema, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_schema + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SchemaService server but before it is returned to user code. + + We recommend only using this `post_create_schema_with_metadata` + interceptor in new development instead of the `post_create_schema` interceptor. + When both interceptors are used, this `post_create_schema_with_metadata` interceptor runs after the + `post_create_schema` interceptor. The (possibly modified) response returned by + `post_create_schema` will be passed to + `post_create_schema_with_metadata`. + """ + return response, metadata + + def pre_delete_schema( + self, + request: schema.DeleteSchemaRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[schema.DeleteSchemaRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_schema + + Override in a subclass to manipulate the request or metadata + before they are sent to the SchemaService server. + """ + return request, metadata + + def pre_delete_schema_revision( + self, + request: schema.DeleteSchemaRevisionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + schema.DeleteSchemaRevisionRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_schema_revision + + Override in a subclass to manipulate the request or metadata + before they are sent to the SchemaService server. + """ + return request, metadata + + def post_delete_schema_revision(self, response: schema.Schema) -> schema.Schema: + """Post-rpc interceptor for delete_schema_revision + + DEPRECATED. Please use the `post_delete_schema_revision_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SchemaService server but before + it is returned to user code. This `post_delete_schema_revision` interceptor runs + before the `post_delete_schema_revision_with_metadata` interceptor. + """ + return response + + def post_delete_schema_revision_with_metadata( + self, response: schema.Schema, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[schema.Schema, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_schema_revision + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SchemaService server but before it is returned to user code. + + We recommend only using this `post_delete_schema_revision_with_metadata` + interceptor in new development instead of the `post_delete_schema_revision` interceptor. + When both interceptors are used, this `post_delete_schema_revision_with_metadata` interceptor runs after the + `post_delete_schema_revision` interceptor. The (possibly modified) response returned by + `post_delete_schema_revision` will be passed to + `post_delete_schema_revision_with_metadata`. + """ + return response, metadata + + def pre_get_schema( + self, + request: schema.GetSchemaRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[schema.GetSchemaRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_schema + + Override in a subclass to manipulate the request or metadata + before they are sent to the SchemaService server. + """ + return request, metadata + + def post_get_schema(self, response: schema.Schema) -> schema.Schema: + """Post-rpc interceptor for get_schema + + DEPRECATED. Please use the `post_get_schema_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SchemaService server but before + it is returned to user code. This `post_get_schema` interceptor runs + before the `post_get_schema_with_metadata` interceptor. + """ + return response + + def post_get_schema_with_metadata( + self, response: schema.Schema, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[schema.Schema, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_schema + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SchemaService server but before it is returned to user code. + + We recommend only using this `post_get_schema_with_metadata` + interceptor in new development instead of the `post_get_schema` interceptor. + When both interceptors are used, this `post_get_schema_with_metadata` interceptor runs after the + `post_get_schema` interceptor. The (possibly modified) response returned by + `post_get_schema` will be passed to + `post_get_schema_with_metadata`. + """ + return response, metadata + + def pre_list_schema_revisions( + self, + request: schema.ListSchemaRevisionsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + schema.ListSchemaRevisionsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_schema_revisions + + Override in a subclass to manipulate the request or metadata + before they are sent to the SchemaService server. + """ + return request, metadata + + def post_list_schema_revisions( + self, response: schema.ListSchemaRevisionsResponse + ) -> schema.ListSchemaRevisionsResponse: + """Post-rpc interceptor for list_schema_revisions + + DEPRECATED. Please use the `post_list_schema_revisions_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SchemaService server but before + it is returned to user code. This `post_list_schema_revisions` interceptor runs + before the `post_list_schema_revisions_with_metadata` interceptor. + """ + return response + + def post_list_schema_revisions_with_metadata( + self, + response: schema.ListSchemaRevisionsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + schema.ListSchemaRevisionsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_schema_revisions + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SchemaService server but before it is returned to user code. + + We recommend only using this `post_list_schema_revisions_with_metadata` + interceptor in new development instead of the `post_list_schema_revisions` interceptor. + When both interceptors are used, this `post_list_schema_revisions_with_metadata` interceptor runs after the + `post_list_schema_revisions` interceptor. The (possibly modified) response returned by + `post_list_schema_revisions` will be passed to + `post_list_schema_revisions_with_metadata`. + """ + return response, metadata + + def pre_list_schemas( + self, + request: schema.ListSchemasRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[schema.ListSchemasRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_schemas + + Override in a subclass to manipulate the request or metadata + before they are sent to the SchemaService server. + """ + return request, metadata + + def post_list_schemas( + self, response: schema.ListSchemasResponse + ) -> schema.ListSchemasResponse: + """Post-rpc interceptor for list_schemas + + DEPRECATED. Please use the `post_list_schemas_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SchemaService server but before + it is returned to user code. This `post_list_schemas` interceptor runs + before the `post_list_schemas_with_metadata` interceptor. + """ + return response + + def post_list_schemas_with_metadata( + self, + response: schema.ListSchemasResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[schema.ListSchemasResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_schemas + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SchemaService server but before it is returned to user code. + + We recommend only using this `post_list_schemas_with_metadata` + interceptor in new development instead of the `post_list_schemas` interceptor. + When both interceptors are used, this `post_list_schemas_with_metadata` interceptor runs after the + `post_list_schemas` interceptor. The (possibly modified) response returned by + `post_list_schemas` will be passed to + `post_list_schemas_with_metadata`. + """ + return response, metadata + + def pre_rollback_schema( + self, + request: schema.RollbackSchemaRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[schema.RollbackSchemaRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for rollback_schema + + Override in a subclass to manipulate the request or metadata + before they are sent to the SchemaService server. + """ + return request, metadata + + def post_rollback_schema(self, response: schema.Schema) -> schema.Schema: + """Post-rpc interceptor for rollback_schema + + DEPRECATED. Please use the `post_rollback_schema_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SchemaService server but before + it is returned to user code. This `post_rollback_schema` interceptor runs + before the `post_rollback_schema_with_metadata` interceptor. + """ + return response + + def post_rollback_schema_with_metadata( + self, response: schema.Schema, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[schema.Schema, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for rollback_schema + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SchemaService server but before it is returned to user code. + + We recommend only using this `post_rollback_schema_with_metadata` + interceptor in new development instead of the `post_rollback_schema` interceptor. + When both interceptors are used, this `post_rollback_schema_with_metadata` interceptor runs after the + `post_rollback_schema` interceptor. The (possibly modified) response returned by + `post_rollback_schema` will be passed to + `post_rollback_schema_with_metadata`. + """ + return response, metadata + + def pre_validate_message( + self, + request: schema.ValidateMessageRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[schema.ValidateMessageRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for validate_message + + Override in a subclass to manipulate the request or metadata + before they are sent to the SchemaService server. + """ + return request, metadata + + def post_validate_message( + self, response: schema.ValidateMessageResponse + ) -> schema.ValidateMessageResponse: + """Post-rpc interceptor for validate_message + + DEPRECATED. Please use the `post_validate_message_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SchemaService server but before + it is returned to user code. This `post_validate_message` interceptor runs + before the `post_validate_message_with_metadata` interceptor. + """ + return response + + def post_validate_message_with_metadata( + self, + response: schema.ValidateMessageResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[schema.ValidateMessageResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for validate_message + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SchemaService server but before it is returned to user code. + + We recommend only using this `post_validate_message_with_metadata` + interceptor in new development instead of the `post_validate_message` interceptor. + When both interceptors are used, this `post_validate_message_with_metadata` interceptor runs after the + `post_validate_message` interceptor. The (possibly modified) response returned by + `post_validate_message` will be passed to + `post_validate_message_with_metadata`. + """ + return response, metadata + + def pre_validate_schema( + self, + request: gp_schema.ValidateSchemaRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gp_schema.ValidateSchemaRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for validate_schema + + Override in a subclass to manipulate the request or metadata + before they are sent to the SchemaService server. + """ + return request, metadata + + def post_validate_schema( + self, response: gp_schema.ValidateSchemaResponse + ) -> gp_schema.ValidateSchemaResponse: + """Post-rpc interceptor for validate_schema + + DEPRECATED. Please use the `post_validate_schema_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SchemaService server but before + it is returned to user code. This `post_validate_schema` interceptor runs + before the `post_validate_schema_with_metadata` interceptor. + """ + return response + + def post_validate_schema_with_metadata( + self, + response: gp_schema.ValidateSchemaResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gp_schema.ValidateSchemaResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for validate_schema + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SchemaService server but before it is returned to user code. + + We recommend only using this `post_validate_schema_with_metadata` + interceptor in new development instead of the `post_validate_schema` interceptor. + When both interceptors are used, this `post_validate_schema_with_metadata` interceptor runs after the + `post_validate_schema` interceptor. The (possibly modified) response returned by + `post_validate_schema` will be passed to + `post_validate_schema_with_metadata`. + """ + return response, metadata + + def pre_get_iam_policy( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the SchemaService server. + """ + return request, metadata + + def post_get_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the SchemaService server but before + it is returned to user code. + """ + return response + + def pre_set_iam_policy( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the SchemaService server. + """ + return request, metadata + + def post_set_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the SchemaService server but before + it is returned to user code. + """ + return response + + def pre_test_iam_permissions( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.TestIamPermissionsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the SchemaService server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsResponse + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the SchemaService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class SchemaServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: SchemaServiceRestInterceptor + + +class SchemaServiceRestTransport(_BaseSchemaServiceRestTransport): + """REST backend synchronous transport for SchemaService. + + Service for doing schema-related operations. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "pubsub.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[SchemaServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'pubsub.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[SchemaServiceRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or SchemaServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CommitSchema( + _BaseSchemaServiceRestTransport._BaseCommitSchema, SchemaServiceRestStub + ): + def __hash__(self): + return hash("SchemaServiceRestTransport.CommitSchema") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: gp_schema.CommitSchemaRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gp_schema.Schema: + r"""Call the commit schema method over HTTP. + + Args: + request (~.gp_schema.CommitSchemaRequest): + The request object. Request for CommitSchema method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gp_schema.Schema: + A schema resource. + """ + + http_options = ( + _BaseSchemaServiceRestTransport._BaseCommitSchema._get_http_options() + ) + + request, metadata = self._interceptor.pre_commit_schema(request, metadata) + transcoded_request = _BaseSchemaServiceRestTransport._BaseCommitSchema._get_transcoded_request( + http_options, request + ) + + body = _BaseSchemaServiceRestTransport._BaseCommitSchema._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSchemaServiceRestTransport._BaseCommitSchema._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.SchemaServiceClient.CommitSchema", + extra={ + "serviceName": "google.pubsub.v1.SchemaService", + "rpcName": "CommitSchema", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SchemaServiceRestTransport._CommitSchema._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gp_schema.Schema() + pb_resp = gp_schema.Schema.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_commit_schema(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_commit_schema_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gp_schema.Schema.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.pubsub_v1.SchemaServiceClient.commit_schema", + extra={ + "serviceName": "google.pubsub.v1.SchemaService", + "rpcName": "CommitSchema", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateSchema( + _BaseSchemaServiceRestTransport._BaseCreateSchema, SchemaServiceRestStub + ): + def __hash__(self): + return hash("SchemaServiceRestTransport.CreateSchema") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: gp_schema.CreateSchemaRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gp_schema.Schema: + r"""Call the create schema method over HTTP. + + Args: + request (~.gp_schema.CreateSchemaRequest): + The request object. Request for the CreateSchema method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gp_schema.Schema: + A schema resource. + """ + + http_options = ( + _BaseSchemaServiceRestTransport._BaseCreateSchema._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_schema(request, metadata) + transcoded_request = _BaseSchemaServiceRestTransport._BaseCreateSchema._get_transcoded_request( + http_options, request + ) + + body = _BaseSchemaServiceRestTransport._BaseCreateSchema._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSchemaServiceRestTransport._BaseCreateSchema._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.SchemaServiceClient.CreateSchema", + extra={ + "serviceName": "google.pubsub.v1.SchemaService", + "rpcName": "CreateSchema", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SchemaServiceRestTransport._CreateSchema._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gp_schema.Schema() + pb_resp = gp_schema.Schema.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_schema(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_schema_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gp_schema.Schema.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.pubsub_v1.SchemaServiceClient.create_schema", + extra={ + "serviceName": "google.pubsub.v1.SchemaService", + "rpcName": "CreateSchema", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteSchema( + _BaseSchemaServiceRestTransport._BaseDeleteSchema, SchemaServiceRestStub + ): + def __hash__(self): + return hash("SchemaServiceRestTransport.DeleteSchema") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: schema.DeleteSchemaRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete schema method over HTTP. + + Args: + request (~.schema.DeleteSchemaRequest): + The request object. Request for the ``DeleteSchema`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseSchemaServiceRestTransport._BaseDeleteSchema._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_schema(request, metadata) + transcoded_request = _BaseSchemaServiceRestTransport._BaseDeleteSchema._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSchemaServiceRestTransport._BaseDeleteSchema._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.SchemaServiceClient.DeleteSchema", + extra={ + "serviceName": "google.pubsub.v1.SchemaService", + "rpcName": "DeleteSchema", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SchemaServiceRestTransport._DeleteSchema._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteSchemaRevision( + _BaseSchemaServiceRestTransport._BaseDeleteSchemaRevision, SchemaServiceRestStub + ): + def __hash__(self): + return hash("SchemaServiceRestTransport.DeleteSchemaRevision") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: schema.DeleteSchemaRevisionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> schema.Schema: + r"""Call the delete schema revision method over HTTP. + + Args: + request (~.schema.DeleteSchemaRevisionRequest): + The request object. Request for the ``DeleteSchemaRevision`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.schema.Schema: + A schema resource. + """ + + http_options = _BaseSchemaServiceRestTransport._BaseDeleteSchemaRevision._get_http_options() + + request, metadata = self._interceptor.pre_delete_schema_revision( + request, metadata + ) + transcoded_request = _BaseSchemaServiceRestTransport._BaseDeleteSchemaRevision._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSchemaServiceRestTransport._BaseDeleteSchemaRevision._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.SchemaServiceClient.DeleteSchemaRevision", + extra={ + "serviceName": "google.pubsub.v1.SchemaService", + "rpcName": "DeleteSchemaRevision", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SchemaServiceRestTransport._DeleteSchemaRevision._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = schema.Schema() + pb_resp = schema.Schema.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_schema_revision(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_schema_revision_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = schema.Schema.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.pubsub_v1.SchemaServiceClient.delete_schema_revision", + extra={ + "serviceName": "google.pubsub.v1.SchemaService", + "rpcName": "DeleteSchemaRevision", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetSchema( + _BaseSchemaServiceRestTransport._BaseGetSchema, SchemaServiceRestStub + ): + def __hash__(self): + return hash("SchemaServiceRestTransport.GetSchema") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: schema.GetSchemaRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> schema.Schema: + r"""Call the get schema method over HTTP. + + Args: + request (~.schema.GetSchemaRequest): + The request object. Request for the GetSchema method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.schema.Schema: + A schema resource. + """ + + http_options = ( + _BaseSchemaServiceRestTransport._BaseGetSchema._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_schema(request, metadata) + transcoded_request = ( + _BaseSchemaServiceRestTransport._BaseGetSchema._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSchemaServiceRestTransport._BaseGetSchema._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.SchemaServiceClient.GetSchema", + extra={ + "serviceName": "google.pubsub.v1.SchemaService", + "rpcName": "GetSchema", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SchemaServiceRestTransport._GetSchema._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = schema.Schema() + pb_resp = schema.Schema.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_schema(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_schema_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = schema.Schema.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.pubsub_v1.SchemaServiceClient.get_schema", + extra={ + "serviceName": "google.pubsub.v1.SchemaService", + "rpcName": "GetSchema", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListSchemaRevisions( + _BaseSchemaServiceRestTransport._BaseListSchemaRevisions, SchemaServiceRestStub + ): + def __hash__(self): + return hash("SchemaServiceRestTransport.ListSchemaRevisions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: schema.ListSchemaRevisionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> schema.ListSchemaRevisionsResponse: + r"""Call the list schema revisions method over HTTP. + + Args: + request (~.schema.ListSchemaRevisionsRequest): + The request object. Request for the ``ListSchemaRevisions`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.schema.ListSchemaRevisionsResponse: + Response for the ``ListSchemaRevisions`` method. + """ + + http_options = _BaseSchemaServiceRestTransport._BaseListSchemaRevisions._get_http_options() + + request, metadata = self._interceptor.pre_list_schema_revisions( + request, metadata + ) + transcoded_request = _BaseSchemaServiceRestTransport._BaseListSchemaRevisions._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSchemaServiceRestTransport._BaseListSchemaRevisions._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.SchemaServiceClient.ListSchemaRevisions", + extra={ + "serviceName": "google.pubsub.v1.SchemaService", + "rpcName": "ListSchemaRevisions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SchemaServiceRestTransport._ListSchemaRevisions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = schema.ListSchemaRevisionsResponse() + pb_resp = schema.ListSchemaRevisionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_schema_revisions(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_schema_revisions_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = schema.ListSchemaRevisionsResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.pubsub_v1.SchemaServiceClient.list_schema_revisions", + extra={ + "serviceName": "google.pubsub.v1.SchemaService", + "rpcName": "ListSchemaRevisions", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListSchemas( + _BaseSchemaServiceRestTransport._BaseListSchemas, SchemaServiceRestStub + ): + def __hash__(self): + return hash("SchemaServiceRestTransport.ListSchemas") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: schema.ListSchemasRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> schema.ListSchemasResponse: + r"""Call the list schemas method over HTTP. + + Args: + request (~.schema.ListSchemasRequest): + The request object. Request for the ``ListSchemas`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.schema.ListSchemasResponse: + Response for the ``ListSchemas`` method. + """ + + http_options = ( + _BaseSchemaServiceRestTransport._BaseListSchemas._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_schemas(request, metadata) + transcoded_request = _BaseSchemaServiceRestTransport._BaseListSchemas._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = ( + _BaseSchemaServiceRestTransport._BaseListSchemas._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.SchemaServiceClient.ListSchemas", + extra={ + "serviceName": "google.pubsub.v1.SchemaService", + "rpcName": "ListSchemas", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SchemaServiceRestTransport._ListSchemas._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = schema.ListSchemasResponse() + pb_resp = schema.ListSchemasResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_schemas(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_schemas_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = schema.ListSchemasResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.pubsub_v1.SchemaServiceClient.list_schemas", + extra={ + "serviceName": "google.pubsub.v1.SchemaService", + "rpcName": "ListSchemas", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _RollbackSchema( + _BaseSchemaServiceRestTransport._BaseRollbackSchema, SchemaServiceRestStub + ): + def __hash__(self): + return hash("SchemaServiceRestTransport.RollbackSchema") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: schema.RollbackSchemaRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> schema.Schema: + r"""Call the rollback schema method over HTTP. + + Args: + request (~.schema.RollbackSchemaRequest): + The request object. Request for the ``RollbackSchema`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.schema.Schema: + A schema resource. + """ + + http_options = ( + _BaseSchemaServiceRestTransport._BaseRollbackSchema._get_http_options() + ) + + request, metadata = self._interceptor.pre_rollback_schema(request, metadata) + transcoded_request = _BaseSchemaServiceRestTransport._BaseRollbackSchema._get_transcoded_request( + http_options, request + ) + + body = _BaseSchemaServiceRestTransport._BaseRollbackSchema._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSchemaServiceRestTransport._BaseRollbackSchema._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.SchemaServiceClient.RollbackSchema", + extra={ + "serviceName": "google.pubsub.v1.SchemaService", + "rpcName": "RollbackSchema", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SchemaServiceRestTransport._RollbackSchema._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = schema.Schema() + pb_resp = schema.Schema.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_rollback_schema(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_rollback_schema_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = schema.Schema.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.pubsub_v1.SchemaServiceClient.rollback_schema", + extra={ + "serviceName": "google.pubsub.v1.SchemaService", + "rpcName": "RollbackSchema", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ValidateMessage( + _BaseSchemaServiceRestTransport._BaseValidateMessage, SchemaServiceRestStub + ): + def __hash__(self): + return hash("SchemaServiceRestTransport.ValidateMessage") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: schema.ValidateMessageRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> schema.ValidateMessageResponse: + r"""Call the validate message method over HTTP. + + Args: + request (~.schema.ValidateMessageRequest): + The request object. Request for the ``ValidateMessage`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.schema.ValidateMessageResponse: + Response for the ``ValidateMessage`` method. Empty for + now. + + """ + + http_options = ( + _BaseSchemaServiceRestTransport._BaseValidateMessage._get_http_options() + ) + + request, metadata = self._interceptor.pre_validate_message( + request, metadata + ) + transcoded_request = _BaseSchemaServiceRestTransport._BaseValidateMessage._get_transcoded_request( + http_options, request + ) + + body = _BaseSchemaServiceRestTransport._BaseValidateMessage._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSchemaServiceRestTransport._BaseValidateMessage._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.SchemaServiceClient.ValidateMessage", + extra={ + "serviceName": "google.pubsub.v1.SchemaService", + "rpcName": "ValidateMessage", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SchemaServiceRestTransport._ValidateMessage._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = schema.ValidateMessageResponse() + pb_resp = schema.ValidateMessageResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_validate_message(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_validate_message_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = schema.ValidateMessageResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.pubsub_v1.SchemaServiceClient.validate_message", + extra={ + "serviceName": "google.pubsub.v1.SchemaService", + "rpcName": "ValidateMessage", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ValidateSchema( + _BaseSchemaServiceRestTransport._BaseValidateSchema, SchemaServiceRestStub + ): + def __hash__(self): + return hash("SchemaServiceRestTransport.ValidateSchema") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: gp_schema.ValidateSchemaRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gp_schema.ValidateSchemaResponse: + r"""Call the validate schema method over HTTP. + + Args: + request (~.gp_schema.ValidateSchemaRequest): + The request object. Request for the ``ValidateSchema`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.gp_schema.ValidateSchemaResponse: + Response for the ``ValidateSchema`` method. Empty for + now. + + """ + + http_options = ( + _BaseSchemaServiceRestTransport._BaseValidateSchema._get_http_options() + ) + + request, metadata = self._interceptor.pre_validate_schema(request, metadata) + transcoded_request = _BaseSchemaServiceRestTransport._BaseValidateSchema._get_transcoded_request( + http_options, request + ) + + body = _BaseSchemaServiceRestTransport._BaseValidateSchema._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSchemaServiceRestTransport._BaseValidateSchema._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.SchemaServiceClient.ValidateSchema", + extra={ + "serviceName": "google.pubsub.v1.SchemaService", + "rpcName": "ValidateSchema", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SchemaServiceRestTransport._ValidateSchema._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = gp_schema.ValidateSchemaResponse() + pb_resp = gp_schema.ValidateSchemaResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_validate_schema(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_validate_schema_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = gp_schema.ValidateSchemaResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.pubsub_v1.SchemaServiceClient.validate_schema", + extra={ + "serviceName": "google.pubsub.v1.SchemaService", + "rpcName": "ValidateSchema", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def commit_schema( + self, + ) -> Callable[[gp_schema.CommitSchemaRequest], gp_schema.Schema]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CommitSchema(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_schema( + self, + ) -> Callable[[gp_schema.CreateSchemaRequest], gp_schema.Schema]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateSchema(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_schema(self) -> Callable[[schema.DeleteSchemaRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteSchema(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_schema_revision( + self, + ) -> Callable[[schema.DeleteSchemaRevisionRequest], schema.Schema]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteSchemaRevision(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_schema(self) -> Callable[[schema.GetSchemaRequest], schema.Schema]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetSchema(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_schema_revisions( + self, + ) -> Callable[ + [schema.ListSchemaRevisionsRequest], schema.ListSchemaRevisionsResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListSchemaRevisions(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_schemas( + self, + ) -> Callable[[schema.ListSchemasRequest], schema.ListSchemasResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListSchemas(self._session, self._host, self._interceptor) # type: ignore + + @property + def rollback_schema( + self, + ) -> Callable[[schema.RollbackSchemaRequest], schema.Schema]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RollbackSchema(self._session, self._host, self._interceptor) # type: ignore + + @property + def validate_message( + self, + ) -> Callable[[schema.ValidateMessageRequest], schema.ValidateMessageResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ValidateMessage(self._session, self._host, self._interceptor) # type: ignore + + @property + def validate_schema( + self, + ) -> Callable[[gp_schema.ValidateSchemaRequest], gp_schema.ValidateSchemaResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ValidateSchema(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy( + _BaseSchemaServiceRestTransport._BaseGetIamPolicy, SchemaServiceRestStub + ): + def __hash__(self): + return hash("SchemaServiceRestTransport.GetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options = ( + _BaseSchemaServiceRestTransport._BaseGetIamPolicy._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + transcoded_request = _BaseSchemaServiceRestTransport._BaseGetIamPolicy._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSchemaServiceRestTransport._BaseGetIamPolicy._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.SchemaServiceClient.GetIamPolicy", + extra={ + "serviceName": "google.pubsub.v1.SchemaService", + "rpcName": "GetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SchemaServiceRestTransport._GetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.pubsub_v1.SchemaServiceAsyncClient.GetIamPolicy", + extra={ + "serviceName": "google.pubsub.v1.SchemaService", + "rpcName": "GetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy( + _BaseSchemaServiceRestTransport._BaseSetIamPolicy, SchemaServiceRestStub + ): + def __hash__(self): + return hash("SchemaServiceRestTransport.SetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options = ( + _BaseSchemaServiceRestTransport._BaseSetIamPolicy._get_http_options() + ) + + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + transcoded_request = _BaseSchemaServiceRestTransport._BaseSetIamPolicy._get_transcoded_request( + http_options, request + ) + + body = _BaseSchemaServiceRestTransport._BaseSetIamPolicy._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSchemaServiceRestTransport._BaseSetIamPolicy._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.SchemaServiceClient.SetIamPolicy", + extra={ + "serviceName": "google.pubsub.v1.SchemaService", + "rpcName": "SetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SchemaServiceRestTransport._SetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_set_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.pubsub_v1.SchemaServiceAsyncClient.SetIamPolicy", + extra={ + "serviceName": "google.pubsub.v1.SchemaService", + "rpcName": "SetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions( + _BaseSchemaServiceRestTransport._BaseTestIamPermissions, SchemaServiceRestStub + ): + def __hash__(self): + return hash("SchemaServiceRestTransport.TestIamPermissions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options = _BaseSchemaServiceRestTransport._BaseTestIamPermissions._get_http_options() + + request, metadata = self._interceptor.pre_test_iam_permissions( + request, metadata + ) + transcoded_request = _BaseSchemaServiceRestTransport._BaseTestIamPermissions._get_transcoded_request( + http_options, request + ) + + body = _BaseSchemaServiceRestTransport._BaseTestIamPermissions._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSchemaServiceRestTransport._BaseTestIamPermissions._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.SchemaServiceClient.TestIamPermissions", + extra={ + "serviceName": "google.pubsub.v1.SchemaService", + "rpcName": "TestIamPermissions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SchemaServiceRestTransport._TestIamPermissions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_test_iam_permissions(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.pubsub_v1.SchemaServiceAsyncClient.TestIamPermissions", + extra={ + "serviceName": "google.pubsub.v1.SchemaService", + "rpcName": "TestIamPermissions", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("SchemaServiceRestTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/schema_service/transports/rest_base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/schema_service/transports/rest_base.py new file mode 100644 index 0000000000000000000000000000000000000000..a8bca0a7276aa8bae67a99909c7bc6f45d177ea2 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/schema_service/transports/rest_base.py @@ -0,0 +1,746 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed 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. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.api_core import gapic_v1, path_template +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.protobuf import json_format + +from google.pubsub_v1.types import schema +from google.pubsub_v1.types import schema as gp_schema + +from .base import DEFAULT_CLIENT_INFO, SchemaServiceTransport + + +class _BaseSchemaServiceRestTransport(SchemaServiceTransport): + """Base REST backend transport for SchemaService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "pubsub.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'pubsub.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseCommitSchema: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/schemas/*}:commit", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gp_schema.CommitSchemaRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSchemaServiceRestTransport._BaseCommitSchema._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateSchema: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*}/schemas", + "body": "schema", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gp_schema.CreateSchemaRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSchemaServiceRestTransport._BaseCreateSchema._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteSchema: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/schemas/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = schema.DeleteSchemaRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSchemaServiceRestTransport._BaseDeleteSchema._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteSchemaRevision: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/schemas/*}:deleteRevision", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = schema.DeleteSchemaRevisionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSchemaServiceRestTransport._BaseDeleteSchemaRevision._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetSchema: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/schemas/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = schema.GetSchemaRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSchemaServiceRestTransport._BaseGetSchema._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListSchemaRevisions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/schemas/*}:listRevisions", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = schema.ListSchemaRevisionsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSchemaServiceRestTransport._BaseListSchemaRevisions._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListSchemas: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*}/schemas", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = schema.ListSchemasRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSchemaServiceRestTransport._BaseListSchemas._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRollbackSchema: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/schemas/*}:rollback", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = schema.RollbackSchemaRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSchemaServiceRestTransport._BaseRollbackSchema._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseValidateMessage: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*}/schemas:validateMessage", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = schema.ValidateMessageRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSchemaServiceRestTransport._BaseValidateMessage._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseValidateSchema: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*}/schemas:validate", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = gp_schema.ValidateSchemaRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSchemaServiceRestTransport._BaseValidateSchema._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{resource=projects/*/topics/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/subscriptions/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/snapshots/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/schemas/*}:getIamPolicy", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseSetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{resource=projects/*/topics/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/subscriptions/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/snapshots/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/schemas/*}:setIamPolicy", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseTestIamPermissions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{resource=projects/*/subscriptions/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/topics/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/snapshots/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/schemas/*}:testIamPermissions", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseSchemaServiceRestTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/subscriber/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/subscriber/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..25cd7a426c410fcd56611b33b78d7049ffc64241 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/subscriber/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed 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. +# +from .async_client import SubscriberAsyncClient +from .client import SubscriberClient + +__all__ = ( + "SubscriberClient", + "SubscriberAsyncClient", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/subscriber/async_client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/subscriber/async_client.py new file mode 100644 index 0000000000000000000000000000000000000000..c63c9ecdbec6765ab2f7f56ea216463297b8d480 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/subscriber/async_client.py @@ -0,0 +1,2672 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed 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. +# +import logging as std_logging +import warnings +import re +from collections import OrderedDict +from typing import ( + AsyncIterable, + AsyncIterator, + Awaitable, + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +import google.protobuf +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.pubsub_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) + +from google.pubsub_v1.services.subscriber import pagers +from google.pubsub_v1.types import pubsub + +from .client import SubscriberClient +from .transports.base import DEFAULT_CLIENT_INFO, SubscriberTransport +from .transports.grpc_asyncio import SubscriberGrpcAsyncIOTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class SubscriberAsyncClient: + """The service that an application uses to manipulate subscriptions and + to consume messages from a subscription via the ``Pull`` method or + by establishing a bi-directional stream using the ``StreamingPull`` + method. + """ + + _client: SubscriberClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = SubscriberClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SubscriberClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = SubscriberClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = SubscriberClient._DEFAULT_UNIVERSE + + listing_path = staticmethod(SubscriberClient.listing_path) + parse_listing_path = staticmethod(SubscriberClient.parse_listing_path) + snapshot_path = staticmethod(SubscriberClient.snapshot_path) + parse_snapshot_path = staticmethod(SubscriberClient.parse_snapshot_path) + subscription_path = staticmethod(SubscriberClient.subscription_path) + parse_subscription_path = staticmethod(SubscriberClient.parse_subscription_path) + topic_path = staticmethod(SubscriberClient.topic_path) + parse_topic_path = staticmethod(SubscriberClient.parse_topic_path) + common_billing_account_path = staticmethod( + SubscriberClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + SubscriberClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(SubscriberClient.common_folder_path) + parse_common_folder_path = staticmethod(SubscriberClient.parse_common_folder_path) + common_organization_path = staticmethod(SubscriberClient.common_organization_path) + parse_common_organization_path = staticmethod( + SubscriberClient.parse_common_organization_path + ) + common_project_path = staticmethod(SubscriberClient.common_project_path) + parse_common_project_path = staticmethod(SubscriberClient.parse_common_project_path) + common_location_path = staticmethod(SubscriberClient.common_location_path) + parse_common_location_path = staticmethod( + SubscriberClient.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SubscriberAsyncClient: The constructed client. + """ + sa_info_func = ( + SubscriberClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(SubscriberAsyncClient, info, *args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SubscriberAsyncClient: The constructed client. + """ + sa_file_func = ( + SubscriberClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(SubscriberAsyncClient, filename, *args, **kwargs) + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return SubscriberClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> SubscriberTransport: + """Returns the transport used by the client instance. + + Returns: + SubscriberTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = SubscriberClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, SubscriberTransport, Callable[..., SubscriberTransport]] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the subscriber async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,SubscriberTransport,Callable[..., SubscriberTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the SubscriberTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = SubscriberClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.pubsub_v1.SubscriberAsyncClient`.", + extra={ + "serviceName": "google.pubsub.v1.Subscriber", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.pubsub.v1.Subscriber", + "credentialsType": None, + }, + ) + + async def create_subscription( + self, + request: Optional[Union[pubsub.Subscription, dict]] = None, + *, + name: Optional[str] = None, + topic: Optional[str] = None, + push_config: Optional[pubsub.PushConfig] = None, + ack_deadline_seconds: Optional[int] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.Subscription: + r"""Creates a subscription to a given topic. See the [resource name + rules] + (https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names). + If the subscription already exists, returns ``ALREADY_EXISTS``. + If the corresponding topic doesn't exist, returns ``NOT_FOUND``. + + If the name is not provided in the request, the server will + assign a random name for this subscription on the same project + as the topic, conforming to the [resource name format] + (https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names). + The generated name is populated in the returned Subscription + object. Note that for REST API requests, you must specify a name + in the request. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + async def sample_create_subscription(): + # Create a client + client = pubsub_v1.SubscriberAsyncClient() + + # Initialize request argument(s) + request = pubsub_v1.Subscription( + name="name_value", + topic="topic_value", + ) + + # Make the request + response = await client.create_subscription(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.pubsub_v1.types.Subscription, dict]]): + The request object. A subscription resource. If none of ``push_config``, + ``bigquery_config``, or ``cloud_storage_config`` is set, + then the subscriber will pull and ack messages using API + methods. At most one of these fields may be set. + name (:class:`str`): + Required. Identifier. The name of the subscription. It + must have the format + ``"projects/{project}/subscriptions/{subscription}"``. + ``{subscription}`` must start with a letter, and contain + only letters (``[A-Za-z]``), numbers (``[0-9]``), dashes + (``-``), underscores (``_``), periods (``.``), tildes + (``~``), plus (``+``) or percent signs (``%``). It must + be between 3 and 255 characters in length, and it must + not start with ``"goog"``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + topic (:class:`str`): + Required. The name of the topic from which this + subscription is receiving messages. Format is + ``projects/{project}/topics/{topic}``. The value of this + field will be ``_deleted-topic_`` if the topic has been + deleted. + + This corresponds to the ``topic`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + push_config (:class:`google.pubsub_v1.types.PushConfig`): + Optional. If push delivery is used + with this subscription, this field is + used to configure it. + + This corresponds to the ``push_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ack_deadline_seconds (:class:`int`): + Optional. The approximate amount of time (on a + best-effort basis) Pub/Sub waits for the subscriber to + acknowledge receipt before resending the message. In the + interval after the message is delivered and before it is + acknowledged, it is considered to be *outstanding*. + During that time period, the message will not be + redelivered (on a best-effort basis). + + For pull subscriptions, this value is used as the + initial value for the ack deadline. To override this + value for a given message, call ``ModifyAckDeadline`` + with the corresponding ``ack_id`` if using non-streaming + pull or send the ``ack_id`` in a + ``StreamingModifyAckDeadlineRequest`` if using streaming + pull. The minimum custom deadline you can specify is 10 + seconds. The maximum custom deadline you can specify is + 600 seconds (10 minutes). If this parameter is 0, a + default value of 10 seconds is used. + + For push delivery, this value is also used to set the + request timeout for the call to the push endpoint. + + If the subscriber never acknowledges the message, the + Pub/Sub system will eventually redeliver the message. + + This corresponds to the ``ack_deadline_seconds`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.types.Subscription: + A subscription resource. If none of push_config, bigquery_config, or + cloud_storage_config is set, then the subscriber will + pull and ack messages using API methods. At most one + of these fields may be set. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, topic, push_config, ack_deadline_seconds] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.Subscription): + request = pubsub.Subscription(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if topic is not None: + request.topic = topic + if push_config is not None: + request.push_config = push_config + if ack_deadline_seconds is not None: + request.ack_deadline_seconds = ack_deadline_seconds + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_subscription + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_subscription( + self, + request: Optional[Union[pubsub.GetSubscriptionRequest, dict]] = None, + *, + subscription: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.Subscription: + r"""Gets the configuration details of a subscription. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + async def sample_get_subscription(): + # Create a client + client = pubsub_v1.SubscriberAsyncClient() + + # Initialize request argument(s) + request = pubsub_v1.GetSubscriptionRequest( + subscription="subscription_value", + ) + + # Make the request + response = await client.get_subscription(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.pubsub_v1.types.GetSubscriptionRequest, dict]]): + The request object. Request for the GetSubscription + method. + subscription (:class:`str`): + Required. The name of the subscription to get. Format is + ``projects/{project}/subscriptions/{sub}``. + + This corresponds to the ``subscription`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.types.Subscription: + A subscription resource. If none of push_config, bigquery_config, or + cloud_storage_config is set, then the subscriber will + pull and ack messages using API methods. At most one + of these fields may be set. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [subscription] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.GetSubscriptionRequest): + request = pubsub.GetSubscriptionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if subscription is not None: + request.subscription = subscription + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_subscription + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("subscription", request.subscription),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_subscription( + self, + request: Optional[Union[pubsub.UpdateSubscriptionRequest, dict]] = None, + *, + subscription: Optional[pubsub.Subscription] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.Subscription: + r"""Updates an existing subscription by updating the + fields specified in the update mask. Note that certain + properties of a subscription, such as its topic, are not + modifiable. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + async def sample_update_subscription(): + # Create a client + client = pubsub_v1.SubscriberAsyncClient() + + # Initialize request argument(s) + subscription = pubsub_v1.Subscription() + subscription.name = "name_value" + subscription.topic = "topic_value" + + request = pubsub_v1.UpdateSubscriptionRequest( + subscription=subscription, + ) + + # Make the request + response = await client.update_subscription(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.pubsub_v1.types.UpdateSubscriptionRequest, dict]]): + The request object. Request for the UpdateSubscription + method. + subscription (:class:`google.pubsub_v1.types.Subscription`): + Required. The updated subscription + object. + + This corresponds to the ``subscription`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Indicates which fields in + the provided subscription to update. + Must be specified and non-empty. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.types.Subscription: + A subscription resource. If none of push_config, bigquery_config, or + cloud_storage_config is set, then the subscriber will + pull and ack messages using API methods. At most one + of these fields may be set. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [subscription, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.UpdateSubscriptionRequest): + request = pubsub.UpdateSubscriptionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if subscription is not None: + request.subscription = subscription + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_subscription + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("subscription.name", request.subscription.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_subscriptions( + self, + request: Optional[Union[pubsub.ListSubscriptionsRequest, dict]] = None, + *, + project: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListSubscriptionsAsyncPager: + r"""Lists matching subscriptions. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + async def sample_list_subscriptions(): + # Create a client + client = pubsub_v1.SubscriberAsyncClient() + + # Initialize request argument(s) + request = pubsub_v1.ListSubscriptionsRequest( + project="project_value", + ) + + # Make the request + page_result = client.list_subscriptions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.pubsub_v1.types.ListSubscriptionsRequest, dict]]): + The request object. Request for the ``ListSubscriptions`` method. + project (:class:`str`): + Required. The name of the project in which to list + subscriptions. Format is ``projects/{project-id}``. + + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.services.subscriber.pagers.ListSubscriptionsAsyncPager: + Response for the ListSubscriptions method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [project] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.ListSubscriptionsRequest): + request = pubsub.ListSubscriptionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_subscriptions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("project", request.project),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListSubscriptionsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_subscription( + self, + request: Optional[Union[pubsub.DeleteSubscriptionRequest, dict]] = None, + *, + subscription: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes an existing subscription. All messages retained in the + subscription are immediately dropped. Calls to ``Pull`` after + deletion will return ``NOT_FOUND``. After a subscription is + deleted, a new one may be created with the same name, but the + new one has no association with the old subscription or its + topic unless the same topic is specified. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + async def sample_delete_subscription(): + # Create a client + client = pubsub_v1.SubscriberAsyncClient() + + # Initialize request argument(s) + request = pubsub_v1.DeleteSubscriptionRequest( + subscription="subscription_value", + ) + + # Make the request + await client.delete_subscription(request=request) + + Args: + request (Optional[Union[google.pubsub_v1.types.DeleteSubscriptionRequest, dict]]): + The request object. Request for the DeleteSubscription + method. + subscription (:class:`str`): + Required. The subscription to delete. Format is + ``projects/{project}/subscriptions/{sub}``. + + This corresponds to the ``subscription`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [subscription] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.DeleteSubscriptionRequest): + request = pubsub.DeleteSubscriptionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if subscription is not None: + request.subscription = subscription + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_subscription + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("subscription", request.subscription),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def modify_ack_deadline( + self, + request: Optional[Union[pubsub.ModifyAckDeadlineRequest, dict]] = None, + *, + subscription: Optional[str] = None, + ack_ids: Optional[MutableSequence[str]] = None, + ack_deadline_seconds: Optional[int] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Modifies the ack deadline for a specific message. This method is + useful to indicate that more time is needed to process a message + by the subscriber, or to make the message available for + redelivery if the processing was interrupted. Note that this + does not modify the subscription-level ``ackDeadlineSeconds`` + used for subsequent messages. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + async def sample_modify_ack_deadline(): + # Create a client + client = pubsub_v1.SubscriberAsyncClient() + + # Initialize request argument(s) + request = pubsub_v1.ModifyAckDeadlineRequest( + subscription="subscription_value", + ack_ids=['ack_ids_value1', 'ack_ids_value2'], + ack_deadline_seconds=2066, + ) + + # Make the request + await client.modify_ack_deadline(request=request) + + Args: + request (Optional[Union[google.pubsub_v1.types.ModifyAckDeadlineRequest, dict]]): + The request object. Request for the ModifyAckDeadline + method. + subscription (:class:`str`): + Required. The name of the subscription. Format is + ``projects/{project}/subscriptions/{sub}``. + + This corresponds to the ``subscription`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ack_ids (:class:`MutableSequence[str]`): + Required. List of acknowledgment IDs. + This corresponds to the ``ack_ids`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ack_deadline_seconds (:class:`int`): + Required. The new ack deadline with respect to the time + this request was sent to the Pub/Sub system. For + example, if the value is 10, the new ack deadline will + expire 10 seconds after the ``ModifyAckDeadline`` call + was made. Specifying zero might immediately make the + message available for delivery to another subscriber + client. This typically results in an increase in the + rate of message redeliveries (that is, duplicates). The + minimum deadline you can specify is 0 seconds. The + maximum deadline you can specify in a single request is + 600 seconds (10 minutes). + + This corresponds to the ``ack_deadline_seconds`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [subscription, ack_ids, ack_deadline_seconds] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.ModifyAckDeadlineRequest): + request = pubsub.ModifyAckDeadlineRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if subscription is not None: + request.subscription = subscription + if ack_deadline_seconds is not None: + request.ack_deadline_seconds = ack_deadline_seconds + if ack_ids: + request.ack_ids.extend(ack_ids) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.modify_ack_deadline + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("subscription", request.subscription),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def acknowledge( + self, + request: Optional[Union[pubsub.AcknowledgeRequest, dict]] = None, + *, + subscription: Optional[str] = None, + ack_ids: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Acknowledges the messages associated with the ``ack_ids`` in the + ``AcknowledgeRequest``. The Pub/Sub system can remove the + relevant messages from the subscription. + + Acknowledging a message whose ack deadline has expired may + succeed, but such a message may be redelivered later. + Acknowledging a message more than once will not result in an + error. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + async def sample_acknowledge(): + # Create a client + client = pubsub_v1.SubscriberAsyncClient() + + # Initialize request argument(s) + request = pubsub_v1.AcknowledgeRequest( + subscription="subscription_value", + ack_ids=['ack_ids_value1', 'ack_ids_value2'], + ) + + # Make the request + await client.acknowledge(request=request) + + Args: + request (Optional[Union[google.pubsub_v1.types.AcknowledgeRequest, dict]]): + The request object. Request for the Acknowledge method. + subscription (:class:`str`): + Required. The subscription whose message is being + acknowledged. Format is + ``projects/{project}/subscriptions/{sub}``. + + This corresponds to the ``subscription`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ack_ids (:class:`MutableSequence[str]`): + Required. The acknowledgment ID for the messages being + acknowledged that was returned by the Pub/Sub system in + the ``Pull`` response. Must not be empty. + + This corresponds to the ``ack_ids`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [subscription, ack_ids] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.AcknowledgeRequest): + request = pubsub.AcknowledgeRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if subscription is not None: + request.subscription = subscription + if ack_ids: + request.ack_ids.extend(ack_ids) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.acknowledge + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("subscription", request.subscription),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def pull( + self, + request: Optional[Union[pubsub.PullRequest, dict]] = None, + *, + subscription: Optional[str] = None, + return_immediately: Optional[bool] = None, + max_messages: Optional[int] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.PullResponse: + r"""Pulls messages from the server. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + async def sample_pull(): + # Create a client + client = pubsub_v1.SubscriberAsyncClient() + + # Initialize request argument(s) + request = pubsub_v1.PullRequest( + subscription="subscription_value", + max_messages=1277, + ) + + # Make the request + response = await client.pull(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.pubsub_v1.types.PullRequest, dict]]): + The request object. Request for the ``Pull`` method. + subscription (:class:`str`): + Required. The subscription from which messages should be + pulled. Format is + ``projects/{project}/subscriptions/{sub}``. + + This corresponds to the ``subscription`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + return_immediately (:class:`bool`): + Optional. If this field set to true, the system will + respond immediately even if it there are no messages + available to return in the ``Pull`` response. Otherwise, + the system may wait (for a bounded amount of time) until + at least one message is available, rather than returning + no messages. Warning: setting this field to ``true`` is + discouraged because it adversely impacts the performance + of ``Pull`` operations. We recommend that users do not + set this field. + + This corresponds to the ``return_immediately`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + max_messages (:class:`int`): + Required. The maximum number of + messages to return for this request. + Must be a positive integer. The Pub/Sub + system may return fewer than the number + specified. + + This corresponds to the ``max_messages`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.types.PullResponse: + Response for the Pull method. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [subscription, return_immediately, max_messages] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.PullRequest): + request = pubsub.PullRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if subscription is not None: + request.subscription = subscription + if return_immediately is not None: + request.return_immediately = return_immediately + if max_messages is not None: + request.max_messages = max_messages + + if request.return_immediately: + warnings.warn( + "The return_immediately flag is deprecated and should be set to False.", + category=DeprecationWarning, + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.pull] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("subscription", request.subscription),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def streaming_pull( + self, + requests: Optional[AsyncIterator[pubsub.StreamingPullRequest]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> Awaitable[AsyncIterable[pubsub.StreamingPullResponse]]: + r"""Establishes a stream with the server, which sends messages down + to the client. The client streams acknowledgments and ack + deadline modifications back to the server. The server will close + the stream and return the status on any error. The server may + close the stream with status ``UNAVAILABLE`` to reassign + server-side resources, in which case, the client should + re-establish the stream. Flow control can be achieved by + configuring the underlying RPC channel. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + async def sample_streaming_pull(): + # Create a client + client = pubsub_v1.SubscriberAsyncClient() + + # Initialize request argument(s) + request = pubsub_v1.StreamingPullRequest( + subscription="subscription_value", + stream_ack_deadline_seconds=2813, + ) + + # This method expects an iterator which contains + # 'pubsub_v1.StreamingPullRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = await client.streaming_pull(requests=request_generator()) + + # Handle the response + async for response in stream: + print(response) + + Args: + requests (AsyncIterator[`google.pubsub_v1.types.StreamingPullRequest`]): + The request object AsyncIterator. Request for the ``StreamingPull`` streaming RPC method. + This request is used to establish the initial stream as + well as to stream acknowledgments and ack deadline + modifications from the client to the server. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + AsyncIterable[google.pubsub_v1.types.StreamingPullResponse]: + Response for the StreamingPull method. This response is used to stream + messages from the server to the client. + + """ + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.streaming_pull + ] + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def modify_push_config( + self, + request: Optional[Union[pubsub.ModifyPushConfigRequest, dict]] = None, + *, + subscription: Optional[str] = None, + push_config: Optional[pubsub.PushConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Modifies the ``PushConfig`` for a specified subscription. + + This may be used to change a push subscription to a pull one + (signified by an empty ``PushConfig``) or vice versa, or change + the endpoint URL and other attributes of a push subscription. + Messages will accumulate for delivery continuously through the + call regardless of changes to the ``PushConfig``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + async def sample_modify_push_config(): + # Create a client + client = pubsub_v1.SubscriberAsyncClient() + + # Initialize request argument(s) + request = pubsub_v1.ModifyPushConfigRequest( + subscription="subscription_value", + ) + + # Make the request + await client.modify_push_config(request=request) + + Args: + request (Optional[Union[google.pubsub_v1.types.ModifyPushConfigRequest, dict]]): + The request object. Request for the ModifyPushConfig + method. + subscription (:class:`str`): + Required. The name of the subscription. Format is + ``projects/{project}/subscriptions/{sub}``. + + This corresponds to the ``subscription`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + push_config (:class:`google.pubsub_v1.types.PushConfig`): + Required. The push configuration for future deliveries. + + An empty ``pushConfig`` indicates that the Pub/Sub + system should stop pushing messages from the given + subscription and allow messages to be pulled and + acknowledged - effectively pausing the subscription if + ``Pull`` or ``StreamingPull`` is not called. + + This corresponds to the ``push_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [subscription, push_config] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.ModifyPushConfigRequest): + request = pubsub.ModifyPushConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if subscription is not None: + request.subscription = subscription + if push_config is not None: + request.push_config = push_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.modify_push_config + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("subscription", request.subscription),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_snapshot( + self, + request: Optional[Union[pubsub.GetSnapshotRequest, dict]] = None, + *, + snapshot: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.Snapshot: + r"""Gets the configuration details of a snapshot. Snapshots are used + in + `Seek `__ + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + async def sample_get_snapshot(): + # Create a client + client = pubsub_v1.SubscriberAsyncClient() + + # Initialize request argument(s) + request = pubsub_v1.GetSnapshotRequest( + snapshot="snapshot_value", + ) + + # Make the request + response = await client.get_snapshot(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.pubsub_v1.types.GetSnapshotRequest, dict]]): + The request object. Request for the GetSnapshot method. + snapshot (:class:`str`): + Required. The name of the snapshot to get. Format is + ``projects/{project}/snapshots/{snap}``. + + This corresponds to the ``snapshot`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.types.Snapshot: + A snapshot resource. Snapshots are used in + [Seek](https://cloud.google.com/pubsub/docs/replay-overview) + operations, which allow you to manage message + acknowledgments in bulk. That is, you can set the + acknowledgment state of messages in an existing + subscription to the state captured by a snapshot. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [snapshot] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.GetSnapshotRequest): + request = pubsub.GetSnapshotRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if snapshot is not None: + request.snapshot = snapshot + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_snapshot + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("snapshot", request.snapshot),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_snapshots( + self, + request: Optional[Union[pubsub.ListSnapshotsRequest, dict]] = None, + *, + project: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListSnapshotsAsyncPager: + r"""Lists the existing snapshots. Snapshots are used in + `Seek `__ + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + async def sample_list_snapshots(): + # Create a client + client = pubsub_v1.SubscriberAsyncClient() + + # Initialize request argument(s) + request = pubsub_v1.ListSnapshotsRequest( + project="project_value", + ) + + # Make the request + page_result = client.list_snapshots(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.pubsub_v1.types.ListSnapshotsRequest, dict]]): + The request object. Request for the ``ListSnapshots`` method. + project (:class:`str`): + Required. The name of the project in which to list + snapshots. Format is ``projects/{project-id}``. + + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.services.subscriber.pagers.ListSnapshotsAsyncPager: + Response for the ListSnapshots method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [project] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.ListSnapshotsRequest): + request = pubsub.ListSnapshotsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_snapshots + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("project", request.project),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListSnapshotsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_snapshot( + self, + request: Optional[Union[pubsub.CreateSnapshotRequest, dict]] = None, + *, + name: Optional[str] = None, + subscription: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.Snapshot: + r"""Creates a snapshot from the requested subscription. Snapshots + are used in + `Seek `__ + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + If the snapshot already exists, returns ``ALREADY_EXISTS``. If + the requested subscription doesn't exist, returns ``NOT_FOUND``. + If the backlog in the subscription is too old -- and the + resulting snapshot would expire in less than 1 hour -- then + ``FAILED_PRECONDITION`` is returned. See also the + ``Snapshot.expire_time`` field. If the name is not provided in + the request, the server will assign a random name for this + snapshot on the same project as the subscription, conforming to + the [resource name format] + (https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names). + The generated name is populated in the returned Snapshot object. + Note that for REST API requests, you must specify a name in the + request. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + async def sample_create_snapshot(): + # Create a client + client = pubsub_v1.SubscriberAsyncClient() + + # Initialize request argument(s) + request = pubsub_v1.CreateSnapshotRequest( + name="name_value", + subscription="subscription_value", + ) + + # Make the request + response = await client.create_snapshot(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.pubsub_v1.types.CreateSnapshotRequest, dict]]): + The request object. Request for the ``CreateSnapshot`` method. + name (:class:`str`): + Required. User-provided name for this snapshot. If the + name is not provided in the request, the server will + assign a random name for this snapshot on the same + project as the subscription. Note that for REST API + requests, you must specify a name. See the `resource + name + rules `__. + Format is ``projects/{project}/snapshots/{snap}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + subscription (:class:`str`): + Required. The subscription whose backlog the snapshot + retains. Specifically, the created snapshot is + guaranteed to retain: (a) The existing backlog on the + subscription. More precisely, this is defined as the + messages in the subscription's backlog that are + unacknowledged upon the successful completion of the + ``CreateSnapshot`` request; as well as: (b) Any messages + published to the subscription's topic following the + successful completion of the CreateSnapshot request. + Format is ``projects/{project}/subscriptions/{sub}``. + + This corresponds to the ``subscription`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.types.Snapshot: + A snapshot resource. Snapshots are used in + [Seek](https://cloud.google.com/pubsub/docs/replay-overview) + operations, which allow you to manage message + acknowledgments in bulk. That is, you can set the + acknowledgment state of messages in an existing + subscription to the state captured by a snapshot. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, subscription] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.CreateSnapshotRequest): + request = pubsub.CreateSnapshotRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if subscription is not None: + request.subscription = subscription + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_snapshot + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_snapshot( + self, + request: Optional[Union[pubsub.UpdateSnapshotRequest, dict]] = None, + *, + snapshot: Optional[pubsub.Snapshot] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.Snapshot: + r"""Updates an existing snapshot by updating the fields specified in + the update mask. Snapshots are used in + `Seek `__ + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + async def sample_update_snapshot(): + # Create a client + client = pubsub_v1.SubscriberAsyncClient() + + # Initialize request argument(s) + request = pubsub_v1.UpdateSnapshotRequest( + ) + + # Make the request + response = await client.update_snapshot(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.pubsub_v1.types.UpdateSnapshotRequest, dict]]): + The request object. Request for the UpdateSnapshot + method. + snapshot (:class:`google.pubsub_v1.types.Snapshot`): + Required. The updated snapshot + object. + + This corresponds to the ``snapshot`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Indicates which fields in + the provided snapshot to update. Must be + specified and non-empty. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.types.Snapshot: + A snapshot resource. Snapshots are used in + [Seek](https://cloud.google.com/pubsub/docs/replay-overview) + operations, which allow you to manage message + acknowledgments in bulk. That is, you can set the + acknowledgment state of messages in an existing + subscription to the state captured by a snapshot. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [snapshot, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.UpdateSnapshotRequest): + request = pubsub.UpdateSnapshotRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if snapshot is not None: + request.snapshot = snapshot + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_snapshot + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("snapshot.name", request.snapshot.name),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_snapshot( + self, + request: Optional[Union[pubsub.DeleteSnapshotRequest, dict]] = None, + *, + snapshot: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Removes an existing snapshot. Snapshots are used in [Seek] + (https://cloud.google.com/pubsub/docs/replay-overview) + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + When the snapshot is deleted, all messages retained in the + snapshot are immediately dropped. After a snapshot is deleted, a + new one may be created with the same name, but the new one has + no association with the old snapshot or its subscription, unless + the same subscription is specified. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + async def sample_delete_snapshot(): + # Create a client + client = pubsub_v1.SubscriberAsyncClient() + + # Initialize request argument(s) + request = pubsub_v1.DeleteSnapshotRequest( + snapshot="snapshot_value", + ) + + # Make the request + await client.delete_snapshot(request=request) + + Args: + request (Optional[Union[google.pubsub_v1.types.DeleteSnapshotRequest, dict]]): + The request object. Request for the ``DeleteSnapshot`` method. + snapshot (:class:`str`): + Required. The name of the snapshot to delete. Format is + ``projects/{project}/snapshots/{snap}``. + + This corresponds to the ``snapshot`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [snapshot] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.DeleteSnapshotRequest): + request = pubsub.DeleteSnapshotRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if snapshot is not None: + request.snapshot = snapshot + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_snapshot + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("snapshot", request.snapshot),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def seek( + self, + request: Optional[Union[pubsub.SeekRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.SeekResponse: + r"""Seeks an existing subscription to a point in time or to a given + snapshot, whichever is provided in the request. Snapshots are + used in [Seek] + (https://cloud.google.com/pubsub/docs/replay-overview) + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + Note that both the subscription and the snapshot must be on the + same topic. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + async def sample_seek(): + # Create a client + client = pubsub_v1.SubscriberAsyncClient() + + # Initialize request argument(s) + request = pubsub_v1.SeekRequest( + subscription="subscription_value", + ) + + # Make the request + response = await client.seek(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.pubsub_v1.types.SeekRequest, dict]]): + The request object. Request for the ``Seek`` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.types.SeekResponse: + Response for the Seek method (this response is empty). + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.SeekRequest): + request = pubsub.SeekRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.seek] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("subscription", request.subscription),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[ + self._client._transport.test_iam_permissions + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "SubscriberAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + client_library_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("SubscriberAsyncClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/subscriber/client.py b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/subscriber/client.py new file mode 100644 index 0000000000000000000000000000000000000000..774ff43ef01bfb3d6d5fcff703a8dc9af746c972 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/subscriber/client.py @@ -0,0 +1,3152 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed 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. +# +import json +import functools +import grpc +import logging as std_logging +import re +import warnings +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Iterable, + Iterator, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.pubsub_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) + +from google.pubsub_v1.services.subscriber import pagers +from google.pubsub_v1.types import pubsub + +from .transports.base import DEFAULT_CLIENT_INFO, SubscriberTransport +from .transports.grpc import SubscriberGrpcTransport +from .transports.grpc_asyncio import SubscriberGrpcAsyncIOTransport +from .transports.rest import SubscriberRestTransport + + +class SubscriberClientMeta(type): + """Metaclass for the Subscriber client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[SubscriberTransport]] + _transport_registry["grpc"] = SubscriberGrpcTransport + _transport_registry["grpc_asyncio"] = SubscriberGrpcAsyncIOTransport + _transport_registry["rest"] = SubscriberRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[SubscriberTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class SubscriberClient(metaclass=SubscriberClientMeta): + """The service that an application uses to manipulate subscriptions and + to consume messages from a subscription via the ``Pull`` method or + by establishing a bi-directional stream using the ``StreamingPull`` + method. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + Optional[str]: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + if m is None: + # Could not parse api_endpoint; return as-is. + return api_endpoint + + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + _DEFAULT_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/pubsub", + ) + SERVICE_ADDRESS = "pubsub.googleapis.com:443" + """The default address of the service.""" + DEFAULT_ENDPOINT = "pubsub.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "pubsub.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SubscriberClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + SubscriberClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> SubscriberTransport: + """Returns the transport used by the client instance. + + Returns: + SubscriberTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def listing_path( + project: str, + location: str, + data_exchange: str, + listing: str, + ) -> str: + """Returns a fully-qualified listing string.""" + return "projects/{project}/locations/{location}/dataExchanges/{data_exchange}/listings/{listing}".format( + project=project, + location=location, + data_exchange=data_exchange, + listing=listing, + ) + + @staticmethod + def parse_listing_path(path: str) -> Dict[str, str]: + """Parses a listing path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/dataExchanges/(?P.+?)/listings/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def snapshot_path( + project: str, + snapshot: str, + ) -> str: + """Returns a fully-qualified snapshot string.""" + return "projects/{project}/snapshots/{snapshot}".format( + project=project, + snapshot=snapshot, + ) + + @staticmethod + def parse_snapshot_path(path: str) -> Dict[str, str]: + """Parses a snapshot path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/snapshots/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def subscription_path( + project: str, + subscription: str, + ) -> str: + """Returns a fully-qualified subscription string.""" + return "projects/{project}/subscriptions/{subscription}".format( + project=project, + subscription=subscription, + ) + + @staticmethod + def parse_subscription_path(path: str) -> Dict[str, str]: + """Parses a subscription path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/subscriptions/(?P.+?)$", path + ) + return m.groupdict() if m else {} + + @staticmethod + def topic_path( + project: str, + topic: str, + ) -> str: + """Returns a fully-qualified topic string.""" + return "projects/{project}/topics/{topic}".format( + project=project, + topic=topic, + ) + + @staticmethod + def parse_topic_path(path: str) -> Dict[str, str]: + """Parses a topic path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/topics/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = SubscriberClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert: + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = SubscriberClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert, use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ) -> str: + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = SubscriberClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = SubscriberClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = SubscriberClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = SubscriberClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self) -> str: + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[str, SubscriberTransport, Callable[..., SubscriberTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the subscriber client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,SubscriberTransport,Callable[..., SubscriberTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the SubscriberTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + SubscriberClient._read_environment_variables() + ) + self._client_cert_source = SubscriberClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = SubscriberClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint: str = "" # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, SubscriberTransport) + if transport_provided: + # transport is a SubscriberTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes directly." + ) + self._transport = cast(SubscriberTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = self._api_endpoint or SubscriberClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[SubscriberTransport], Callable[..., SubscriberTransport] + ] = ( + SubscriberClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., SubscriberTransport], transport) + ) + # initialize with the provided callable or the passed in class + emulator_host = os.environ.get("PUBSUB_EMULATOR_HOST") + if emulator_host: + if issubclass(transport_init, type(self)._transport_registry["grpc"]): # type: ignore + channel = grpc.insecure_channel(target=emulator_host) + else: + channel = grpc.aio.insecure_channel(target=emulator_host) + transport_init = functools.partial(transport_init, channel=channel) + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.pubsub_v1.SubscriberClient`.", + extra={ + "serviceName": "google.pubsub.v1.Subscriber", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.pubsub.v1.Subscriber", + "credentialsType": None, + }, + ) + + def create_subscription( + self, + request: Optional[Union[pubsub.Subscription, dict]] = None, + *, + name: Optional[str] = None, + topic: Optional[str] = None, + push_config: Optional[pubsub.PushConfig] = None, + ack_deadline_seconds: Optional[int] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.Subscription: + r"""Creates a subscription to a given topic. See the [resource name + rules] + (https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names). + If the subscription already exists, returns ``ALREADY_EXISTS``. + If the corresponding topic doesn't exist, returns ``NOT_FOUND``. + + If the name is not provided in the request, the server will + assign a random name for this subscription on the same project + as the topic, conforming to the [resource name format] + (https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names). + The generated name is populated in the returned Subscription + object. Note that for REST API requests, you must specify a name + in the request. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + def sample_create_subscription(): + # Create a client + client = pubsub_v1.SubscriberClient() + + # Initialize request argument(s) + request = pubsub_v1.Subscription( + name="name_value", + topic="topic_value", + ) + + # Make the request + response = client.create_subscription(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.pubsub_v1.types.Subscription, dict]): + The request object. A subscription resource. If none of ``push_config``, + ``bigquery_config``, or ``cloud_storage_config`` is set, + then the subscriber will pull and ack messages using API + methods. At most one of these fields may be set. + name (str): + Required. Identifier. The name of the subscription. It + must have the format + ``"projects/{project}/subscriptions/{subscription}"``. + ``{subscription}`` must start with a letter, and contain + only letters (``[A-Za-z]``), numbers (``[0-9]``), dashes + (``-``), underscores (``_``), periods (``.``), tildes + (``~``), plus (``+``) or percent signs (``%``). It must + be between 3 and 255 characters in length, and it must + not start with ``"goog"``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + topic (str): + Required. The name of the topic from which this + subscription is receiving messages. Format is + ``projects/{project}/topics/{topic}``. The value of this + field will be ``_deleted-topic_`` if the topic has been + deleted. + + This corresponds to the ``topic`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + push_config (google.pubsub_v1.types.PushConfig): + Optional. If push delivery is used + with this subscription, this field is + used to configure it. + + This corresponds to the ``push_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ack_deadline_seconds (int): + Optional. The approximate amount of time (on a + best-effort basis) Pub/Sub waits for the subscriber to + acknowledge receipt before resending the message. In the + interval after the message is delivered and before it is + acknowledged, it is considered to be *outstanding*. + During that time period, the message will not be + redelivered (on a best-effort basis). + + For pull subscriptions, this value is used as the + initial value for the ack deadline. To override this + value for a given message, call ``ModifyAckDeadline`` + with the corresponding ``ack_id`` if using non-streaming + pull or send the ``ack_id`` in a + ``StreamingModifyAckDeadlineRequest`` if using streaming + pull. The minimum custom deadline you can specify is 10 + seconds. The maximum custom deadline you can specify is + 600 seconds (10 minutes). If this parameter is 0, a + default value of 10 seconds is used. + + For push delivery, this value is also used to set the + request timeout for the call to the push endpoint. + + If the subscriber never acknowledges the message, the + Pub/Sub system will eventually redeliver the message. + + This corresponds to the ``ack_deadline_seconds`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.types.Subscription: + A subscription resource. If none of push_config, bigquery_config, or + cloud_storage_config is set, then the subscriber will + pull and ack messages using API methods. At most one + of these fields may be set. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, topic, push_config, ack_deadline_seconds] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.Subscription): + request = pubsub.Subscription(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if topic is not None: + request.topic = topic + if push_config is not None: + request.push_config = push_config + if ack_deadline_seconds is not None: + request.ack_deadline_seconds = ack_deadline_seconds + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_subscription] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_subscription( + self, + request: Optional[Union[pubsub.GetSubscriptionRequest, dict]] = None, + *, + subscription: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.Subscription: + r"""Gets the configuration details of a subscription. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + def sample_get_subscription(): + # Create a client + client = pubsub_v1.SubscriberClient() + + # Initialize request argument(s) + request = pubsub_v1.GetSubscriptionRequest( + subscription="subscription_value", + ) + + # Make the request + response = client.get_subscription(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.pubsub_v1.types.GetSubscriptionRequest, dict]): + The request object. Request for the GetSubscription + method. + subscription (str): + Required. The name of the subscription to get. Format is + ``projects/{project}/subscriptions/{sub}``. + + This corresponds to the ``subscription`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.types.Subscription: + A subscription resource. If none of push_config, bigquery_config, or + cloud_storage_config is set, then the subscriber will + pull and ack messages using API methods. At most one + of these fields may be set. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [subscription] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.GetSubscriptionRequest): + request = pubsub.GetSubscriptionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if subscription is not None: + request.subscription = subscription + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_subscription] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("subscription", request.subscription),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_subscription( + self, + request: Optional[Union[pubsub.UpdateSubscriptionRequest, dict]] = None, + *, + subscription: Optional[pubsub.Subscription] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.Subscription: + r"""Updates an existing subscription by updating the + fields specified in the update mask. Note that certain + properties of a subscription, such as its topic, are not + modifiable. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + def sample_update_subscription(): + # Create a client + client = pubsub_v1.SubscriberClient() + + # Initialize request argument(s) + subscription = pubsub_v1.Subscription() + subscription.name = "name_value" + subscription.topic = "topic_value" + + request = pubsub_v1.UpdateSubscriptionRequest( + subscription=subscription, + ) + + # Make the request + response = client.update_subscription(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.pubsub_v1.types.UpdateSubscriptionRequest, dict]): + The request object. Request for the UpdateSubscription + method. + subscription (google.pubsub_v1.types.Subscription): + Required. The updated subscription + object. + + This corresponds to the ``subscription`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Indicates which fields in + the provided subscription to update. + Must be specified and non-empty. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.types.Subscription: + A subscription resource. If none of push_config, bigquery_config, or + cloud_storage_config is set, then the subscriber will + pull and ack messages using API methods. At most one + of these fields may be set. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [subscription, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.UpdateSubscriptionRequest): + request = pubsub.UpdateSubscriptionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if subscription is not None: + request.subscription = subscription + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_subscription] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("subscription.name", request.subscription.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_subscriptions( + self, + request: Optional[Union[pubsub.ListSubscriptionsRequest, dict]] = None, + *, + project: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListSubscriptionsPager: + r"""Lists matching subscriptions. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + def sample_list_subscriptions(): + # Create a client + client = pubsub_v1.SubscriberClient() + + # Initialize request argument(s) + request = pubsub_v1.ListSubscriptionsRequest( + project="project_value", + ) + + # Make the request + page_result = client.list_subscriptions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.pubsub_v1.types.ListSubscriptionsRequest, dict]): + The request object. Request for the ``ListSubscriptions`` method. + project (str): + Required. The name of the project in which to list + subscriptions. Format is ``projects/{project-id}``. + + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.services.subscriber.pagers.ListSubscriptionsPager: + Response for the ListSubscriptions method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [project] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.ListSubscriptionsRequest): + request = pubsub.ListSubscriptionsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_subscriptions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("project", request.project),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListSubscriptionsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_subscription( + self, + request: Optional[Union[pubsub.DeleteSubscriptionRequest, dict]] = None, + *, + subscription: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Deletes an existing subscription. All messages retained in the + subscription are immediately dropped. Calls to ``Pull`` after + deletion will return ``NOT_FOUND``. After a subscription is + deleted, a new one may be created with the same name, but the + new one has no association with the old subscription or its + topic unless the same topic is specified. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + def sample_delete_subscription(): + # Create a client + client = pubsub_v1.SubscriberClient() + + # Initialize request argument(s) + request = pubsub_v1.DeleteSubscriptionRequest( + subscription="subscription_value", + ) + + # Make the request + client.delete_subscription(request=request) + + Args: + request (Union[google.pubsub_v1.types.DeleteSubscriptionRequest, dict]): + The request object. Request for the DeleteSubscription + method. + subscription (str): + Required. The subscription to delete. Format is + ``projects/{project}/subscriptions/{sub}``. + + This corresponds to the ``subscription`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [subscription] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.DeleteSubscriptionRequest): + request = pubsub.DeleteSubscriptionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if subscription is not None: + request.subscription = subscription + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_subscription] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("subscription", request.subscription),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def modify_ack_deadline( + self, + request: Optional[Union[pubsub.ModifyAckDeadlineRequest, dict]] = None, + *, + subscription: Optional[str] = None, + ack_ids: Optional[MutableSequence[str]] = None, + ack_deadline_seconds: Optional[int] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Modifies the ack deadline for a specific message. This method is + useful to indicate that more time is needed to process a message + by the subscriber, or to make the message available for + redelivery if the processing was interrupted. Note that this + does not modify the subscription-level ``ackDeadlineSeconds`` + used for subsequent messages. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + def sample_modify_ack_deadline(): + # Create a client + client = pubsub_v1.SubscriberClient() + + # Initialize request argument(s) + request = pubsub_v1.ModifyAckDeadlineRequest( + subscription="subscription_value", + ack_ids=['ack_ids_value1', 'ack_ids_value2'], + ack_deadline_seconds=2066, + ) + + # Make the request + client.modify_ack_deadline(request=request) + + Args: + request (Union[google.pubsub_v1.types.ModifyAckDeadlineRequest, dict]): + The request object. Request for the ModifyAckDeadline + method. + subscription (str): + Required. The name of the subscription. Format is + ``projects/{project}/subscriptions/{sub}``. + + This corresponds to the ``subscription`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ack_ids (MutableSequence[str]): + Required. List of acknowledgment IDs. + This corresponds to the ``ack_ids`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ack_deadline_seconds (int): + Required. The new ack deadline with respect to the time + this request was sent to the Pub/Sub system. For + example, if the value is 10, the new ack deadline will + expire 10 seconds after the ``ModifyAckDeadline`` call + was made. Specifying zero might immediately make the + message available for delivery to another subscriber + client. This typically results in an increase in the + rate of message redeliveries (that is, duplicates). The + minimum deadline you can specify is 0 seconds. The + maximum deadline you can specify in a single request is + 600 seconds (10 minutes). + + This corresponds to the ``ack_deadline_seconds`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [subscription, ack_ids, ack_deadline_seconds] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.ModifyAckDeadlineRequest): + request = pubsub.ModifyAckDeadlineRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if subscription is not None: + request.subscription = subscription + if ack_ids is not None: + request.ack_ids = ack_ids + if ack_deadline_seconds is not None: + request.ack_deadline_seconds = ack_deadline_seconds + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.modify_ack_deadline] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("subscription", request.subscription),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def acknowledge( + self, + request: Optional[Union[pubsub.AcknowledgeRequest, dict]] = None, + *, + subscription: Optional[str] = None, + ack_ids: Optional[MutableSequence[str]] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Acknowledges the messages associated with the ``ack_ids`` in the + ``AcknowledgeRequest``. The Pub/Sub system can remove the + relevant messages from the subscription. + + Acknowledging a message whose ack deadline has expired may + succeed, but such a message may be redelivered later. + Acknowledging a message more than once will not result in an + error. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + def sample_acknowledge(): + # Create a client + client = pubsub_v1.SubscriberClient() + + # Initialize request argument(s) + request = pubsub_v1.AcknowledgeRequest( + subscription="subscription_value", + ack_ids=['ack_ids_value1', 'ack_ids_value2'], + ) + + # Make the request + client.acknowledge(request=request) + + Args: + request (Union[google.pubsub_v1.types.AcknowledgeRequest, dict]): + The request object. Request for the Acknowledge method. + subscription (str): + Required. The subscription whose message is being + acknowledged. Format is + ``projects/{project}/subscriptions/{sub}``. + + This corresponds to the ``subscription`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ack_ids (MutableSequence[str]): + Required. The acknowledgment ID for the messages being + acknowledged that was returned by the Pub/Sub system in + the ``Pull`` response. Must not be empty. + + This corresponds to the ``ack_ids`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [subscription, ack_ids] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.AcknowledgeRequest): + request = pubsub.AcknowledgeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if subscription is not None: + request.subscription = subscription + if ack_ids is not None: + request.ack_ids = ack_ids + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.acknowledge] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("subscription", request.subscription),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def pull( + self, + request: Optional[Union[pubsub.PullRequest, dict]] = None, + *, + subscription: Optional[str] = None, + return_immediately: Optional[bool] = None, + max_messages: Optional[int] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.PullResponse: + r"""Pulls messages from the server. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + def sample_pull(): + # Create a client + client = pubsub_v1.SubscriberClient() + + # Initialize request argument(s) + request = pubsub_v1.PullRequest( + subscription="subscription_value", + max_messages=1277, + ) + + # Make the request + response = client.pull(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.pubsub_v1.types.PullRequest, dict]): + The request object. Request for the ``Pull`` method. + subscription (str): + Required. The subscription from which messages should be + pulled. Format is + ``projects/{project}/subscriptions/{sub}``. + + This corresponds to the ``subscription`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + return_immediately (bool): + Optional. If this field set to true, the system will + respond immediately even if it there are no messages + available to return in the ``Pull`` response. Otherwise, + the system may wait (for a bounded amount of time) until + at least one message is available, rather than returning + no messages. Warning: setting this field to ``true`` is + discouraged because it adversely impacts the performance + of ``Pull`` operations. We recommend that users do not + set this field. + + This corresponds to the ``return_immediately`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + max_messages (int): + Required. The maximum number of + messages to return for this request. + Must be a positive integer. The Pub/Sub + system may return fewer than the number + specified. + + This corresponds to the ``max_messages`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.types.PullResponse: + Response for the Pull method. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [subscription, return_immediately, max_messages] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.PullRequest): + request = pubsub.PullRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if subscription is not None: + request.subscription = subscription + if return_immediately is not None: + request.return_immediately = return_immediately + if max_messages is not None: + request.max_messages = max_messages + + if request.return_immediately: + warnings.warn( + "The return_immediately flag is deprecated and should be set to False.", + category=DeprecationWarning, + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.pull] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("subscription", request.subscription),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def streaming_pull( + self, + requests: Optional[Iterator[pubsub.StreamingPullRequest]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> Iterable[pubsub.StreamingPullResponse]: + r"""Establishes a stream with the server, which sends messages down + to the client. The client streams acknowledgments and ack + deadline modifications back to the server. The server will close + the stream and return the status on any error. The server may + close the stream with status ``UNAVAILABLE`` to reassign + server-side resources, in which case, the client should + re-establish the stream. Flow control can be achieved by + configuring the underlying RPC channel. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + def sample_streaming_pull(): + # Create a client + client = pubsub_v1.SubscriberClient() + + # Initialize request argument(s) + request = pubsub_v1.StreamingPullRequest( + subscription="subscription_value", + stream_ack_deadline_seconds=2813, + ) + + # This method expects an iterator which contains + # 'pubsub_v1.StreamingPullRequest' objects + # Here we create a generator that yields a single `request` for + # demonstrative purposes. + requests = [request] + + def request_generator(): + for request in requests: + yield request + + # Make the request + stream = client.streaming_pull(requests=request_generator()) + + # Handle the response + for response in stream: + print(response) + + Args: + requests (Iterator[google.pubsub_v1.types.StreamingPullRequest]): + The request object iterator. Request for the ``StreamingPull`` streaming RPC method. + This request is used to establish the initial stream as + well as to stream acknowledgments and ack deadline + modifications from the client to the server. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + Iterable[google.pubsub_v1.types.StreamingPullResponse]: + Response for the StreamingPull method. This response is used to stream + messages from the server to the client. + + """ + + # Wrappers in api-core should not automatically pre-fetch the first + # stream result, as this breaks the stream when re-opening it. + # https://github.com/googleapis/python-pubsub/issues/93#issuecomment-630762257 + self._transport.streaming_pull._prefetch_first_result_ = False + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.streaming_pull] + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + requests, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def modify_push_config( + self, + request: Optional[Union[pubsub.ModifyPushConfigRequest, dict]] = None, + *, + subscription: Optional[str] = None, + push_config: Optional[pubsub.PushConfig] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Modifies the ``PushConfig`` for a specified subscription. + + This may be used to change a push subscription to a pull one + (signified by an empty ``PushConfig``) or vice versa, or change + the endpoint URL and other attributes of a push subscription. + Messages will accumulate for delivery continuously through the + call regardless of changes to the ``PushConfig``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + def sample_modify_push_config(): + # Create a client + client = pubsub_v1.SubscriberClient() + + # Initialize request argument(s) + request = pubsub_v1.ModifyPushConfigRequest( + subscription="subscription_value", + ) + + # Make the request + client.modify_push_config(request=request) + + Args: + request (Union[google.pubsub_v1.types.ModifyPushConfigRequest, dict]): + The request object. Request for the ModifyPushConfig + method. + subscription (str): + Required. The name of the subscription. Format is + ``projects/{project}/subscriptions/{sub}``. + + This corresponds to the ``subscription`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + push_config (google.pubsub_v1.types.PushConfig): + Required. The push configuration for future deliveries. + + An empty ``pushConfig`` indicates that the Pub/Sub + system should stop pushing messages from the given + subscription and allow messages to be pulled and + acknowledged - effectively pausing the subscription if + ``Pull`` or ``StreamingPull`` is not called. + + This corresponds to the ``push_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [subscription, push_config] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.ModifyPushConfigRequest): + request = pubsub.ModifyPushConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if subscription is not None: + request.subscription = subscription + if push_config is not None: + request.push_config = push_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.modify_push_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("subscription", request.subscription),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_snapshot( + self, + request: Optional[Union[pubsub.GetSnapshotRequest, dict]] = None, + *, + snapshot: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.Snapshot: + r"""Gets the configuration details of a snapshot. Snapshots are used + in + `Seek `__ + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + def sample_get_snapshot(): + # Create a client + client = pubsub_v1.SubscriberClient() + + # Initialize request argument(s) + request = pubsub_v1.GetSnapshotRequest( + snapshot="snapshot_value", + ) + + # Make the request + response = client.get_snapshot(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.pubsub_v1.types.GetSnapshotRequest, dict]): + The request object. Request for the GetSnapshot method. + snapshot (str): + Required. The name of the snapshot to get. Format is + ``projects/{project}/snapshots/{snap}``. + + This corresponds to the ``snapshot`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.types.Snapshot: + A snapshot resource. Snapshots are used in + [Seek](https://cloud.google.com/pubsub/docs/replay-overview) + operations, which allow you to manage message + acknowledgments in bulk. That is, you can set the + acknowledgment state of messages in an existing + subscription to the state captured by a snapshot. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [snapshot] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.GetSnapshotRequest): + request = pubsub.GetSnapshotRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if snapshot is not None: + request.snapshot = snapshot + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_snapshot] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("snapshot", request.snapshot),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_snapshots( + self, + request: Optional[Union[pubsub.ListSnapshotsRequest, dict]] = None, + *, + project: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListSnapshotsPager: + r"""Lists the existing snapshots. Snapshots are used in + `Seek `__ + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + def sample_list_snapshots(): + # Create a client + client = pubsub_v1.SubscriberClient() + + # Initialize request argument(s) + request = pubsub_v1.ListSnapshotsRequest( + project="project_value", + ) + + # Make the request + page_result = client.list_snapshots(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.pubsub_v1.types.ListSnapshotsRequest, dict]): + The request object. Request for the ``ListSnapshots`` method. + project (str): + Required. The name of the project in which to list + snapshots. Format is ``projects/{project-id}``. + + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.services.subscriber.pagers.ListSnapshotsPager: + Response for the ListSnapshots method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [project] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.ListSnapshotsRequest): + request = pubsub.ListSnapshotsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_snapshots] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("project", request.project),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListSnapshotsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_snapshot( + self, + request: Optional[Union[pubsub.CreateSnapshotRequest, dict]] = None, + *, + name: Optional[str] = None, + subscription: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.Snapshot: + r"""Creates a snapshot from the requested subscription. Snapshots + are used in + `Seek `__ + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + If the snapshot already exists, returns ``ALREADY_EXISTS``. If + the requested subscription doesn't exist, returns ``NOT_FOUND``. + If the backlog in the subscription is too old -- and the + resulting snapshot would expire in less than 1 hour -- then + ``FAILED_PRECONDITION`` is returned. See also the + ``Snapshot.expire_time`` field. If the name is not provided in + the request, the server will assign a random name for this + snapshot on the same project as the subscription, conforming to + the [resource name format] + (https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names). + The generated name is populated in the returned Snapshot object. + Note that for REST API requests, you must specify a name in the + request. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + def sample_create_snapshot(): + # Create a client + client = pubsub_v1.SubscriberClient() + + # Initialize request argument(s) + request = pubsub_v1.CreateSnapshotRequest( + name="name_value", + subscription="subscription_value", + ) + + # Make the request + response = client.create_snapshot(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.pubsub_v1.types.CreateSnapshotRequest, dict]): + The request object. Request for the ``CreateSnapshot`` method. + name (str): + Required. User-provided name for this snapshot. If the + name is not provided in the request, the server will + assign a random name for this snapshot on the same + project as the subscription. Note that for REST API + requests, you must specify a name. See the `resource + name + rules `__. + Format is ``projects/{project}/snapshots/{snap}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + subscription (str): + Required. The subscription whose backlog the snapshot + retains. Specifically, the created snapshot is + guaranteed to retain: (a) The existing backlog on the + subscription. More precisely, this is defined as the + messages in the subscription's backlog that are + unacknowledged upon the successful completion of the + ``CreateSnapshot`` request; as well as: (b) Any messages + published to the subscription's topic following the + successful completion of the CreateSnapshot request. + Format is ``projects/{project}/subscriptions/{sub}``. + + This corresponds to the ``subscription`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.types.Snapshot: + A snapshot resource. Snapshots are used in + [Seek](https://cloud.google.com/pubsub/docs/replay-overview) + operations, which allow you to manage message + acknowledgments in bulk. That is, you can set the + acknowledgment state of messages in an existing + subscription to the state captured by a snapshot. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name, subscription] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.CreateSnapshotRequest): + request = pubsub.CreateSnapshotRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if subscription is not None: + request.subscription = subscription + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_snapshot] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_snapshot( + self, + request: Optional[Union[pubsub.UpdateSnapshotRequest, dict]] = None, + *, + snapshot: Optional[pubsub.Snapshot] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.Snapshot: + r"""Updates an existing snapshot by updating the fields specified in + the update mask. Snapshots are used in + `Seek `__ + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + def sample_update_snapshot(): + # Create a client + client = pubsub_v1.SubscriberClient() + + # Initialize request argument(s) + request = pubsub_v1.UpdateSnapshotRequest( + ) + + # Make the request + response = client.update_snapshot(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.pubsub_v1.types.UpdateSnapshotRequest, dict]): + The request object. Request for the UpdateSnapshot + method. + snapshot (google.pubsub_v1.types.Snapshot): + Required. The updated snapshot + object. + + This corresponds to the ``snapshot`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Indicates which fields in + the provided snapshot to update. Must be + specified and non-empty. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.types.Snapshot: + A snapshot resource. Snapshots are used in + [Seek](https://cloud.google.com/pubsub/docs/replay-overview) + operations, which allow you to manage message + acknowledgments in bulk. That is, you can set the + acknowledgment state of messages in an existing + subscription to the state captured by a snapshot. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [snapshot, update_mask] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.UpdateSnapshotRequest): + request = pubsub.UpdateSnapshotRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if snapshot is not None: + request.snapshot = snapshot + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_snapshot] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("snapshot.name", request.snapshot.name),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_snapshot( + self, + request: Optional[Union[pubsub.DeleteSnapshotRequest, dict]] = None, + *, + snapshot: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Removes an existing snapshot. Snapshots are used in [Seek] + (https://cloud.google.com/pubsub/docs/replay-overview) + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + When the snapshot is deleted, all messages retained in the + snapshot are immediately dropped. After a snapshot is deleted, a + new one may be created with the same name, but the new one has + no association with the old snapshot or its subscription, unless + the same subscription is specified. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + def sample_delete_snapshot(): + # Create a client + client = pubsub_v1.SubscriberClient() + + # Initialize request argument(s) + request = pubsub_v1.DeleteSnapshotRequest( + snapshot="snapshot_value", + ) + + # Make the request + client.delete_snapshot(request=request) + + Args: + request (Union[google.pubsub_v1.types.DeleteSnapshotRequest, dict]): + The request object. Request for the ``DeleteSnapshot`` method. + snapshot (str): + Required. The name of the snapshot to delete. Format is + ``projects/{project}/snapshots/{snap}``. + + This corresponds to the ``snapshot`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [snapshot] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.DeleteSnapshotRequest): + request = pubsub.DeleteSnapshotRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if snapshot is not None: + request.snapshot = snapshot + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_snapshot] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("snapshot", request.snapshot),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def seek( + self, + request: Optional[Union[pubsub.SeekRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.SeekResponse: + r"""Seeks an existing subscription to a point in time or to a given + snapshot, whichever is provided in the request. Snapshots are + used in [Seek] + (https://cloud.google.com/pubsub/docs/replay-overview) + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + Note that both the subscription and the snapshot must be on the + same topic. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google import pubsub_v1 + + def sample_seek(): + # Create a client + client = pubsub_v1.SubscriberClient() + + # Initialize request argument(s) + request = pubsub_v1.SeekRequest( + subscription="subscription_value", + ) + + # Make the request + response = client.seek(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.pubsub_v1.types.SeekRequest, dict]): + The request object. Request for the ``Seek`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.pubsub_v1.types.SeekResponse: + Response for the Seek method (this response is empty). + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, pubsub.SeekRequest): + request = pubsub.SeekRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.seek] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("subscription", request.subscription),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "SubscriberClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def set_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.SetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.SetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_iam_policy( + self, + request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.GetIamPolicyRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.GetIamPolicyRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def test_iam_permissions( + self, + request: Optional[Union[iam_policy_pb2.TestIamPermissionsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = iam_policy_pb2.TestIamPermissionsRequest() + elif isinstance(request, dict): + request_pb = iam_policy_pb2.TestIamPermissionsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request_pb.resource),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + client_library_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("SubscriberClient",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/subscriber/pagers.py b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/subscriber/pagers.py new file mode 100644 index 0000000000000000000000000000000000000000..823ba9bd2db2c2083571768fd88c2ad4adc6bdea --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/subscriber/pagers.py @@ -0,0 +1,353 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed 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. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[ + retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None + ] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.pubsub_v1.types import pubsub + + +class ListSubscriptionsPager: + """A pager for iterating through ``list_subscriptions`` requests. + + This class thinly wraps an initial + :class:`google.pubsub_v1.types.ListSubscriptionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``subscriptions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSubscriptions`` requests and continue to iterate + through the ``subscriptions`` field on the + corresponding responses. + + All the usual :class:`google.pubsub_v1.types.ListSubscriptionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., pubsub.ListSubscriptionsResponse], + request: pubsub.ListSubscriptionsRequest, + response: pubsub.ListSubscriptionsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.pubsub_v1.types.ListSubscriptionsRequest): + The initial request object. + response (google.pubsub_v1.types.ListSubscriptionsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = pubsub.ListSubscriptionsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[pubsub.ListSubscriptionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[pubsub.Subscription]: + for page in self.pages: + yield from page.subscriptions + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSubscriptionsAsyncPager: + """A pager for iterating through ``list_subscriptions`` requests. + + This class thinly wraps an initial + :class:`google.pubsub_v1.types.ListSubscriptionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``subscriptions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSubscriptions`` requests and continue to iterate + through the ``subscriptions`` field on the + corresponding responses. + + All the usual :class:`google.pubsub_v1.types.ListSubscriptionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[pubsub.ListSubscriptionsResponse]], + request: pubsub.ListSubscriptionsRequest, + response: pubsub.ListSubscriptionsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.pubsub_v1.types.ListSubscriptionsRequest): + The initial request object. + response (google.pubsub_v1.types.ListSubscriptionsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = pubsub.ListSubscriptionsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[pubsub.ListSubscriptionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[pubsub.Subscription]: + async def async_generator(): + async for page in self.pages: + for response in page.subscriptions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSnapshotsPager: + """A pager for iterating through ``list_snapshots`` requests. + + This class thinly wraps an initial + :class:`google.pubsub_v1.types.ListSnapshotsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``snapshots`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSnapshots`` requests and continue to iterate + through the ``snapshots`` field on the + corresponding responses. + + All the usual :class:`google.pubsub_v1.types.ListSnapshotsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., pubsub.ListSnapshotsResponse], + request: pubsub.ListSnapshotsRequest, + response: pubsub.ListSnapshotsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.pubsub_v1.types.ListSnapshotsRequest): + The initial request object. + response (google.pubsub_v1.types.ListSnapshotsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = pubsub.ListSnapshotsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[pubsub.ListSnapshotsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[pubsub.Snapshot]: + for page in self.pages: + yield from page.snapshots + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSnapshotsAsyncPager: + """A pager for iterating through ``list_snapshots`` requests. + + This class thinly wraps an initial + :class:`google.pubsub_v1.types.ListSnapshotsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``snapshots`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSnapshots`` requests and continue to iterate + through the ``snapshots`` field on the + corresponding responses. + + All the usual :class:`google.pubsub_v1.types.ListSnapshotsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[pubsub.ListSnapshotsResponse]], + request: pubsub.ListSnapshotsRequest, + response: pubsub.ListSnapshotsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.pubsub_v1.types.ListSnapshotsRequest): + The initial request object. + response (google.pubsub_v1.types.ListSnapshotsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = pubsub.ListSnapshotsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[pubsub.ListSnapshotsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[pubsub.Snapshot]: + async def async_generator(): + async for page in self.pages: + for response in page.snapshots: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/subscriber/transports/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/subscriber/transports/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e5fa8ba4626e8ff4abbcefd60a5912219b45a9f0 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/subscriber/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed 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. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import SubscriberTransport +from .grpc import SubscriberGrpcTransport +from .grpc_asyncio import SubscriberGrpcAsyncIOTransport +from .rest import SubscriberRestInterceptor, SubscriberRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SubscriberTransport]] +_transport_registry["grpc"] = SubscriberGrpcTransport +_transport_registry["grpc_asyncio"] = SubscriberGrpcAsyncIOTransport +_transport_registry["rest"] = SubscriberRestTransport + +__all__ = ( + "SubscriberTransport", + "SubscriberGrpcTransport", + "SubscriberGrpcAsyncIOTransport", + "SubscriberRestTransport", + "SubscriberRestInterceptor", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/subscriber/transports/base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/subscriber/transports/base.py new file mode 100644 index 0000000000000000000000000000000000000000..287199eeee765a17b34093382791f2f8795c111e --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/subscriber/transports/base.py @@ -0,0 +1,600 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed 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. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +import google.auth # type: ignore +import google.protobuf +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.oauth2 import service_account # type: ignore + +from google.pubsub_v1 import gapic_version as package_version +from google.pubsub_v1.types import pubsub + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + client_library_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class SubscriberTransport(abc.ABC): + """Abstract transport class for Subscriber.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/pubsub", + ) + + DEFAULT_HOST: str = "pubsub.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'pubsub.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_subscription: gapic_v1.method.wrap_method( + self.create_subscription, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_subscription: gapic_v1.method.wrap_method( + self.get_subscription, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_subscription: gapic_v1.method.wrap_method( + self.update_subscription, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_subscriptions: gapic_v1.method.wrap_method( + self.list_subscriptions, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_subscription: gapic_v1.method.wrap_method( + self.delete_subscription, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.modify_ack_deadline: gapic_v1.method.wrap_method( + self.modify_ack_deadline, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.acknowledge: gapic_v1.method.wrap_method( + self.acknowledge, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.pull: gapic_v1.method.wrap_method( + self.pull, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.InternalServerError, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.streaming_pull: gapic_v1.method.wrap_method( + self.streaming_pull, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=4, + predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + ), + deadline=900.0, + ), + default_timeout=900.0, + client_info=client_info, + ), + self.modify_push_config: gapic_v1.method.wrap_method( + self.modify_push_config, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_snapshot: gapic_v1.method.wrap_method( + self.get_snapshot, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_snapshots: gapic_v1.method.wrap_method( + self.list_snapshots, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_snapshot: gapic_v1.method.wrap_method( + self.create_snapshot, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_snapshot: gapic_v1.method.wrap_method( + self.update_snapshot, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_snapshot: gapic_v1.method.wrap_method( + self.delete_snapshot, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.seek: gapic_v1.method.wrap_method( + self.seek, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def create_subscription( + self, + ) -> Callable[ + [pubsub.Subscription], + Union[pubsub.Subscription, Awaitable[pubsub.Subscription]], + ]: + raise NotImplementedError() + + @property + def get_subscription( + self, + ) -> Callable[ + [pubsub.GetSubscriptionRequest], + Union[pubsub.Subscription, Awaitable[pubsub.Subscription]], + ]: + raise NotImplementedError() + + @property + def update_subscription( + self, + ) -> Callable[ + [pubsub.UpdateSubscriptionRequest], + Union[pubsub.Subscription, Awaitable[pubsub.Subscription]], + ]: + raise NotImplementedError() + + @property + def list_subscriptions( + self, + ) -> Callable[ + [pubsub.ListSubscriptionsRequest], + Union[ + pubsub.ListSubscriptionsResponse, + Awaitable[pubsub.ListSubscriptionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def delete_subscription( + self, + ) -> Callable[ + [pubsub.DeleteSubscriptionRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def modify_ack_deadline( + self, + ) -> Callable[ + [pubsub.ModifyAckDeadlineRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def acknowledge( + self, + ) -> Callable[ + [pubsub.AcknowledgeRequest], Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]] + ]: + raise NotImplementedError() + + @property + def pull( + self, + ) -> Callable[ + [pubsub.PullRequest], Union[pubsub.PullResponse, Awaitable[pubsub.PullResponse]] + ]: + raise NotImplementedError() + + @property + def streaming_pull( + self, + ) -> Callable[ + [pubsub.StreamingPullRequest], + Union[pubsub.StreamingPullResponse, Awaitable[pubsub.StreamingPullResponse]], + ]: + raise NotImplementedError() + + @property + def modify_push_config( + self, + ) -> Callable[ + [pubsub.ModifyPushConfigRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def get_snapshot( + self, + ) -> Callable[ + [pubsub.GetSnapshotRequest], Union[pubsub.Snapshot, Awaitable[pubsub.Snapshot]] + ]: + raise NotImplementedError() + + @property + def list_snapshots( + self, + ) -> Callable[ + [pubsub.ListSnapshotsRequest], + Union[pubsub.ListSnapshotsResponse, Awaitable[pubsub.ListSnapshotsResponse]], + ]: + raise NotImplementedError() + + @property + def create_snapshot( + self, + ) -> Callable[ + [pubsub.CreateSnapshotRequest], + Union[pubsub.Snapshot, Awaitable[pubsub.Snapshot]], + ]: + raise NotImplementedError() + + @property + def update_snapshot( + self, + ) -> Callable[ + [pubsub.UpdateSnapshotRequest], + Union[pubsub.Snapshot, Awaitable[pubsub.Snapshot]], + ]: + raise NotImplementedError() + + @property + def delete_snapshot( + self, + ) -> Callable[ + [pubsub.DeleteSnapshotRequest], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], + ]: + raise NotImplementedError() + + @property + def seek( + self, + ) -> Callable[ + [pubsub.SeekRequest], Union[pubsub.SeekResponse, Awaitable[pubsub.SeekResponse]] + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("SubscriberTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/subscriber/transports/grpc.py b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/subscriber/transports/grpc.py new file mode 100644 index 0000000000000000000000000000000000000000..5a882def970a9a0025d789aa69f454ecbeffb852 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/subscriber/transports/grpc.py @@ -0,0 +1,928 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed 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. +# +import json +import logging as std_logging +import pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +import google.auth # type: ignore +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.protobuf.json_format import MessageToJson + +from google.pubsub_v1.types import pubsub + +from .base import DEFAULT_CLIENT_INFO, SubscriberTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.pubsub.v1.Subscriber", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.pubsub.v1.Subscriber", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class SubscriberGrpcTransport(SubscriberTransport): + """gRPC backend transport for Subscriber. + + The service that an application uses to manipulate subscriptions and + to consume messages from a subscription via the ``Pull`` method or + by establishing a bi-directional stream using the ``StreamingPull`` + method. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "pubsub.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'pubsub.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ("grpc.max_metadata_size", 4 * 1024 * 1024), + ("grpc.keepalive_time_ms", 30000), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "pubsub.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def create_subscription( + self, + ) -> Callable[[pubsub.Subscription], pubsub.Subscription]: + r"""Return a callable for the create subscription method over gRPC. + + Creates a subscription to a given topic. See the [resource name + rules] + (https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names). + If the subscription already exists, returns ``ALREADY_EXISTS``. + If the corresponding topic doesn't exist, returns ``NOT_FOUND``. + + If the name is not provided in the request, the server will + assign a random name for this subscription on the same project + as the topic, conforming to the [resource name format] + (https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names). + The generated name is populated in the returned Subscription + object. Note that for REST API requests, you must specify a name + in the request. + + Returns: + Callable[[~.Subscription], + ~.Subscription]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_subscription" not in self._stubs: + self._stubs["create_subscription"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Subscriber/CreateSubscription", + request_serializer=pubsub.Subscription.serialize, + response_deserializer=pubsub.Subscription.deserialize, + ) + return self._stubs["create_subscription"] + + @property + def get_subscription( + self, + ) -> Callable[[pubsub.GetSubscriptionRequest], pubsub.Subscription]: + r"""Return a callable for the get subscription method over gRPC. + + Gets the configuration details of a subscription. + + Returns: + Callable[[~.GetSubscriptionRequest], + ~.Subscription]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_subscription" not in self._stubs: + self._stubs["get_subscription"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Subscriber/GetSubscription", + request_serializer=pubsub.GetSubscriptionRequest.serialize, + response_deserializer=pubsub.Subscription.deserialize, + ) + return self._stubs["get_subscription"] + + @property + def update_subscription( + self, + ) -> Callable[[pubsub.UpdateSubscriptionRequest], pubsub.Subscription]: + r"""Return a callable for the update subscription method over gRPC. + + Updates an existing subscription by updating the + fields specified in the update mask. Note that certain + properties of a subscription, such as its topic, are not + modifiable. + + Returns: + Callable[[~.UpdateSubscriptionRequest], + ~.Subscription]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_subscription" not in self._stubs: + self._stubs["update_subscription"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Subscriber/UpdateSubscription", + request_serializer=pubsub.UpdateSubscriptionRequest.serialize, + response_deserializer=pubsub.Subscription.deserialize, + ) + return self._stubs["update_subscription"] + + @property + def list_subscriptions( + self, + ) -> Callable[[pubsub.ListSubscriptionsRequest], pubsub.ListSubscriptionsResponse]: + r"""Return a callable for the list subscriptions method over gRPC. + + Lists matching subscriptions. + + Returns: + Callable[[~.ListSubscriptionsRequest], + ~.ListSubscriptionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_subscriptions" not in self._stubs: + self._stubs["list_subscriptions"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Subscriber/ListSubscriptions", + request_serializer=pubsub.ListSubscriptionsRequest.serialize, + response_deserializer=pubsub.ListSubscriptionsResponse.deserialize, + ) + return self._stubs["list_subscriptions"] + + @property + def delete_subscription( + self, + ) -> Callable[[pubsub.DeleteSubscriptionRequest], empty_pb2.Empty]: + r"""Return a callable for the delete subscription method over gRPC. + + Deletes an existing subscription. All messages retained in the + subscription are immediately dropped. Calls to ``Pull`` after + deletion will return ``NOT_FOUND``. After a subscription is + deleted, a new one may be created with the same name, but the + new one has no association with the old subscription or its + topic unless the same topic is specified. + + Returns: + Callable[[~.DeleteSubscriptionRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_subscription" not in self._stubs: + self._stubs["delete_subscription"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Subscriber/DeleteSubscription", + request_serializer=pubsub.DeleteSubscriptionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_subscription"] + + @property + def modify_ack_deadline( + self, + ) -> Callable[[pubsub.ModifyAckDeadlineRequest], empty_pb2.Empty]: + r"""Return a callable for the modify ack deadline method over gRPC. + + Modifies the ack deadline for a specific message. This method is + useful to indicate that more time is needed to process a message + by the subscriber, or to make the message available for + redelivery if the processing was interrupted. Note that this + does not modify the subscription-level ``ackDeadlineSeconds`` + used for subsequent messages. + + Returns: + Callable[[~.ModifyAckDeadlineRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "modify_ack_deadline" not in self._stubs: + self._stubs["modify_ack_deadline"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Subscriber/ModifyAckDeadline", + request_serializer=pubsub.ModifyAckDeadlineRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["modify_ack_deadline"] + + @property + def acknowledge(self) -> Callable[[pubsub.AcknowledgeRequest], empty_pb2.Empty]: + r"""Return a callable for the acknowledge method over gRPC. + + Acknowledges the messages associated with the ``ack_ids`` in the + ``AcknowledgeRequest``. The Pub/Sub system can remove the + relevant messages from the subscription. + + Acknowledging a message whose ack deadline has expired may + succeed, but such a message may be redelivered later. + Acknowledging a message more than once will not result in an + error. + + Returns: + Callable[[~.AcknowledgeRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "acknowledge" not in self._stubs: + self._stubs["acknowledge"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Subscriber/Acknowledge", + request_serializer=pubsub.AcknowledgeRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["acknowledge"] + + @property + def pull(self) -> Callable[[pubsub.PullRequest], pubsub.PullResponse]: + r"""Return a callable for the pull method over gRPC. + + Pulls messages from the server. + + Returns: + Callable[[~.PullRequest], + ~.PullResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "pull" not in self._stubs: + self._stubs["pull"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Subscriber/Pull", + request_serializer=pubsub.PullRequest.serialize, + response_deserializer=pubsub.PullResponse.deserialize, + ) + return self._stubs["pull"] + + @property + def streaming_pull( + self, + ) -> Callable[[pubsub.StreamingPullRequest], pubsub.StreamingPullResponse]: + r"""Return a callable for the streaming pull method over gRPC. + + Establishes a stream with the server, which sends messages down + to the client. The client streams acknowledgments and ack + deadline modifications back to the server. The server will close + the stream and return the status on any error. The server may + close the stream with status ``UNAVAILABLE`` to reassign + server-side resources, in which case, the client should + re-establish the stream. Flow control can be achieved by + configuring the underlying RPC channel. + + Returns: + Callable[[~.StreamingPullRequest], + ~.StreamingPullResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "streaming_pull" not in self._stubs: + self._stubs["streaming_pull"] = self._logged_channel.stream_stream( + "/google.pubsub.v1.Subscriber/StreamingPull", + request_serializer=pubsub.StreamingPullRequest.serialize, + response_deserializer=pubsub.StreamingPullResponse.deserialize, + ) + return self._stubs["streaming_pull"] + + @property + def modify_push_config( + self, + ) -> Callable[[pubsub.ModifyPushConfigRequest], empty_pb2.Empty]: + r"""Return a callable for the modify push config method over gRPC. + + Modifies the ``PushConfig`` for a specified subscription. + + This may be used to change a push subscription to a pull one + (signified by an empty ``PushConfig``) or vice versa, or change + the endpoint URL and other attributes of a push subscription. + Messages will accumulate for delivery continuously through the + call regardless of changes to the ``PushConfig``. + + Returns: + Callable[[~.ModifyPushConfigRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "modify_push_config" not in self._stubs: + self._stubs["modify_push_config"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Subscriber/ModifyPushConfig", + request_serializer=pubsub.ModifyPushConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["modify_push_config"] + + @property + def get_snapshot(self) -> Callable[[pubsub.GetSnapshotRequest], pubsub.Snapshot]: + r"""Return a callable for the get snapshot method over gRPC. + + Gets the configuration details of a snapshot. Snapshots are used + in + `Seek `__ + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + + Returns: + Callable[[~.GetSnapshotRequest], + ~.Snapshot]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_snapshot" not in self._stubs: + self._stubs["get_snapshot"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Subscriber/GetSnapshot", + request_serializer=pubsub.GetSnapshotRequest.serialize, + response_deserializer=pubsub.Snapshot.deserialize, + ) + return self._stubs["get_snapshot"] + + @property + def list_snapshots( + self, + ) -> Callable[[pubsub.ListSnapshotsRequest], pubsub.ListSnapshotsResponse]: + r"""Return a callable for the list snapshots method over gRPC. + + Lists the existing snapshots. Snapshots are used in + `Seek `__ + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + + Returns: + Callable[[~.ListSnapshotsRequest], + ~.ListSnapshotsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_snapshots" not in self._stubs: + self._stubs["list_snapshots"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Subscriber/ListSnapshots", + request_serializer=pubsub.ListSnapshotsRequest.serialize, + response_deserializer=pubsub.ListSnapshotsResponse.deserialize, + ) + return self._stubs["list_snapshots"] + + @property + def create_snapshot( + self, + ) -> Callable[[pubsub.CreateSnapshotRequest], pubsub.Snapshot]: + r"""Return a callable for the create snapshot method over gRPC. + + Creates a snapshot from the requested subscription. Snapshots + are used in + `Seek `__ + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + If the snapshot already exists, returns ``ALREADY_EXISTS``. If + the requested subscription doesn't exist, returns ``NOT_FOUND``. + If the backlog in the subscription is too old -- and the + resulting snapshot would expire in less than 1 hour -- then + ``FAILED_PRECONDITION`` is returned. See also the + ``Snapshot.expire_time`` field. If the name is not provided in + the request, the server will assign a random name for this + snapshot on the same project as the subscription, conforming to + the [resource name format] + (https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names). + The generated name is populated in the returned Snapshot object. + Note that for REST API requests, you must specify a name in the + request. + + Returns: + Callable[[~.CreateSnapshotRequest], + ~.Snapshot]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_snapshot" not in self._stubs: + self._stubs["create_snapshot"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Subscriber/CreateSnapshot", + request_serializer=pubsub.CreateSnapshotRequest.serialize, + response_deserializer=pubsub.Snapshot.deserialize, + ) + return self._stubs["create_snapshot"] + + @property + def update_snapshot( + self, + ) -> Callable[[pubsub.UpdateSnapshotRequest], pubsub.Snapshot]: + r"""Return a callable for the update snapshot method over gRPC. + + Updates an existing snapshot by updating the fields specified in + the update mask. Snapshots are used in + `Seek `__ + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + + Returns: + Callable[[~.UpdateSnapshotRequest], + ~.Snapshot]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_snapshot" not in self._stubs: + self._stubs["update_snapshot"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Subscriber/UpdateSnapshot", + request_serializer=pubsub.UpdateSnapshotRequest.serialize, + response_deserializer=pubsub.Snapshot.deserialize, + ) + return self._stubs["update_snapshot"] + + @property + def delete_snapshot( + self, + ) -> Callable[[pubsub.DeleteSnapshotRequest], empty_pb2.Empty]: + r"""Return a callable for the delete snapshot method over gRPC. + + Removes an existing snapshot. Snapshots are used in [Seek] + (https://cloud.google.com/pubsub/docs/replay-overview) + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + When the snapshot is deleted, all messages retained in the + snapshot are immediately dropped. After a snapshot is deleted, a + new one may be created with the same name, but the new one has + no association with the old snapshot or its subscription, unless + the same subscription is specified. + + Returns: + Callable[[~.DeleteSnapshotRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_snapshot" not in self._stubs: + self._stubs["delete_snapshot"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Subscriber/DeleteSnapshot", + request_serializer=pubsub.DeleteSnapshotRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_snapshot"] + + @property + def seek(self) -> Callable[[pubsub.SeekRequest], pubsub.SeekResponse]: + r"""Return a callable for the seek method over gRPC. + + Seeks an existing subscription to a point in time or to a given + snapshot, whichever is provided in the request. Snapshots are + used in [Seek] + (https://cloud.google.com/pubsub/docs/replay-overview) + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + Note that both the subscription and the snapshot must be on the + same topic. + + Returns: + Callable[[~.SeekRequest], + ~.SeekResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "seek" not in self._stubs: + self._stubs["seek"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Subscriber/Seek", + request_serializer=pubsub.SeekRequest.serialize, + response_deserializer=pubsub.SeekResponse.deserialize, + ) + return self._stubs["seek"] + + def close(self): + self._logged_channel.close() + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("SubscriberGrpcTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py new file mode 100644 index 0000000000000000000000000000000000000000..608398e2105d70468dfd96a4e8f7faa6f564743c --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/subscriber/transports/grpc_asyncio.py @@ -0,0 +1,1214 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed 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. +# +import inspect +import json +import logging as std_logging +import pickle +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.protobuf.json_format import MessageToJson +from grpc.experimental import aio # type: ignore + +from google.pubsub_v1.types import pubsub + +from .base import DEFAULT_CLIENT_INFO, SubscriberTransport +from .grpc import SubscriberGrpcTransport + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.pubsub.v1.Subscriber", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.pubsub.v1.Subscriber", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class SubscriberGrpcAsyncIOTransport(SubscriberTransport): + """gRPC AsyncIO backend transport for Subscriber. + + The service that an application uses to manipulate subscriptions and + to consume messages from a subscription via the ``Pull`` method or + by establishing a bi-directional stream using the ``StreamingPull`` + method. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "pubsub.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "pubsub.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'pubsub.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ("grpc.max_metadata_size", 4 * 1024 * 1024), + ("grpc.keepalive_time_ms", 30000), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_subscription( + self, + ) -> Callable[[pubsub.Subscription], Awaitable[pubsub.Subscription]]: + r"""Return a callable for the create subscription method over gRPC. + + Creates a subscription to a given topic. See the [resource name + rules] + (https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names). + If the subscription already exists, returns ``ALREADY_EXISTS``. + If the corresponding topic doesn't exist, returns ``NOT_FOUND``. + + If the name is not provided in the request, the server will + assign a random name for this subscription on the same project + as the topic, conforming to the [resource name format] + (https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names). + The generated name is populated in the returned Subscription + object. Note that for REST API requests, you must specify a name + in the request. + + Returns: + Callable[[~.Subscription], + Awaitable[~.Subscription]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_subscription" not in self._stubs: + self._stubs["create_subscription"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Subscriber/CreateSubscription", + request_serializer=pubsub.Subscription.serialize, + response_deserializer=pubsub.Subscription.deserialize, + ) + return self._stubs["create_subscription"] + + @property + def get_subscription( + self, + ) -> Callable[[pubsub.GetSubscriptionRequest], Awaitable[pubsub.Subscription]]: + r"""Return a callable for the get subscription method over gRPC. + + Gets the configuration details of a subscription. + + Returns: + Callable[[~.GetSubscriptionRequest], + Awaitable[~.Subscription]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_subscription" not in self._stubs: + self._stubs["get_subscription"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Subscriber/GetSubscription", + request_serializer=pubsub.GetSubscriptionRequest.serialize, + response_deserializer=pubsub.Subscription.deserialize, + ) + return self._stubs["get_subscription"] + + @property + def update_subscription( + self, + ) -> Callable[[pubsub.UpdateSubscriptionRequest], Awaitable[pubsub.Subscription]]: + r"""Return a callable for the update subscription method over gRPC. + + Updates an existing subscription by updating the + fields specified in the update mask. Note that certain + properties of a subscription, such as its topic, are not + modifiable. + + Returns: + Callable[[~.UpdateSubscriptionRequest], + Awaitable[~.Subscription]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_subscription" not in self._stubs: + self._stubs["update_subscription"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Subscriber/UpdateSubscription", + request_serializer=pubsub.UpdateSubscriptionRequest.serialize, + response_deserializer=pubsub.Subscription.deserialize, + ) + return self._stubs["update_subscription"] + + @property + def list_subscriptions( + self, + ) -> Callable[ + [pubsub.ListSubscriptionsRequest], Awaitable[pubsub.ListSubscriptionsResponse] + ]: + r"""Return a callable for the list subscriptions method over gRPC. + + Lists matching subscriptions. + + Returns: + Callable[[~.ListSubscriptionsRequest], + Awaitable[~.ListSubscriptionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_subscriptions" not in self._stubs: + self._stubs["list_subscriptions"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Subscriber/ListSubscriptions", + request_serializer=pubsub.ListSubscriptionsRequest.serialize, + response_deserializer=pubsub.ListSubscriptionsResponse.deserialize, + ) + return self._stubs["list_subscriptions"] + + @property + def delete_subscription( + self, + ) -> Callable[[pubsub.DeleteSubscriptionRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete subscription method over gRPC. + + Deletes an existing subscription. All messages retained in the + subscription are immediately dropped. Calls to ``Pull`` after + deletion will return ``NOT_FOUND``. After a subscription is + deleted, a new one may be created with the same name, but the + new one has no association with the old subscription or its + topic unless the same topic is specified. + + Returns: + Callable[[~.DeleteSubscriptionRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_subscription" not in self._stubs: + self._stubs["delete_subscription"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Subscriber/DeleteSubscription", + request_serializer=pubsub.DeleteSubscriptionRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_subscription"] + + @property + def modify_ack_deadline( + self, + ) -> Callable[[pubsub.ModifyAckDeadlineRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the modify ack deadline method over gRPC. + + Modifies the ack deadline for a specific message. This method is + useful to indicate that more time is needed to process a message + by the subscriber, or to make the message available for + redelivery if the processing was interrupted. Note that this + does not modify the subscription-level ``ackDeadlineSeconds`` + used for subsequent messages. + + Returns: + Callable[[~.ModifyAckDeadlineRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "modify_ack_deadline" not in self._stubs: + self._stubs["modify_ack_deadline"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Subscriber/ModifyAckDeadline", + request_serializer=pubsub.ModifyAckDeadlineRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["modify_ack_deadline"] + + @property + def acknowledge( + self, + ) -> Callable[[pubsub.AcknowledgeRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the acknowledge method over gRPC. + + Acknowledges the messages associated with the ``ack_ids`` in the + ``AcknowledgeRequest``. The Pub/Sub system can remove the + relevant messages from the subscription. + + Acknowledging a message whose ack deadline has expired may + succeed, but such a message may be redelivered later. + Acknowledging a message more than once will not result in an + error. + + Returns: + Callable[[~.AcknowledgeRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "acknowledge" not in self._stubs: + self._stubs["acknowledge"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Subscriber/Acknowledge", + request_serializer=pubsub.AcknowledgeRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["acknowledge"] + + @property + def pull(self) -> Callable[[pubsub.PullRequest], Awaitable[pubsub.PullResponse]]: + r"""Return a callable for the pull method over gRPC. + + Pulls messages from the server. + + Returns: + Callable[[~.PullRequest], + Awaitable[~.PullResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "pull" not in self._stubs: + self._stubs["pull"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Subscriber/Pull", + request_serializer=pubsub.PullRequest.serialize, + response_deserializer=pubsub.PullResponse.deserialize, + ) + return self._stubs["pull"] + + @property + def streaming_pull( + self, + ) -> Callable[ + [pubsub.StreamingPullRequest], Awaitable[pubsub.StreamingPullResponse] + ]: + r"""Return a callable for the streaming pull method over gRPC. + + Establishes a stream with the server, which sends messages down + to the client. The client streams acknowledgments and ack + deadline modifications back to the server. The server will close + the stream and return the status on any error. The server may + close the stream with status ``UNAVAILABLE`` to reassign + server-side resources, in which case, the client should + re-establish the stream. Flow control can be achieved by + configuring the underlying RPC channel. + + Returns: + Callable[[~.StreamingPullRequest], + Awaitable[~.StreamingPullResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "streaming_pull" not in self._stubs: + self._stubs["streaming_pull"] = self._logged_channel.stream_stream( + "/google.pubsub.v1.Subscriber/StreamingPull", + request_serializer=pubsub.StreamingPullRequest.serialize, + response_deserializer=pubsub.StreamingPullResponse.deserialize, + ) + return self._stubs["streaming_pull"] + + @property + def modify_push_config( + self, + ) -> Callable[[pubsub.ModifyPushConfigRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the modify push config method over gRPC. + + Modifies the ``PushConfig`` for a specified subscription. + + This may be used to change a push subscription to a pull one + (signified by an empty ``PushConfig``) or vice versa, or change + the endpoint URL and other attributes of a push subscription. + Messages will accumulate for delivery continuously through the + call regardless of changes to the ``PushConfig``. + + Returns: + Callable[[~.ModifyPushConfigRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "modify_push_config" not in self._stubs: + self._stubs["modify_push_config"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Subscriber/ModifyPushConfig", + request_serializer=pubsub.ModifyPushConfigRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["modify_push_config"] + + @property + def get_snapshot( + self, + ) -> Callable[[pubsub.GetSnapshotRequest], Awaitable[pubsub.Snapshot]]: + r"""Return a callable for the get snapshot method over gRPC. + + Gets the configuration details of a snapshot. Snapshots are used + in + `Seek `__ + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + + Returns: + Callable[[~.GetSnapshotRequest], + Awaitable[~.Snapshot]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_snapshot" not in self._stubs: + self._stubs["get_snapshot"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Subscriber/GetSnapshot", + request_serializer=pubsub.GetSnapshotRequest.serialize, + response_deserializer=pubsub.Snapshot.deserialize, + ) + return self._stubs["get_snapshot"] + + @property + def list_snapshots( + self, + ) -> Callable[ + [pubsub.ListSnapshotsRequest], Awaitable[pubsub.ListSnapshotsResponse] + ]: + r"""Return a callable for the list snapshots method over gRPC. + + Lists the existing snapshots. Snapshots are used in + `Seek `__ + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + + Returns: + Callable[[~.ListSnapshotsRequest], + Awaitable[~.ListSnapshotsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_snapshots" not in self._stubs: + self._stubs["list_snapshots"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Subscriber/ListSnapshots", + request_serializer=pubsub.ListSnapshotsRequest.serialize, + response_deserializer=pubsub.ListSnapshotsResponse.deserialize, + ) + return self._stubs["list_snapshots"] + + @property + def create_snapshot( + self, + ) -> Callable[[pubsub.CreateSnapshotRequest], Awaitable[pubsub.Snapshot]]: + r"""Return a callable for the create snapshot method over gRPC. + + Creates a snapshot from the requested subscription. Snapshots + are used in + `Seek `__ + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + If the snapshot already exists, returns ``ALREADY_EXISTS``. If + the requested subscription doesn't exist, returns ``NOT_FOUND``. + If the backlog in the subscription is too old -- and the + resulting snapshot would expire in less than 1 hour -- then + ``FAILED_PRECONDITION`` is returned. See also the + ``Snapshot.expire_time`` field. If the name is not provided in + the request, the server will assign a random name for this + snapshot on the same project as the subscription, conforming to + the [resource name format] + (https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names). + The generated name is populated in the returned Snapshot object. + Note that for REST API requests, you must specify a name in the + request. + + Returns: + Callable[[~.CreateSnapshotRequest], + Awaitable[~.Snapshot]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_snapshot" not in self._stubs: + self._stubs["create_snapshot"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Subscriber/CreateSnapshot", + request_serializer=pubsub.CreateSnapshotRequest.serialize, + response_deserializer=pubsub.Snapshot.deserialize, + ) + return self._stubs["create_snapshot"] + + @property + def update_snapshot( + self, + ) -> Callable[[pubsub.UpdateSnapshotRequest], Awaitable[pubsub.Snapshot]]: + r"""Return a callable for the update snapshot method over gRPC. + + Updates an existing snapshot by updating the fields specified in + the update mask. Snapshots are used in + `Seek `__ + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + + Returns: + Callable[[~.UpdateSnapshotRequest], + Awaitable[~.Snapshot]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_snapshot" not in self._stubs: + self._stubs["update_snapshot"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Subscriber/UpdateSnapshot", + request_serializer=pubsub.UpdateSnapshotRequest.serialize, + response_deserializer=pubsub.Snapshot.deserialize, + ) + return self._stubs["update_snapshot"] + + @property + def delete_snapshot( + self, + ) -> Callable[[pubsub.DeleteSnapshotRequest], Awaitable[empty_pb2.Empty]]: + r"""Return a callable for the delete snapshot method over gRPC. + + Removes an existing snapshot. Snapshots are used in [Seek] + (https://cloud.google.com/pubsub/docs/replay-overview) + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + When the snapshot is deleted, all messages retained in the + snapshot are immediately dropped. After a snapshot is deleted, a + new one may be created with the same name, but the new one has + no association with the old snapshot or its subscription, unless + the same subscription is specified. + + Returns: + Callable[[~.DeleteSnapshotRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_snapshot" not in self._stubs: + self._stubs["delete_snapshot"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Subscriber/DeleteSnapshot", + request_serializer=pubsub.DeleteSnapshotRequest.serialize, + response_deserializer=empty_pb2.Empty.FromString, + ) + return self._stubs["delete_snapshot"] + + @property + def seek(self) -> Callable[[pubsub.SeekRequest], Awaitable[pubsub.SeekResponse]]: + r"""Return a callable for the seek method over gRPC. + + Seeks an existing subscription to a point in time or to a given + snapshot, whichever is provided in the request. Snapshots are + used in [Seek] + (https://cloud.google.com/pubsub/docs/replay-overview) + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages + in an existing subscription to the state captured by a snapshot. + Note that both the subscription and the snapshot must be on the + same topic. + + Returns: + Callable[[~.SeekRequest], + Awaitable[~.SeekResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "seek" not in self._stubs: + self._stubs["seek"] = self._logged_channel.unary_unary( + "/google.pubsub.v1.Subscriber/Seek", + request_serializer=pubsub.SeekRequest.serialize, + response_deserializer=pubsub.SeekResponse.deserialize, + ) + return self._stubs["seek"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.create_subscription: self._wrap_method( + self.create_subscription, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_subscription: self._wrap_method( + self.get_subscription, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_subscription: self._wrap_method( + self.update_subscription, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_subscriptions: self._wrap_method( + self.list_subscriptions, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_subscription: self._wrap_method( + self.delete_subscription, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.modify_ack_deadline: self._wrap_method( + self.modify_ack_deadline, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.acknowledge: self._wrap_method( + self.acknowledge, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.pull: self._wrap_method( + self.pull, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.InternalServerError, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.streaming_pull: self._wrap_method( + self.streaming_pull, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=4, + predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.DeadlineExceeded, + core_exceptions.InternalServerError, + core_exceptions.ResourceExhausted, + core_exceptions.ServiceUnavailable, + ), + deadline=900.0, + ), + default_timeout=900.0, + client_info=client_info, + ), + self.modify_push_config: self._wrap_method( + self.modify_push_config, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_snapshot: self._wrap_method( + self.get_snapshot, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_snapshots: self._wrap_method( + self.list_snapshots, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_snapshot: self._wrap_method( + self.create_snapshot, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_snapshot: self._wrap_method( + self.update_snapshot, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_snapshot: self._wrap_method( + self.delete_snapshot, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.seek: self._wrap_method( + self.seek, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.Aborted, + core_exceptions.ServiceUnavailable, + core_exceptions.Unknown, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_iam_policy: self._wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: self._wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: self._wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ("SubscriberGrpcAsyncIOTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/subscriber/transports/rest.py b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/subscriber/transports/rest.py new file mode 100644 index 0000000000000000000000000000000000000000..04977a781db0493b2ae950a40d593d92d4b0f7a4 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/subscriber/transports/rest.py @@ -0,0 +1,3564 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed 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. +# +import dataclasses +import json # type: ignore +import logging +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.pubsub_v1.types import pubsub + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseSubscriberRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class SubscriberRestInterceptor: + """Interceptor for Subscriber. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the SubscriberRestTransport. + + .. code-block:: python + class MyCustomSubscriberInterceptor(SubscriberRestInterceptor): + def pre_acknowledge(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_create_snapshot(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_snapshot(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_subscription(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_subscription(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_snapshot(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_subscription(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_snapshot(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_snapshot(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_subscription(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_subscription(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_snapshots(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_snapshots(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_subscriptions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_subscriptions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_modify_ack_deadline(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_modify_push_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_pull(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_pull(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_seek(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_seek(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_snapshot(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_snapshot(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_subscription(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_subscription(self, response): + logging.log(f"Received response: {response}") + return response + + transport = SubscriberRestTransport(interceptor=MyCustomSubscriberInterceptor()) + client = SubscriberClient(transport=transport) + + + """ + + def pre_acknowledge( + self, + request: pubsub.AcknowledgeRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[pubsub.AcknowledgeRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for acknowledge + + Override in a subclass to manipulate the request or metadata + before they are sent to the Subscriber server. + """ + return request, metadata + + def pre_create_snapshot( + self, + request: pubsub.CreateSnapshotRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[pubsub.CreateSnapshotRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_snapshot + + Override in a subclass to manipulate the request or metadata + before they are sent to the Subscriber server. + """ + return request, metadata + + def post_create_snapshot(self, response: pubsub.Snapshot) -> pubsub.Snapshot: + """Post-rpc interceptor for create_snapshot + + DEPRECATED. Please use the `post_create_snapshot_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Subscriber server but before + it is returned to user code. This `post_create_snapshot` interceptor runs + before the `post_create_snapshot_with_metadata` interceptor. + """ + return response + + def post_create_snapshot_with_metadata( + self, + response: pubsub.Snapshot, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[pubsub.Snapshot, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_snapshot + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Subscriber server but before it is returned to user code. + + We recommend only using this `post_create_snapshot_with_metadata` + interceptor in new development instead of the `post_create_snapshot` interceptor. + When both interceptors are used, this `post_create_snapshot_with_metadata` interceptor runs after the + `post_create_snapshot` interceptor. The (possibly modified) response returned by + `post_create_snapshot` will be passed to + `post_create_snapshot_with_metadata`. + """ + return response, metadata + + def pre_create_subscription( + self, + request: pubsub.Subscription, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[pubsub.Subscription, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for create_subscription + + Override in a subclass to manipulate the request or metadata + before they are sent to the Subscriber server. + """ + return request, metadata + + def post_create_subscription( + self, response: pubsub.Subscription + ) -> pubsub.Subscription: + """Post-rpc interceptor for create_subscription + + DEPRECATED. Please use the `post_create_subscription_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Subscriber server but before + it is returned to user code. This `post_create_subscription` interceptor runs + before the `post_create_subscription_with_metadata` interceptor. + """ + return response + + def post_create_subscription_with_metadata( + self, + response: pubsub.Subscription, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[pubsub.Subscription, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_subscription + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Subscriber server but before it is returned to user code. + + We recommend only using this `post_create_subscription_with_metadata` + interceptor in new development instead of the `post_create_subscription` interceptor. + When both interceptors are used, this `post_create_subscription_with_metadata` interceptor runs after the + `post_create_subscription` interceptor. The (possibly modified) response returned by + `post_create_subscription` will be passed to + `post_create_subscription_with_metadata`. + """ + return response, metadata + + def pre_delete_snapshot( + self, + request: pubsub.DeleteSnapshotRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[pubsub.DeleteSnapshotRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for delete_snapshot + + Override in a subclass to manipulate the request or metadata + before they are sent to the Subscriber server. + """ + return request, metadata + + def pre_delete_subscription( + self, + request: pubsub.DeleteSubscriptionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + pubsub.DeleteSubscriptionRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_subscription + + Override in a subclass to manipulate the request or metadata + before they are sent to the Subscriber server. + """ + return request, metadata + + def pre_get_snapshot( + self, + request: pubsub.GetSnapshotRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[pubsub.GetSnapshotRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_snapshot + + Override in a subclass to manipulate the request or metadata + before they are sent to the Subscriber server. + """ + return request, metadata + + def post_get_snapshot(self, response: pubsub.Snapshot) -> pubsub.Snapshot: + """Post-rpc interceptor for get_snapshot + + DEPRECATED. Please use the `post_get_snapshot_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Subscriber server but before + it is returned to user code. This `post_get_snapshot` interceptor runs + before the `post_get_snapshot_with_metadata` interceptor. + """ + return response + + def post_get_snapshot_with_metadata( + self, + response: pubsub.Snapshot, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[pubsub.Snapshot, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_snapshot + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Subscriber server but before it is returned to user code. + + We recommend only using this `post_get_snapshot_with_metadata` + interceptor in new development instead of the `post_get_snapshot` interceptor. + When both interceptors are used, this `post_get_snapshot_with_metadata` interceptor runs after the + `post_get_snapshot` interceptor. The (possibly modified) response returned by + `post_get_snapshot` will be passed to + `post_get_snapshot_with_metadata`. + """ + return response, metadata + + def pre_get_subscription( + self, + request: pubsub.GetSubscriptionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[pubsub.GetSubscriptionRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_subscription + + Override in a subclass to manipulate the request or metadata + before they are sent to the Subscriber server. + """ + return request, metadata + + def post_get_subscription( + self, response: pubsub.Subscription + ) -> pubsub.Subscription: + """Post-rpc interceptor for get_subscription + + DEPRECATED. Please use the `post_get_subscription_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Subscriber server but before + it is returned to user code. This `post_get_subscription` interceptor runs + before the `post_get_subscription_with_metadata` interceptor. + """ + return response + + def post_get_subscription_with_metadata( + self, + response: pubsub.Subscription, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[pubsub.Subscription, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_subscription + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Subscriber server but before it is returned to user code. + + We recommend only using this `post_get_subscription_with_metadata` + interceptor in new development instead of the `post_get_subscription` interceptor. + When both interceptors are used, this `post_get_subscription_with_metadata` interceptor runs after the + `post_get_subscription` interceptor. The (possibly modified) response returned by + `post_get_subscription` will be passed to + `post_get_subscription_with_metadata`. + """ + return response, metadata + + def pre_list_snapshots( + self, + request: pubsub.ListSnapshotsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[pubsub.ListSnapshotsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_snapshots + + Override in a subclass to manipulate the request or metadata + before they are sent to the Subscriber server. + """ + return request, metadata + + def post_list_snapshots( + self, response: pubsub.ListSnapshotsResponse + ) -> pubsub.ListSnapshotsResponse: + """Post-rpc interceptor for list_snapshots + + DEPRECATED. Please use the `post_list_snapshots_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Subscriber server but before + it is returned to user code. This `post_list_snapshots` interceptor runs + before the `post_list_snapshots_with_metadata` interceptor. + """ + return response + + def post_list_snapshots_with_metadata( + self, + response: pubsub.ListSnapshotsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[pubsub.ListSnapshotsResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_snapshots + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Subscriber server but before it is returned to user code. + + We recommend only using this `post_list_snapshots_with_metadata` + interceptor in new development instead of the `post_list_snapshots` interceptor. + When both interceptors are used, this `post_list_snapshots_with_metadata` interceptor runs after the + `post_list_snapshots` interceptor. The (possibly modified) response returned by + `post_list_snapshots` will be passed to + `post_list_snapshots_with_metadata`. + """ + return response, metadata + + def pre_list_subscriptions( + self, + request: pubsub.ListSubscriptionsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + pubsub.ListSubscriptionsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_subscriptions + + Override in a subclass to manipulate the request or metadata + before they are sent to the Subscriber server. + """ + return request, metadata + + def post_list_subscriptions( + self, response: pubsub.ListSubscriptionsResponse + ) -> pubsub.ListSubscriptionsResponse: + """Post-rpc interceptor for list_subscriptions + + DEPRECATED. Please use the `post_list_subscriptions_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Subscriber server but before + it is returned to user code. This `post_list_subscriptions` interceptor runs + before the `post_list_subscriptions_with_metadata` interceptor. + """ + return response + + def post_list_subscriptions_with_metadata( + self, + response: pubsub.ListSubscriptionsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + pubsub.ListSubscriptionsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_subscriptions + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Subscriber server but before it is returned to user code. + + We recommend only using this `post_list_subscriptions_with_metadata` + interceptor in new development instead of the `post_list_subscriptions` interceptor. + When both interceptors are used, this `post_list_subscriptions_with_metadata` interceptor runs after the + `post_list_subscriptions` interceptor. The (possibly modified) response returned by + `post_list_subscriptions` will be passed to + `post_list_subscriptions_with_metadata`. + """ + return response, metadata + + def pre_modify_ack_deadline( + self, + request: pubsub.ModifyAckDeadlineRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + pubsub.ModifyAckDeadlineRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for modify_ack_deadline + + Override in a subclass to manipulate the request or metadata + before they are sent to the Subscriber server. + """ + return request, metadata + + def pre_modify_push_config( + self, + request: pubsub.ModifyPushConfigRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[pubsub.ModifyPushConfigRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for modify_push_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the Subscriber server. + """ + return request, metadata + + def pre_pull( + self, + request: pubsub.PullRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[pubsub.PullRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for pull + + Override in a subclass to manipulate the request or metadata + before they are sent to the Subscriber server. + """ + return request, metadata + + def post_pull(self, response: pubsub.PullResponse) -> pubsub.PullResponse: + """Post-rpc interceptor for pull + + DEPRECATED. Please use the `post_pull_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Subscriber server but before + it is returned to user code. This `post_pull` interceptor runs + before the `post_pull_with_metadata` interceptor. + """ + return response + + def post_pull_with_metadata( + self, + response: pubsub.PullResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[pubsub.PullResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for pull + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Subscriber server but before it is returned to user code. + + We recommend only using this `post_pull_with_metadata` + interceptor in new development instead of the `post_pull` interceptor. + When both interceptors are used, this `post_pull_with_metadata` interceptor runs after the + `post_pull` interceptor. The (possibly modified) response returned by + `post_pull` will be passed to + `post_pull_with_metadata`. + """ + return response, metadata + + def pre_seek( + self, + request: pubsub.SeekRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[pubsub.SeekRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for seek + + Override in a subclass to manipulate the request or metadata + before they are sent to the Subscriber server. + """ + return request, metadata + + def post_seek(self, response: pubsub.SeekResponse) -> pubsub.SeekResponse: + """Post-rpc interceptor for seek + + DEPRECATED. Please use the `post_seek_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Subscriber server but before + it is returned to user code. This `post_seek` interceptor runs + before the `post_seek_with_metadata` interceptor. + """ + return response + + def post_seek_with_metadata( + self, + response: pubsub.SeekResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[pubsub.SeekResponse, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for seek + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Subscriber server but before it is returned to user code. + + We recommend only using this `post_seek_with_metadata` + interceptor in new development instead of the `post_seek` interceptor. + When both interceptors are used, this `post_seek_with_metadata` interceptor runs after the + `post_seek` interceptor. The (possibly modified) response returned by + `post_seek` will be passed to + `post_seek_with_metadata`. + """ + return response, metadata + + def pre_update_snapshot( + self, + request: pubsub.UpdateSnapshotRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[pubsub.UpdateSnapshotRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for update_snapshot + + Override in a subclass to manipulate the request or metadata + before they are sent to the Subscriber server. + """ + return request, metadata + + def post_update_snapshot(self, response: pubsub.Snapshot) -> pubsub.Snapshot: + """Post-rpc interceptor for update_snapshot + + DEPRECATED. Please use the `post_update_snapshot_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Subscriber server but before + it is returned to user code. This `post_update_snapshot` interceptor runs + before the `post_update_snapshot_with_metadata` interceptor. + """ + return response + + def post_update_snapshot_with_metadata( + self, + response: pubsub.Snapshot, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[pubsub.Snapshot, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_snapshot + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Subscriber server but before it is returned to user code. + + We recommend only using this `post_update_snapshot_with_metadata` + interceptor in new development instead of the `post_update_snapshot` interceptor. + When both interceptors are used, this `post_update_snapshot_with_metadata` interceptor runs after the + `post_update_snapshot` interceptor. The (possibly modified) response returned by + `post_update_snapshot` will be passed to + `post_update_snapshot_with_metadata`. + """ + return response, metadata + + def pre_update_subscription( + self, + request: pubsub.UpdateSubscriptionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + pubsub.UpdateSubscriptionRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_subscription + + Override in a subclass to manipulate the request or metadata + before they are sent to the Subscriber server. + """ + return request, metadata + + def post_update_subscription( + self, response: pubsub.Subscription + ) -> pubsub.Subscription: + """Post-rpc interceptor for update_subscription + + DEPRECATED. Please use the `post_update_subscription_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Subscriber server but before + it is returned to user code. This `post_update_subscription` interceptor runs + before the `post_update_subscription_with_metadata` interceptor. + """ + return response + + def post_update_subscription_with_metadata( + self, + response: pubsub.Subscription, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[pubsub.Subscription, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_subscription + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Subscriber server but before it is returned to user code. + + We recommend only using this `post_update_subscription_with_metadata` + interceptor in new development instead of the `post_update_subscription` interceptor. + When both interceptors are used, this `post_update_subscription_with_metadata` interceptor runs after the + `post_update_subscription` interceptor. The (possibly modified) response returned by + `post_update_subscription` will be passed to + `post_update_subscription_with_metadata`. + """ + return response, metadata + + def pre_get_iam_policy( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the Subscriber server. + """ + return request, metadata + + def post_get_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the Subscriber server but before + it is returned to user code. + """ + return response + + def pre_set_iam_policy( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the Subscriber server. + """ + return request, metadata + + def post_set_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the Subscriber server but before + it is returned to user code. + """ + return response + + def pre_test_iam_permissions( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.TestIamPermissionsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the Subscriber server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsResponse + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the Subscriber server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class SubscriberRestStub: + _session: AuthorizedSession + _host: str + _interceptor: SubscriberRestInterceptor + + +class SubscriberRestTransport(_BaseSubscriberRestTransport): + """REST backend synchronous transport for Subscriber. + + The service that an application uses to manipulate subscriptions and + to consume messages from a subscription via the ``Pull`` method or + by establishing a bi-directional stream using the ``StreamingPull`` + method. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "pubsub.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[SubscriberRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'pubsub.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + interceptor (Optional[SubscriberRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or SubscriberRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _Acknowledge( + _BaseSubscriberRestTransport._BaseAcknowledge, SubscriberRestStub + ): + def __hash__(self): + return hash("SubscriberRestTransport.Acknowledge") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: pubsub.AcknowledgeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the acknowledge method over HTTP. + + Args: + request (~.pubsub.AcknowledgeRequest): + The request object. Request for the Acknowledge method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseSubscriberRestTransport._BaseAcknowledge._get_http_options() + ) + + request, metadata = self._interceptor.pre_acknowledge(request, metadata) + transcoded_request = ( + _BaseSubscriberRestTransport._BaseAcknowledge._get_transcoded_request( + http_options, request + ) + ) + + body = _BaseSubscriberRestTransport._BaseAcknowledge._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BaseSubscriberRestTransport._BaseAcknowledge._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.SubscriberClient.Acknowledge", + extra={ + "serviceName": "google.pubsub.v1.Subscriber", + "rpcName": "Acknowledge", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SubscriberRestTransport._Acknowledge._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _CreateSnapshot( + _BaseSubscriberRestTransport._BaseCreateSnapshot, SubscriberRestStub + ): + def __hash__(self): + return hash("SubscriberRestTransport.CreateSnapshot") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: pubsub.CreateSnapshotRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.Snapshot: + r"""Call the create snapshot method over HTTP. + + Args: + request (~.pubsub.CreateSnapshotRequest): + The request object. Request for the ``CreateSnapshot`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.pubsub.Snapshot: + A snapshot resource. Snapshots are used in + `Seek `__ + operations, which allow you to manage message + acknowledgments in bulk. That is, you can set the + acknowledgment state of messages in an existing + subscription to the state captured by a snapshot. + + """ + + http_options = ( + _BaseSubscriberRestTransport._BaseCreateSnapshot._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_snapshot(request, metadata) + transcoded_request = _BaseSubscriberRestTransport._BaseCreateSnapshot._get_transcoded_request( + http_options, request + ) + + body = ( + _BaseSubscriberRestTransport._BaseCreateSnapshot._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSubscriberRestTransport._BaseCreateSnapshot._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.SubscriberClient.CreateSnapshot", + extra={ + "serviceName": "google.pubsub.v1.Subscriber", + "rpcName": "CreateSnapshot", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SubscriberRestTransport._CreateSnapshot._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = pubsub.Snapshot() + pb_resp = pubsub.Snapshot.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_snapshot(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_snapshot_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = pubsub.Snapshot.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.pubsub_v1.SubscriberClient.create_snapshot", + extra={ + "serviceName": "google.pubsub.v1.Subscriber", + "rpcName": "CreateSnapshot", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateSubscription( + _BaseSubscriberRestTransport._BaseCreateSubscription, SubscriberRestStub + ): + def __hash__(self): + return hash("SubscriberRestTransport.CreateSubscription") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: pubsub.Subscription, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.Subscription: + r"""Call the create subscription method over HTTP. + + Args: + request (~.pubsub.Subscription): + The request object. A subscription resource. If none of ``push_config``, + ``bigquery_config``, or ``cloud_storage_config`` is set, + then the subscriber will pull and ack messages using API + methods. At most one of these fields may be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.pubsub.Subscription: + A subscription resource. If none of ``push_config``, + ``bigquery_config``, or ``cloud_storage_config`` is set, + then the subscriber will pull and ack messages using API + methods. At most one of these fields may be set. + + """ + + http_options = ( + _BaseSubscriberRestTransport._BaseCreateSubscription._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_subscription( + request, metadata + ) + transcoded_request = _BaseSubscriberRestTransport._BaseCreateSubscription._get_transcoded_request( + http_options, request + ) + + body = _BaseSubscriberRestTransport._BaseCreateSubscription._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSubscriberRestTransport._BaseCreateSubscription._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.SubscriberClient.CreateSubscription", + extra={ + "serviceName": "google.pubsub.v1.Subscriber", + "rpcName": "CreateSubscription", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SubscriberRestTransport._CreateSubscription._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = pubsub.Subscription() + pb_resp = pubsub.Subscription.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_subscription(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_subscription_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = pubsub.Subscription.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.pubsub_v1.SubscriberClient.create_subscription", + extra={ + "serviceName": "google.pubsub.v1.Subscriber", + "rpcName": "CreateSubscription", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteSnapshot( + _BaseSubscriberRestTransport._BaseDeleteSnapshot, SubscriberRestStub + ): + def __hash__(self): + return hash("SubscriberRestTransport.DeleteSnapshot") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: pubsub.DeleteSnapshotRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete snapshot method over HTTP. + + Args: + request (~.pubsub.DeleteSnapshotRequest): + The request object. Request for the ``DeleteSnapshot`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseSubscriberRestTransport._BaseDeleteSnapshot._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_snapshot(request, metadata) + transcoded_request = _BaseSubscriberRestTransport._BaseDeleteSnapshot._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = ( + _BaseSubscriberRestTransport._BaseDeleteSnapshot._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.SubscriberClient.DeleteSnapshot", + extra={ + "serviceName": "google.pubsub.v1.Subscriber", + "rpcName": "DeleteSnapshot", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SubscriberRestTransport._DeleteSnapshot._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteSubscription( + _BaseSubscriberRestTransport._BaseDeleteSubscription, SubscriberRestStub + ): + def __hash__(self): + return hash("SubscriberRestTransport.DeleteSubscription") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: pubsub.DeleteSubscriptionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the delete subscription method over HTTP. + + Args: + request (~.pubsub.DeleteSubscriptionRequest): + The request object. Request for the DeleteSubscription + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseSubscriberRestTransport._BaseDeleteSubscription._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_subscription( + request, metadata + ) + transcoded_request = _BaseSubscriberRestTransport._BaseDeleteSubscription._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSubscriberRestTransport._BaseDeleteSubscription._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.SubscriberClient.DeleteSubscription", + extra={ + "serviceName": "google.pubsub.v1.Subscriber", + "rpcName": "DeleteSubscription", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SubscriberRestTransport._DeleteSubscription._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _GetSnapshot( + _BaseSubscriberRestTransport._BaseGetSnapshot, SubscriberRestStub + ): + def __hash__(self): + return hash("SubscriberRestTransport.GetSnapshot") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: pubsub.GetSnapshotRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.Snapshot: + r"""Call the get snapshot method over HTTP. + + Args: + request (~.pubsub.GetSnapshotRequest): + The request object. Request for the GetSnapshot method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.pubsub.Snapshot: + A snapshot resource. Snapshots are used in + `Seek `__ + operations, which allow you to manage message + acknowledgments in bulk. That is, you can set the + acknowledgment state of messages in an existing + subscription to the state captured by a snapshot. + + """ + + http_options = ( + _BaseSubscriberRestTransport._BaseGetSnapshot._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_snapshot(request, metadata) + transcoded_request = ( + _BaseSubscriberRestTransport._BaseGetSnapshot._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSubscriberRestTransport._BaseGetSnapshot._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.SubscriberClient.GetSnapshot", + extra={ + "serviceName": "google.pubsub.v1.Subscriber", + "rpcName": "GetSnapshot", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SubscriberRestTransport._GetSnapshot._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = pubsub.Snapshot() + pb_resp = pubsub.Snapshot.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_snapshot(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_snapshot_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = pubsub.Snapshot.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.pubsub_v1.SubscriberClient.get_snapshot", + extra={ + "serviceName": "google.pubsub.v1.Subscriber", + "rpcName": "GetSnapshot", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetSubscription( + _BaseSubscriberRestTransport._BaseGetSubscription, SubscriberRestStub + ): + def __hash__(self): + return hash("SubscriberRestTransport.GetSubscription") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: pubsub.GetSubscriptionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.Subscription: + r"""Call the get subscription method over HTTP. + + Args: + request (~.pubsub.GetSubscriptionRequest): + The request object. Request for the GetSubscription + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.pubsub.Subscription: + A subscription resource. If none of ``push_config``, + ``bigquery_config``, or ``cloud_storage_config`` is set, + then the subscriber will pull and ack messages using API + methods. At most one of these fields may be set. + + """ + + http_options = ( + _BaseSubscriberRestTransport._BaseGetSubscription._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_subscription( + request, metadata + ) + transcoded_request = _BaseSubscriberRestTransport._BaseGetSubscription._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSubscriberRestTransport._BaseGetSubscription._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.SubscriberClient.GetSubscription", + extra={ + "serviceName": "google.pubsub.v1.Subscriber", + "rpcName": "GetSubscription", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SubscriberRestTransport._GetSubscription._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = pubsub.Subscription() + pb_resp = pubsub.Subscription.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_subscription(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_subscription_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = pubsub.Subscription.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.pubsub_v1.SubscriberClient.get_subscription", + extra={ + "serviceName": "google.pubsub.v1.Subscriber", + "rpcName": "GetSubscription", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListSnapshots( + _BaseSubscriberRestTransport._BaseListSnapshots, SubscriberRestStub + ): + def __hash__(self): + return hash("SubscriberRestTransport.ListSnapshots") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: pubsub.ListSnapshotsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.ListSnapshotsResponse: + r"""Call the list snapshots method over HTTP. + + Args: + request (~.pubsub.ListSnapshotsRequest): + The request object. Request for the ``ListSnapshots`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.pubsub.ListSnapshotsResponse: + Response for the ``ListSnapshots`` method. + """ + + http_options = ( + _BaseSubscriberRestTransport._BaseListSnapshots._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_snapshots(request, metadata) + transcoded_request = ( + _BaseSubscriberRestTransport._BaseListSnapshots._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSubscriberRestTransport._BaseListSnapshots._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.SubscriberClient.ListSnapshots", + extra={ + "serviceName": "google.pubsub.v1.Subscriber", + "rpcName": "ListSnapshots", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SubscriberRestTransport._ListSnapshots._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = pubsub.ListSnapshotsResponse() + pb_resp = pubsub.ListSnapshotsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_snapshots(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_snapshots_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = pubsub.ListSnapshotsResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.pubsub_v1.SubscriberClient.list_snapshots", + extra={ + "serviceName": "google.pubsub.v1.Subscriber", + "rpcName": "ListSnapshots", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListSubscriptions( + _BaseSubscriberRestTransport._BaseListSubscriptions, SubscriberRestStub + ): + def __hash__(self): + return hash("SubscriberRestTransport.ListSubscriptions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: pubsub.ListSubscriptionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.ListSubscriptionsResponse: + r"""Call the list subscriptions method over HTTP. + + Args: + request (~.pubsub.ListSubscriptionsRequest): + The request object. Request for the ``ListSubscriptions`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.pubsub.ListSubscriptionsResponse: + Response for the ``ListSubscriptions`` method. + """ + + http_options = ( + _BaseSubscriberRestTransport._BaseListSubscriptions._get_http_options() + ) + + request, metadata = self._interceptor.pre_list_subscriptions( + request, metadata + ) + transcoded_request = _BaseSubscriberRestTransport._BaseListSubscriptions._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseSubscriberRestTransport._BaseListSubscriptions._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.SubscriberClient.ListSubscriptions", + extra={ + "serviceName": "google.pubsub.v1.Subscriber", + "rpcName": "ListSubscriptions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SubscriberRestTransport._ListSubscriptions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = pubsub.ListSubscriptionsResponse() + pb_resp = pubsub.ListSubscriptionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_subscriptions(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_subscriptions_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = pubsub.ListSubscriptionsResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.pubsub_v1.SubscriberClient.list_subscriptions", + extra={ + "serviceName": "google.pubsub.v1.Subscriber", + "rpcName": "ListSubscriptions", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ModifyAckDeadline( + _BaseSubscriberRestTransport._BaseModifyAckDeadline, SubscriberRestStub + ): + def __hash__(self): + return hash("SubscriberRestTransport.ModifyAckDeadline") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: pubsub.ModifyAckDeadlineRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the modify ack deadline method over HTTP. + + Args: + request (~.pubsub.ModifyAckDeadlineRequest): + The request object. Request for the ModifyAckDeadline + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseSubscriberRestTransport._BaseModifyAckDeadline._get_http_options() + ) + + request, metadata = self._interceptor.pre_modify_ack_deadline( + request, metadata + ) + transcoded_request = _BaseSubscriberRestTransport._BaseModifyAckDeadline._get_transcoded_request( + http_options, request + ) + + body = _BaseSubscriberRestTransport._BaseModifyAckDeadline._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSubscriberRestTransport._BaseModifyAckDeadline._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.SubscriberClient.ModifyAckDeadline", + extra={ + "serviceName": "google.pubsub.v1.Subscriber", + "rpcName": "ModifyAckDeadline", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SubscriberRestTransport._ModifyAckDeadline._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _ModifyPushConfig( + _BaseSubscriberRestTransport._BaseModifyPushConfig, SubscriberRestStub + ): + def __hash__(self): + return hash("SubscriberRestTransport.ModifyPushConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: pubsub.ModifyPushConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + r"""Call the modify push config method over HTTP. + + Args: + request (~.pubsub.ModifyPushConfigRequest): + The request object. Request for the ModifyPushConfig + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + + http_options = ( + _BaseSubscriberRestTransport._BaseModifyPushConfig._get_http_options() + ) + + request, metadata = self._interceptor.pre_modify_push_config( + request, metadata + ) + transcoded_request = _BaseSubscriberRestTransport._BaseModifyPushConfig._get_transcoded_request( + http_options, request + ) + + body = _BaseSubscriberRestTransport._BaseModifyPushConfig._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSubscriberRestTransport._BaseModifyPushConfig._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.SubscriberClient.ModifyPushConfig", + extra={ + "serviceName": "google.pubsub.v1.Subscriber", + "rpcName": "ModifyPushConfig", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SubscriberRestTransport._ModifyPushConfig._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _Pull(_BaseSubscriberRestTransport._BasePull, SubscriberRestStub): + def __hash__(self): + return hash("SubscriberRestTransport.Pull") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: pubsub.PullRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.PullResponse: + r"""Call the pull method over HTTP. + + Args: + request (~.pubsub.PullRequest): + The request object. Request for the ``Pull`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.pubsub.PullResponse: + Response for the ``Pull`` method. + """ + + http_options = _BaseSubscriberRestTransport._BasePull._get_http_options() + + request, metadata = self._interceptor.pre_pull(request, metadata) + transcoded_request = ( + _BaseSubscriberRestTransport._BasePull._get_transcoded_request( + http_options, request + ) + ) + + body = _BaseSubscriberRestTransport._BasePull._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BaseSubscriberRestTransport._BasePull._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.SubscriberClient.Pull", + extra={ + "serviceName": "google.pubsub.v1.Subscriber", + "rpcName": "Pull", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SubscriberRestTransport._Pull._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = pubsub.PullResponse() + pb_resp = pubsub.PullResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_pull(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_pull_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = pubsub.PullResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.pubsub_v1.SubscriberClient.pull", + extra={ + "serviceName": "google.pubsub.v1.Subscriber", + "rpcName": "Pull", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _Seek(_BaseSubscriberRestTransport._BaseSeek, SubscriberRestStub): + def __hash__(self): + return hash("SubscriberRestTransport.Seek") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: pubsub.SeekRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.SeekResponse: + r"""Call the seek method over HTTP. + + Args: + request (~.pubsub.SeekRequest): + The request object. Request for the ``Seek`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.pubsub.SeekResponse: + Response for the ``Seek`` method (this response is + empty). + + """ + + http_options = _BaseSubscriberRestTransport._BaseSeek._get_http_options() + + request, metadata = self._interceptor.pre_seek(request, metadata) + transcoded_request = ( + _BaseSubscriberRestTransport._BaseSeek._get_transcoded_request( + http_options, request + ) + ) + + body = _BaseSubscriberRestTransport._BaseSeek._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BaseSubscriberRestTransport._BaseSeek._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.SubscriberClient.Seek", + extra={ + "serviceName": "google.pubsub.v1.Subscriber", + "rpcName": "Seek", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SubscriberRestTransport._Seek._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = pubsub.SeekResponse() + pb_resp = pubsub.SeekResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_seek(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_seek_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = pubsub.SeekResponse.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.pubsub_v1.SubscriberClient.seek", + extra={ + "serviceName": "google.pubsub.v1.Subscriber", + "rpcName": "Seek", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _StreamingPull( + _BaseSubscriberRestTransport._BaseStreamingPull, SubscriberRestStub + ): + def __hash__(self): + return hash("SubscriberRestTransport.StreamingPull") + + def __call__( + self, + request: pubsub.StreamingPullRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> rest_streaming.ResponseIterator: + raise NotImplementedError( + "Method StreamingPull is not available over REST transport" + ) + + class _UpdateSnapshot( + _BaseSubscriberRestTransport._BaseUpdateSnapshot, SubscriberRestStub + ): + def __hash__(self): + return hash("SubscriberRestTransport.UpdateSnapshot") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: pubsub.UpdateSnapshotRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.Snapshot: + r"""Call the update snapshot method over HTTP. + + Args: + request (~.pubsub.UpdateSnapshotRequest): + The request object. Request for the UpdateSnapshot + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.pubsub.Snapshot: + A snapshot resource. Snapshots are used in + `Seek `__ + operations, which allow you to manage message + acknowledgments in bulk. That is, you can set the + acknowledgment state of messages in an existing + subscription to the state captured by a snapshot. + + """ + + http_options = ( + _BaseSubscriberRestTransport._BaseUpdateSnapshot._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_snapshot(request, metadata) + transcoded_request = _BaseSubscriberRestTransport._BaseUpdateSnapshot._get_transcoded_request( + http_options, request + ) + + body = ( + _BaseSubscriberRestTransport._BaseUpdateSnapshot._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSubscriberRestTransport._BaseUpdateSnapshot._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.SubscriberClient.UpdateSnapshot", + extra={ + "serviceName": "google.pubsub.v1.Subscriber", + "rpcName": "UpdateSnapshot", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SubscriberRestTransport._UpdateSnapshot._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = pubsub.Snapshot() + pb_resp = pubsub.Snapshot.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_snapshot(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_snapshot_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = pubsub.Snapshot.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.pubsub_v1.SubscriberClient.update_snapshot", + extra={ + "serviceName": "google.pubsub.v1.Subscriber", + "rpcName": "UpdateSnapshot", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateSubscription( + _BaseSubscriberRestTransport._BaseUpdateSubscription, SubscriberRestStub + ): + def __hash__(self): + return hash("SubscriberRestTransport.UpdateSubscription") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: pubsub.UpdateSubscriptionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pubsub.Subscription: + r"""Call the update subscription method over HTTP. + + Args: + request (~.pubsub.UpdateSubscriptionRequest): + The request object. Request for the UpdateSubscription + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.pubsub.Subscription: + A subscription resource. If none of ``push_config``, + ``bigquery_config``, or ``cloud_storage_config`` is set, + then the subscriber will pull and ack messages using API + methods. At most one of these fields may be set. + + """ + + http_options = ( + _BaseSubscriberRestTransport._BaseUpdateSubscription._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_subscription( + request, metadata + ) + transcoded_request = _BaseSubscriberRestTransport._BaseUpdateSubscription._get_transcoded_request( + http_options, request + ) + + body = _BaseSubscriberRestTransport._BaseUpdateSubscription._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSubscriberRestTransport._BaseUpdateSubscription._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.SubscriberClient.UpdateSubscription", + extra={ + "serviceName": "google.pubsub.v1.Subscriber", + "rpcName": "UpdateSubscription", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SubscriberRestTransport._UpdateSubscription._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = pubsub.Subscription() + pb_resp = pubsub.Subscription.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_subscription(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_subscription_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = pubsub.Subscription.to_json(response) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.pubsub_v1.SubscriberClient.update_subscription", + extra={ + "serviceName": "google.pubsub.v1.Subscriber", + "rpcName": "UpdateSubscription", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def acknowledge(self) -> Callable[[pubsub.AcknowledgeRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Acknowledge(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_snapshot( + self, + ) -> Callable[[pubsub.CreateSnapshotRequest], pubsub.Snapshot]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateSnapshot(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_subscription( + self, + ) -> Callable[[pubsub.Subscription], pubsub.Subscription]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateSubscription(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_snapshot( + self, + ) -> Callable[[pubsub.DeleteSnapshotRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteSnapshot(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_subscription( + self, + ) -> Callable[[pubsub.DeleteSubscriptionRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteSubscription(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_snapshot(self) -> Callable[[pubsub.GetSnapshotRequest], pubsub.Snapshot]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetSnapshot(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_subscription( + self, + ) -> Callable[[pubsub.GetSubscriptionRequest], pubsub.Subscription]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetSubscription(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_snapshots( + self, + ) -> Callable[[pubsub.ListSnapshotsRequest], pubsub.ListSnapshotsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListSnapshots(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_subscriptions( + self, + ) -> Callable[[pubsub.ListSubscriptionsRequest], pubsub.ListSubscriptionsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListSubscriptions(self._session, self._host, self._interceptor) # type: ignore + + @property + def modify_ack_deadline( + self, + ) -> Callable[[pubsub.ModifyAckDeadlineRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ModifyAckDeadline(self._session, self._host, self._interceptor) # type: ignore + + @property + def modify_push_config( + self, + ) -> Callable[[pubsub.ModifyPushConfigRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ModifyPushConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def pull(self) -> Callable[[pubsub.PullRequest], pubsub.PullResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Pull(self._session, self._host, self._interceptor) # type: ignore + + @property + def seek(self) -> Callable[[pubsub.SeekRequest], pubsub.SeekResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Seek(self._session, self._host, self._interceptor) # type: ignore + + @property + def streaming_pull( + self, + ) -> Callable[[pubsub.StreamingPullRequest], pubsub.StreamingPullResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._StreamingPull(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_snapshot( + self, + ) -> Callable[[pubsub.UpdateSnapshotRequest], pubsub.Snapshot]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateSnapshot(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_subscription( + self, + ) -> Callable[[pubsub.UpdateSubscriptionRequest], pubsub.Subscription]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateSubscription(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy( + _BaseSubscriberRestTransport._BaseGetIamPolicy, SubscriberRestStub + ): + def __hash__(self): + return hash("SubscriberRestTransport.GetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options = ( + _BaseSubscriberRestTransport._BaseGetIamPolicy._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + transcoded_request = ( + _BaseSubscriberRestTransport._BaseGetIamPolicy._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSubscriberRestTransport._BaseGetIamPolicy._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.SubscriberClient.GetIamPolicy", + extra={ + "serviceName": "google.pubsub.v1.Subscriber", + "rpcName": "GetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SubscriberRestTransport._GetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.pubsub_v1.SubscriberAsyncClient.GetIamPolicy", + extra={ + "serviceName": "google.pubsub.v1.Subscriber", + "rpcName": "GetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy( + _BaseSubscriberRestTransport._BaseSetIamPolicy, SubscriberRestStub + ): + def __hash__(self): + return hash("SubscriberRestTransport.SetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> policy_pb2.Policy: + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options = ( + _BaseSubscriberRestTransport._BaseSetIamPolicy._get_http_options() + ) + + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + transcoded_request = ( + _BaseSubscriberRestTransport._BaseSetIamPolicy._get_transcoded_request( + http_options, request + ) + ) + + body = ( + _BaseSubscriberRestTransport._BaseSetIamPolicy._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseSubscriberRestTransport._BaseSetIamPolicy._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.SubscriberClient.SetIamPolicy", + extra={ + "serviceName": "google.pubsub.v1.Subscriber", + "rpcName": "SetIamPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SubscriberRestTransport._SetIamPolicy._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_set_iam_policy(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.pubsub_v1.SubscriberAsyncClient.SetIamPolicy", + extra={ + "serviceName": "google.pubsub.v1.Subscriber", + "rpcName": "SetIamPolicy", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions( + _BaseSubscriberRestTransport._BaseTestIamPermissions, SubscriberRestStub + ): + def __hash__(self): + return hash("SubscriberRestTransport.TestIamPermissions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options = ( + _BaseSubscriberRestTransport._BaseTestIamPermissions._get_http_options() + ) + + request, metadata = self._interceptor.pre_test_iam_permissions( + request, metadata + ) + transcoded_request = _BaseSubscriberRestTransport._BaseTestIamPermissions._get_transcoded_request( + http_options, request + ) + + body = _BaseSubscriberRestTransport._BaseTestIamPermissions._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSubscriberRestTransport._BaseTestIamPermissions._get_query_params_json( + transcoded_request + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = json_format.MessageToJson(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.pubsub_v1.SubscriberClient.TestIamPermissions", + extra={ + "serviceName": "google.pubsub.v1.Subscriber", + "rpcName": "TestIamPermissions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SubscriberRestTransport._TestIamPermissions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_test_iam_permissions(resp) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.pubsub_v1.SubscriberAsyncClient.TestIamPermissions", + extra={ + "serviceName": "google.pubsub.v1.Subscriber", + "rpcName": "TestIamPermissions", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("SubscriberRestTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/subscriber/transports/rest_base.py b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/subscriber/transports/rest_base.py new file mode 100644 index 0000000000000000000000000000000000000000..ea1d6ace9c9bce77edc36e064113baee868a2e6b --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/services/subscriber/transports/rest_base.py @@ -0,0 +1,1024 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed 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. +# +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf.empty_pb2 as empty_pb2 # type: ignore +from google.api_core import gapic_v1, path_template +from google.iam.v1 import ( + iam_policy_pb2, # type: ignore + policy_pb2, # type: ignore +) +from google.protobuf import json_format + +from google.pubsub_v1.types import pubsub + +from .base import DEFAULT_CLIENT_INFO, SubscriberTransport + + +class _BaseSubscriberRestTransport(SubscriberTransport): + """Base REST backend transport for Subscriber. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "pubsub.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'pubsub.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseAcknowledge: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{subscription=projects/*/subscriptions/*}:acknowledge", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = pubsub.AcknowledgeRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSubscriberRestTransport._BaseAcknowledge._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateSnapshot: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "put", + "uri": "/v1/{name=projects/*/snapshots/*}", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = pubsub.CreateSnapshotRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSubscriberRestTransport._BaseCreateSnapshot._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateSubscription: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "put", + "uri": "/v1/{name=projects/*/subscriptions/*}", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = pubsub.Subscription.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSubscriberRestTransport._BaseCreateSubscription._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteSnapshot: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{snapshot=projects/*/snapshots/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = pubsub.DeleteSnapshotRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSubscriberRestTransport._BaseDeleteSnapshot._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDeleteSubscription: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{subscription=projects/*/subscriptions/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = pubsub.DeleteSubscriptionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSubscriberRestTransport._BaseDeleteSubscription._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetSnapshot: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{snapshot=projects/*/snapshots/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = pubsub.GetSnapshotRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSubscriberRestTransport._BaseGetSnapshot._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetSubscription: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{subscription=projects/*/subscriptions/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = pubsub.GetSubscriptionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSubscriberRestTransport._BaseGetSubscription._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListSnapshots: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{project=projects/*}/snapshots", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = pubsub.ListSnapshotsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSubscriberRestTransport._BaseListSnapshots._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListSubscriptions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{project=projects/*}/subscriptions", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = pubsub.ListSubscriptionsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSubscriberRestTransport._BaseListSubscriptions._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseModifyAckDeadline: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{subscription=projects/*/subscriptions/*}:modifyAckDeadline", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = pubsub.ModifyAckDeadlineRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSubscriberRestTransport._BaseModifyAckDeadline._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseModifyPushConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{subscription=projects/*/subscriptions/*}:modifyPushConfig", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = pubsub.ModifyPushConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSubscriberRestTransport._BaseModifyPushConfig._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BasePull: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{subscription=projects/*/subscriptions/*}:pull", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = pubsub.PullRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSubscriberRestTransport._BasePull._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseSeek: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{subscription=projects/*/subscriptions/*}:seek", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = pubsub.SeekRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSubscriberRestTransport._BaseSeek._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseStreamingPull: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + class _BaseUpdateSnapshot: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{snapshot.name=projects/*/snapshots/*}", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = pubsub.UpdateSnapshotRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSubscriberRestTransport._BaseUpdateSnapshot._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateSubscription: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{subscription.name=projects/*/subscriptions/*}", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = pubsub.UpdateSubscriptionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSubscriberRestTransport._BaseUpdateSubscription._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{resource=projects/*/topics/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/subscriptions/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/snapshots/*}:getIamPolicy", + }, + { + "method": "get", + "uri": "/v1/{resource=projects/*/schemas/*}:getIamPolicy", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseSetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{resource=projects/*/topics/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/subscriptions/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/snapshots/*}:setIamPolicy", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/schemas/*}:setIamPolicy", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + class _BaseTestIamPermissions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{resource=projects/*/subscriptions/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/topics/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/snapshots/*}:testIamPermissions", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{resource=projects/*/schemas/*}:testIamPermissions", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request["body"]) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + return query_params + + +__all__ = ("_BaseSubscriberRestTransport",) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/types/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/types/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..47aabec693ebd92a11dd90ed626d4b2f9910dfc0 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/types/__init__.py @@ -0,0 +1,173 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed 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. +# +from typing import Union + +from .pubsub import ( + AcknowledgeRequest, + AIInference, + BigQueryConfig, + BigtableConfig, + CloudStorageConfig, + CreateSnapshotRequest, + DeadLetterPolicy, + DeleteSnapshotRequest, + DeleteSubscriptionRequest, + DeleteTopicRequest, + DetachSubscriptionRequest, + DetachSubscriptionResponse, + ExpirationPolicy, + GetSnapshotRequest, + GetSubscriptionRequest, + GetTopicRequest, + IngestionDataSourceSettings, + IngestionFailureEvent, + JavaScriptUDF, + ListSnapshotsRequest, + ListSnapshotsResponse, + ListSubscriptionsRequest, + ListSubscriptionsResponse, + ListTopicSnapshotsRequest, + ListTopicSnapshotsResponse, + ListTopicsRequest, + ListTopicsResponse, + ListTopicSubscriptionsRequest, + ListTopicSubscriptionsResponse, + MessageStoragePolicy, + MessageTransform, + ModifyAckDeadlineRequest, + ModifyPushConfigRequest, + PlatformLogsSettings, + PublishRequest, + PublishResponse, + PubsubMessage, + PullRequest, + PullResponse, + PushConfig, + ReceivedMessage, + RetryPolicy, + SchemaSettings, + SeekRequest, + SeekResponse, + Snapshot, + StreamingPullRequest, + StreamingPullResponse, + Subscription, + Topic, + UpdateSnapshotRequest, + UpdateSubscriptionRequest, + UpdateTopicRequest, +) +from .schema import ( + CommitSchemaRequest, + CreateSchemaRequest, + DeleteSchemaRequest, + DeleteSchemaRevisionRequest, + Encoding, + GetSchemaRequest, + ListSchemaRevisionsRequest, + ListSchemaRevisionsResponse, + ListSchemasRequest, + ListSchemasResponse, + RollbackSchemaRequest, + Schema, + SchemaView, + ValidateMessageRequest, + ValidateMessageResponse, + ValidateSchemaRequest, + ValidateSchemaResponse, +) + +TimeoutType = Union[ + int, + float, + "google.api_core.timeout.ConstantTimeout", + "google.api_core.timeout.ExponentialTimeout", +] +"""The type of the timeout parameter of publisher client methods.""" + +__all__ = ( + "TimeoutType", + "AcknowledgeRequest", + "AIInference", + "BigQueryConfig", + "BigtableConfig", + "CloudStorageConfig", + "CreateSnapshotRequest", + "DeadLetterPolicy", + "DeleteSnapshotRequest", + "DeleteSubscriptionRequest", + "DeleteTopicRequest", + "DetachSubscriptionRequest", + "DetachSubscriptionResponse", + "ExpirationPolicy", + "GetSnapshotRequest", + "GetSubscriptionRequest", + "GetTopicRequest", + "IngestionDataSourceSettings", + "IngestionFailureEvent", + "JavaScriptUDF", + "ListSnapshotsRequest", + "ListSnapshotsResponse", + "ListSubscriptionsRequest", + "ListSubscriptionsResponse", + "ListTopicSnapshotsRequest", + "ListTopicSnapshotsResponse", + "ListTopicsRequest", + "ListTopicsResponse", + "ListTopicSubscriptionsRequest", + "ListTopicSubscriptionsResponse", + "MessageStoragePolicy", + "MessageTransform", + "ModifyAckDeadlineRequest", + "ModifyPushConfigRequest", + "PlatformLogsSettings", + "PublishRequest", + "PublishResponse", + "PubsubMessage", + "PullRequest", + "PullResponse", + "PushConfig", + "ReceivedMessage", + "RetryPolicy", + "SchemaSettings", + "SeekRequest", + "SeekResponse", + "Snapshot", + "StreamingPullRequest", + "StreamingPullResponse", + "Subscription", + "Topic", + "UpdateSnapshotRequest", + "UpdateSubscriptionRequest", + "UpdateTopicRequest", + "CommitSchemaRequest", + "CreateSchemaRequest", + "DeleteSchemaRequest", + "DeleteSchemaRevisionRequest", + "GetSchemaRequest", + "ListSchemaRevisionsRequest", + "ListSchemaRevisionsResponse", + "ListSchemasRequest", + "ListSchemasResponse", + "RollbackSchemaRequest", + "Schema", + "ValidateMessageRequest", + "ValidateMessageResponse", + "ValidateSchemaRequest", + "ValidateSchemaResponse", + "Encoding", + "SchemaView", +) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/types/pubsub.py b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/types/pubsub.py new file mode 100644 index 0000000000000000000000000000000000000000..7d95585992d6be6bb556497026e51695a85c9882 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/types/pubsub.py @@ -0,0 +1,3844 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed 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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.struct_pb2 as struct_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.pubsub_v1.types import schema as gp_schema + +__protobuf__ = proto.module( + package="google.pubsub.v1", + manifest={ + "MessageStoragePolicy", + "SchemaSettings", + "IngestionDataSourceSettings", + "PlatformLogsSettings", + "IngestionFailureEvent", + "JavaScriptUDF", + "AIInference", + "MessageTransform", + "Topic", + "PubsubMessage", + "GetTopicRequest", + "UpdateTopicRequest", + "PublishRequest", + "PublishResponse", + "ListTopicsRequest", + "ListTopicsResponse", + "ListTopicSubscriptionsRequest", + "ListTopicSubscriptionsResponse", + "ListTopicSnapshotsRequest", + "ListTopicSnapshotsResponse", + "DeleteTopicRequest", + "DetachSubscriptionRequest", + "DetachSubscriptionResponse", + "Subscription", + "RetryPolicy", + "DeadLetterPolicy", + "ExpirationPolicy", + "PushConfig", + "BigQueryConfig", + "BigtableConfig", + "CloudStorageConfig", + "ReceivedMessage", + "GetSubscriptionRequest", + "UpdateSubscriptionRequest", + "ListSubscriptionsRequest", + "ListSubscriptionsResponse", + "DeleteSubscriptionRequest", + "ModifyPushConfigRequest", + "PullRequest", + "PullResponse", + "ModifyAckDeadlineRequest", + "AcknowledgeRequest", + "StreamingPullRequest", + "StreamingPullResponse", + "CreateSnapshotRequest", + "UpdateSnapshotRequest", + "Snapshot", + "GetSnapshotRequest", + "ListSnapshotsRequest", + "ListSnapshotsResponse", + "DeleteSnapshotRequest", + "SeekRequest", + "SeekResponse", + }, +) + + +class MessageStoragePolicy(proto.Message): + r"""A policy constraining the storage of messages published to + the topic. + + Attributes: + allowed_persistence_regions (MutableSequence[str]): + Optional. A list of IDs of Google Cloud + regions where messages that are published to the + topic may be persisted in storage. Messages + published by publishers running in non-allowed + Google Cloud regions (or running outside of + Google Cloud altogether) are routed for storage + in one of the allowed regions. An empty list + means that no regions are allowed, and is not a + valid configuration. + enforce_in_transit (bool): + Optional. If true, ``allowed_persistence_regions`` is also + used to enforce in-transit guarantees for messages. That is, + Pub/Sub will fail Publish operations on this topic and + subscribe operations on any subscription attached to this + topic in any region that is not in + ``allowed_persistence_regions``. + """ + + allowed_persistence_regions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + enforce_in_transit: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class SchemaSettings(proto.Message): + r"""Settings for validating messages published against a schema. + + Attributes: + schema (str): + Required. The name of the schema that messages published + should be validated against. Format is + ``projects/{project}/schemas/{schema}``. The value of this + field will be ``_deleted-schema_`` if the schema has been + deleted. + encoding (google.pubsub_v1.types.Encoding): + Optional. The encoding of messages validated against + ``schema``. + first_revision_id (str): + Optional. The minimum (inclusive) revision allowed for + validating messages. If empty or not present, allow any + revision to be validated against last_revision or any + revision created before. + last_revision_id (str): + Optional. The maximum (inclusive) revision allowed for + validating messages. If empty or not present, allow any + revision to be validated against first_revision or any + revision created after. + """ + + schema: str = proto.Field( + proto.STRING, + number=1, + ) + encoding: gp_schema.Encoding = proto.Field( + proto.ENUM, + number=2, + enum=gp_schema.Encoding, + ) + first_revision_id: str = proto.Field( + proto.STRING, + number=3, + ) + last_revision_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class IngestionDataSourceSettings(proto.Message): + r"""Settings for an ingestion data source on a topic. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + aws_kinesis (google.pubsub_v1.types.IngestionDataSourceSettings.AwsKinesis): + Optional. Amazon Kinesis Data Streams. + + This field is a member of `oneof`_ ``source``. + cloud_storage (google.pubsub_v1.types.IngestionDataSourceSettings.CloudStorage): + Optional. Cloud Storage. + + This field is a member of `oneof`_ ``source``. + azure_event_hubs (google.pubsub_v1.types.IngestionDataSourceSettings.AzureEventHubs): + Optional. Azure Event Hubs. + + This field is a member of `oneof`_ ``source``. + aws_msk (google.pubsub_v1.types.IngestionDataSourceSettings.AwsMsk): + Optional. Amazon MSK. + + This field is a member of `oneof`_ ``source``. + confluent_cloud (google.pubsub_v1.types.IngestionDataSourceSettings.ConfluentCloud): + Optional. Confluent Cloud. + + This field is a member of `oneof`_ ``source``. + platform_logs_settings (google.pubsub_v1.types.PlatformLogsSettings): + Optional. Platform Logs settings. If unset, + no Platform Logs will be generated. + """ + + class AwsKinesis(proto.Message): + r"""Ingestion settings for Amazon Kinesis Data Streams. + + Attributes: + state (google.pubsub_v1.types.IngestionDataSourceSettings.AwsKinesis.State): + Output only. An output-only field that + indicates the state of the Kinesis ingestion + source. + stream_arn (str): + Required. The Kinesis stream ARN to ingest + data from. + consumer_arn (str): + Required. The Kinesis consumer ARN to used + for ingestion in Enhanced Fan-Out mode. The + consumer must be already created and ready to be + used. + aws_role_arn (str): + Required. AWS role ARN to be used for + Federated Identity authentication with Kinesis. + Check the Pub/Sub docs for how to set up this + role and the required permissions that need to + be attached to it. + gcp_service_account (str): + Required. The GCP service account to be used for Federated + Identity authentication with Kinesis (via a + ``AssumeRoleWithWebIdentity`` call for the provided role). + The ``aws_role_arn`` must be set up with + ``accounts.google.com:sub`` equals to this service account + number. + """ + + class State(proto.Enum): + r"""Possible states for ingestion from Amazon Kinesis Data + Streams. + + Values: + STATE_UNSPECIFIED (0): + Default value. This value is unused. + ACTIVE (1): + Ingestion is active. + KINESIS_PERMISSION_DENIED (2): + Permission denied encountered while consuming data from + Kinesis. This can happen if: + + - The provided ``aws_role_arn`` does not exist or does not + have the appropriate permissions attached. + - The provided ``aws_role_arn`` is not set up properly for + Identity Federation using ``gcp_service_account``. + - The Pub/Sub SA is not granted the + ``iam.serviceAccounts.getOpenIdToken`` permission on + ``gcp_service_account``. + PUBLISH_PERMISSION_DENIED (3): + Permission denied encountered while publishing to the topic. + This can happen if the Pub/Sub SA has not been granted the + `appropriate publish + permissions `__ + STREAM_NOT_FOUND (4): + The Kinesis stream does not exist. + CONSUMER_NOT_FOUND (5): + The Kinesis consumer does not exist. + """ + + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + KINESIS_PERMISSION_DENIED = 2 + PUBLISH_PERMISSION_DENIED = 3 + STREAM_NOT_FOUND = 4 + CONSUMER_NOT_FOUND = 5 + + state: "IngestionDataSourceSettings.AwsKinesis.State" = proto.Field( + proto.ENUM, + number=1, + enum="IngestionDataSourceSettings.AwsKinesis.State", + ) + stream_arn: str = proto.Field( + proto.STRING, + number=2, + ) + consumer_arn: str = proto.Field( + proto.STRING, + number=3, + ) + aws_role_arn: str = proto.Field( + proto.STRING, + number=4, + ) + gcp_service_account: str = proto.Field( + proto.STRING, + number=5, + ) + + class CloudStorage(proto.Message): + r"""Ingestion settings for Cloud Storage. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + state (google.pubsub_v1.types.IngestionDataSourceSettings.CloudStorage.State): + Output only. An output-only field that + indicates the state of the Cloud Storage + ingestion source. + bucket (str): + Optional. Cloud Storage bucket. The bucket name must be + without any prefix like "gs://". See the [bucket naming + requirements] + (https://cloud.google.com/storage/docs/buckets#naming). + text_format (google.pubsub_v1.types.IngestionDataSourceSettings.CloudStorage.TextFormat): + Optional. Data from Cloud Storage will be + interpreted as text. + + This field is a member of `oneof`_ ``input_format``. + avro_format (google.pubsub_v1.types.IngestionDataSourceSettings.CloudStorage.AvroFormat): + Optional. Data from Cloud Storage will be + interpreted in Avro format. + + This field is a member of `oneof`_ ``input_format``. + pubsub_avro_format (google.pubsub_v1.types.IngestionDataSourceSettings.CloudStorage.PubSubAvroFormat): + Optional. It will be assumed data from Cloud Storage was + written via `Cloud Storage + subscriptions `__. + + This field is a member of `oneof`_ ``input_format``. + minimum_object_create_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. Only objects with a larger or equal + creation timestamp will be ingested. + match_glob (str): + Optional. Glob pattern used to match objects that will be + ingested. If unset, all objects will be ingested. See the + `supported + patterns `__. + """ + + class State(proto.Enum): + r"""Possible states for ingestion from Cloud Storage. + + Values: + STATE_UNSPECIFIED (0): + Default value. This value is unused. + ACTIVE (1): + Ingestion is active. + CLOUD_STORAGE_PERMISSION_DENIED (2): + Permission denied encountered while calling the Cloud + Storage API. This can happen if the Pub/Sub SA has not been + granted the `appropriate + permissions `__: + + - storage.objects.list: to list the objects in a bucket. + - storage.objects.get: to read the objects in a bucket. + - storage.buckets.get: to verify the bucket exists. + PUBLISH_PERMISSION_DENIED (3): + Permission denied encountered while publishing to the topic. + This can happen if the Pub/Sub SA has not been granted the + `appropriate publish + permissions `__ + BUCKET_NOT_FOUND (4): + The provided Cloud Storage bucket doesn't + exist. + TOO_MANY_OBJECTS (5): + The Cloud Storage bucket has too many + objects, ingestion will be paused. + """ + + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + CLOUD_STORAGE_PERMISSION_DENIED = 2 + PUBLISH_PERMISSION_DENIED = 3 + BUCKET_NOT_FOUND = 4 + TOO_MANY_OBJECTS = 5 + + class TextFormat(proto.Message): + r"""Configuration for reading Cloud Storage data in text format. Each + line of text as specified by the delimiter will be set to the + ``data`` field of a Pub/Sub message. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + delimiter (str): + Optional. When unset, '\n' is used. + + This field is a member of `oneof`_ ``_delimiter``. + """ + + delimiter: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + + class AvroFormat(proto.Message): + r"""Configuration for reading Cloud Storage data in Avro binary format. + The bytes of each object will be set to the ``data`` field of a + Pub/Sub message. + + """ + + class PubSubAvroFormat(proto.Message): + r"""Configuration for reading Cloud Storage data written via `Cloud + Storage + subscriptions `__. + The data and attributes fields of the originally exported Pub/Sub + message will be restored when publishing. + + """ + + state: "IngestionDataSourceSettings.CloudStorage.State" = proto.Field( + proto.ENUM, + number=1, + enum="IngestionDataSourceSettings.CloudStorage.State", + ) + bucket: str = proto.Field( + proto.STRING, + number=2, + ) + text_format: "IngestionDataSourceSettings.CloudStorage.TextFormat" = ( + proto.Field( + proto.MESSAGE, + number=3, + oneof="input_format", + message="IngestionDataSourceSettings.CloudStorage.TextFormat", + ) + ) + avro_format: "IngestionDataSourceSettings.CloudStorage.AvroFormat" = ( + proto.Field( + proto.MESSAGE, + number=4, + oneof="input_format", + message="IngestionDataSourceSettings.CloudStorage.AvroFormat", + ) + ) + pubsub_avro_format: "IngestionDataSourceSettings.CloudStorage.PubSubAvroFormat" = proto.Field( + proto.MESSAGE, + number=5, + oneof="input_format", + message="IngestionDataSourceSettings.CloudStorage.PubSubAvroFormat", + ) + minimum_object_create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + match_glob: str = proto.Field( + proto.STRING, + number=9, + ) + + class AzureEventHubs(proto.Message): + r"""Ingestion settings for Azure Event Hubs. + + Attributes: + state (google.pubsub_v1.types.IngestionDataSourceSettings.AzureEventHubs.State): + Output only. An output-only field that + indicates the state of the Event Hubs ingestion + source. + resource_group (str): + Optional. Name of the resource group within + the azure subscription. + namespace (str): + Optional. The name of the Event Hubs + namespace. + event_hub (str): + Optional. The name of the Event Hub. + client_id (str): + Optional. The client id of the Azure + application that is being used to authenticate + Pub/Sub. + tenant_id (str): + Optional. The tenant id of the Azure + application that is being used to authenticate + Pub/Sub. + subscription_id (str): + Optional. The Azure subscription id. + gcp_service_account (str): + Optional. The GCP service account to be used + for Federated Identity authentication. + """ + + class State(proto.Enum): + r"""Possible states for managed ingestion from Event Hubs. + + Values: + STATE_UNSPECIFIED (0): + Default value. This value is unused. + ACTIVE (1): + Ingestion is active. + EVENT_HUBS_PERMISSION_DENIED (2): + Permission denied encountered while consuming data from + Event Hubs. This can happen when ``client_id``, or + ``tenant_id`` are invalid. Or the right permissions haven't + been granted. + PUBLISH_PERMISSION_DENIED (3): + Permission denied encountered while + publishing to the topic. + NAMESPACE_NOT_FOUND (4): + The provided Event Hubs namespace couldn't be + found. + EVENT_HUB_NOT_FOUND (5): + The provided Event Hub couldn't be found. + SUBSCRIPTION_NOT_FOUND (6): + The provided Event Hubs subscription couldn't + be found. + RESOURCE_GROUP_NOT_FOUND (7): + The provided Event Hubs resource group + couldn't be found. + """ + + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + EVENT_HUBS_PERMISSION_DENIED = 2 + PUBLISH_PERMISSION_DENIED = 3 + NAMESPACE_NOT_FOUND = 4 + EVENT_HUB_NOT_FOUND = 5 + SUBSCRIPTION_NOT_FOUND = 6 + RESOURCE_GROUP_NOT_FOUND = 7 + + state: "IngestionDataSourceSettings.AzureEventHubs.State" = proto.Field( + proto.ENUM, + number=1, + enum="IngestionDataSourceSettings.AzureEventHubs.State", + ) + resource_group: str = proto.Field( + proto.STRING, + number=2, + ) + namespace: str = proto.Field( + proto.STRING, + number=3, + ) + event_hub: str = proto.Field( + proto.STRING, + number=4, + ) + client_id: str = proto.Field( + proto.STRING, + number=5, + ) + tenant_id: str = proto.Field( + proto.STRING, + number=6, + ) + subscription_id: str = proto.Field( + proto.STRING, + number=7, + ) + gcp_service_account: str = proto.Field( + proto.STRING, + number=8, + ) + + class AwsMsk(proto.Message): + r"""Ingestion settings for Amazon MSK. + + Attributes: + state (google.pubsub_v1.types.IngestionDataSourceSettings.AwsMsk.State): + Output only. An output-only field that + indicates the state of the Amazon MSK ingestion + source. + cluster_arn (str): + Required. The Amazon Resource Name (ARN) that + uniquely identifies the cluster. + topic (str): + Required. The name of the topic in the Amazon + MSK cluster that Pub/Sub will import from. + aws_role_arn (str): + Required. AWS role ARN to be used for + Federated Identity authentication with Amazon + MSK. Check the Pub/Sub docs for how to set up + this role and the required permissions that need + to be attached to it. + gcp_service_account (str): + Required. The GCP service account to be used for Federated + Identity authentication with Amazon MSK (via a + ``AssumeRoleWithWebIdentity`` call for the provided role). + The ``aws_role_arn`` must be set up with + ``accounts.google.com:sub`` equals to this service account + number. + """ + + class State(proto.Enum): + r"""Possible states for managed ingestion from Amazon MSK. + + Values: + STATE_UNSPECIFIED (0): + Default value. This value is unused. + ACTIVE (1): + Ingestion is active. + MSK_PERMISSION_DENIED (2): + Permission denied encountered while consuming + data from Amazon MSK. + PUBLISH_PERMISSION_DENIED (3): + Permission denied encountered while + publishing to the topic. + CLUSTER_NOT_FOUND (4): + The provided MSK cluster wasn't found. + TOPIC_NOT_FOUND (5): + The provided topic wasn't found. + """ + + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + MSK_PERMISSION_DENIED = 2 + PUBLISH_PERMISSION_DENIED = 3 + CLUSTER_NOT_FOUND = 4 + TOPIC_NOT_FOUND = 5 + + state: "IngestionDataSourceSettings.AwsMsk.State" = proto.Field( + proto.ENUM, + number=1, + enum="IngestionDataSourceSettings.AwsMsk.State", + ) + cluster_arn: str = proto.Field( + proto.STRING, + number=2, + ) + topic: str = proto.Field( + proto.STRING, + number=3, + ) + aws_role_arn: str = proto.Field( + proto.STRING, + number=4, + ) + gcp_service_account: str = proto.Field( + proto.STRING, + number=5, + ) + + class ConfluentCloud(proto.Message): + r"""Ingestion settings for Confluent Cloud. + + Attributes: + state (google.pubsub_v1.types.IngestionDataSourceSettings.ConfluentCloud.State): + Output only. An output-only field that + indicates the state of the Confluent Cloud + ingestion source. + bootstrap_server (str): + Required. The address of the bootstrap + server. The format is url:port. + cluster_id (str): + Required. The id of the cluster. + topic (str): + Required. The name of the topic in the + Confluent Cloud cluster that Pub/Sub will import + from. + identity_pool_id (str): + Required. The id of the identity pool to be + used for Federated Identity authentication with + Confluent Cloud. See + https://docs.confluent.io/cloud/current/security/authenticate/workload-identities/identity-providers/oauth/identity-pools.html#add-oauth-identity-pools. + gcp_service_account (str): + Required. The GCP service account to be used for Federated + Identity authentication with ``identity_pool_id``. + """ + + class State(proto.Enum): + r"""Possible states for managed ingestion from Confluent Cloud. + + Values: + STATE_UNSPECIFIED (0): + Default value. This value is unused. + ACTIVE (1): + Ingestion is active. + CONFLUENT_CLOUD_PERMISSION_DENIED (2): + Permission denied encountered while consuming + data from Confluent Cloud. + PUBLISH_PERMISSION_DENIED (3): + Permission denied encountered while + publishing to the topic. + UNREACHABLE_BOOTSTRAP_SERVER (4): + The provided bootstrap server address is + unreachable. + CLUSTER_NOT_FOUND (5): + The provided cluster wasn't found. + TOPIC_NOT_FOUND (6): + The provided topic wasn't found. + """ + + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + CONFLUENT_CLOUD_PERMISSION_DENIED = 2 + PUBLISH_PERMISSION_DENIED = 3 + UNREACHABLE_BOOTSTRAP_SERVER = 4 + CLUSTER_NOT_FOUND = 5 + TOPIC_NOT_FOUND = 6 + + state: "IngestionDataSourceSettings.ConfluentCloud.State" = proto.Field( + proto.ENUM, + number=1, + enum="IngestionDataSourceSettings.ConfluentCloud.State", + ) + bootstrap_server: str = proto.Field( + proto.STRING, + number=2, + ) + cluster_id: str = proto.Field( + proto.STRING, + number=3, + ) + topic: str = proto.Field( + proto.STRING, + number=4, + ) + identity_pool_id: str = proto.Field( + proto.STRING, + number=5, + ) + gcp_service_account: str = proto.Field( + proto.STRING, + number=6, + ) + + aws_kinesis: AwsKinesis = proto.Field( + proto.MESSAGE, + number=1, + oneof="source", + message=AwsKinesis, + ) + cloud_storage: CloudStorage = proto.Field( + proto.MESSAGE, + number=2, + oneof="source", + message=CloudStorage, + ) + azure_event_hubs: AzureEventHubs = proto.Field( + proto.MESSAGE, + number=3, + oneof="source", + message=AzureEventHubs, + ) + aws_msk: AwsMsk = proto.Field( + proto.MESSAGE, + number=5, + oneof="source", + message=AwsMsk, + ) + confluent_cloud: ConfluentCloud = proto.Field( + proto.MESSAGE, + number=6, + oneof="source", + message=ConfluentCloud, + ) + platform_logs_settings: "PlatformLogsSettings" = proto.Field( + proto.MESSAGE, + number=4, + message="PlatformLogsSettings", + ) + + +class PlatformLogsSettings(proto.Message): + r"""Settings for Platform Logs produced by Pub/Sub. + + Attributes: + severity (google.pubsub_v1.types.PlatformLogsSettings.Severity): + Optional. The minimum severity level of + Platform Logs that will be written. + """ + + class Severity(proto.Enum): + r"""Severity levels of Platform Logs. + + Values: + SEVERITY_UNSPECIFIED (0): + Default value. Logs level is unspecified. + Logs will be disabled. + DISABLED (1): + Logs will be disabled. + DEBUG (2): + Debug logs and higher-severity logs will be + written. + INFO (3): + Info logs and higher-severity logs will be + written. + WARNING (4): + Warning logs and higher-severity logs will be + written. + ERROR (5): + Only error logs will be written. + """ + + SEVERITY_UNSPECIFIED = 0 + DISABLED = 1 + DEBUG = 2 + INFO = 3 + WARNING = 4 + ERROR = 5 + + severity: Severity = proto.Field( + proto.ENUM, + number=1, + enum=Severity, + ) + + +class IngestionFailureEvent(proto.Message): + r"""Payload of the Platform Log entry sent when a failure is + encountered while ingesting. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + topic (str): + Required. Name of the import topic. Format is: + projects/{project_name}/topics/{topic_name}. + error_message (str): + Required. Error details explaining why + ingestion to Pub/Sub has failed. + cloud_storage_failure (google.pubsub_v1.types.IngestionFailureEvent.CloudStorageFailure): + Optional. Failure when ingesting from Cloud + Storage. + + This field is a member of `oneof`_ ``failure``. + aws_msk_failure (google.pubsub_v1.types.IngestionFailureEvent.AwsMskFailureReason): + Optional. Failure when ingesting from Amazon + MSK. + + This field is a member of `oneof`_ ``failure``. + azure_event_hubs_failure (google.pubsub_v1.types.IngestionFailureEvent.AzureEventHubsFailureReason): + Optional. Failure when ingesting from Azure + Event Hubs. + + This field is a member of `oneof`_ ``failure``. + confluent_cloud_failure (google.pubsub_v1.types.IngestionFailureEvent.ConfluentCloudFailureReason): + Optional. Failure when ingesting from + Confluent Cloud. + + This field is a member of `oneof`_ ``failure``. + aws_kinesis_failure (google.pubsub_v1.types.IngestionFailureEvent.AwsKinesisFailureReason): + Optional. Failure when ingesting from AWS + Kinesis. + + This field is a member of `oneof`_ ``failure``. + """ + + class ApiViolationReason(proto.Message): + r"""Specifies the reason why some data may have been left out of the + desired Pub/Sub message due to the API message limits + (https://cloud.google.com/pubsub/quotas#resource_limits). For + example, when the number of attributes is larger than 100, the + number of attributes is truncated to 100 to respect the limit on the + attribute count. Other attribute limits are treated similarly. When + the size of the desired message would've been larger than 10MB, the + message won't be published at all, and ingestion of the subsequent + messages will proceed as normal. + + """ + + class AvroFailureReason(proto.Message): + r"""Set when an Avro file is unsupported or its format is not + valid. When this occurs, one or more Avro objects won't be + ingested. + + """ + + class SchemaViolationReason(proto.Message): + r"""Set when a Pub/Sub message fails to get published due to a + schema validation violation. + + """ + + class MessageTransformationFailureReason(proto.Message): + r"""Set when a Pub/Sub message fails to get published due to a + message transformation error. + + """ + + class CloudStorageFailure(proto.Message): + r"""Failure when ingesting from a Cloud Storage source. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + bucket (str): + Optional. Name of the Cloud Storage bucket + used for ingestion. + object_name (str): + Optional. Name of the Cloud Storage object + which contained the section that couldn't be + ingested. + object_generation (int): + Optional. Generation of the Cloud Storage + object which contained the section that couldn't + be ingested. + avro_failure_reason (google.pubsub_v1.types.IngestionFailureEvent.AvroFailureReason): + Optional. Failure encountered when parsing an + Avro file. + + This field is a member of `oneof`_ ``reason``. + api_violation_reason (google.pubsub_v1.types.IngestionFailureEvent.ApiViolationReason): + Optional. The Pub/Sub API limits prevented + the desired message from being published. + + This field is a member of `oneof`_ ``reason``. + schema_violation_reason (google.pubsub_v1.types.IngestionFailureEvent.SchemaViolationReason): + Optional. The Pub/Sub message failed schema + validation. + + This field is a member of `oneof`_ ``reason``. + message_transformation_failure_reason (google.pubsub_v1.types.IngestionFailureEvent.MessageTransformationFailureReason): + Optional. Failure encountered when applying a + message transformation to the Pub/Sub message. + + This field is a member of `oneof`_ ``reason``. + """ + + bucket: str = proto.Field( + proto.STRING, + number=1, + ) + object_name: str = proto.Field( + proto.STRING, + number=2, + ) + object_generation: int = proto.Field( + proto.INT64, + number=3, + ) + avro_failure_reason: "IngestionFailureEvent.AvroFailureReason" = proto.Field( + proto.MESSAGE, + number=5, + oneof="reason", + message="IngestionFailureEvent.AvroFailureReason", + ) + api_violation_reason: "IngestionFailureEvent.ApiViolationReason" = proto.Field( + proto.MESSAGE, + number=6, + oneof="reason", + message="IngestionFailureEvent.ApiViolationReason", + ) + schema_violation_reason: "IngestionFailureEvent.SchemaViolationReason" = ( + proto.Field( + proto.MESSAGE, + number=7, + oneof="reason", + message="IngestionFailureEvent.SchemaViolationReason", + ) + ) + message_transformation_failure_reason: "IngestionFailureEvent.MessageTransformationFailureReason" = proto.Field( + proto.MESSAGE, + number=8, + oneof="reason", + message="IngestionFailureEvent.MessageTransformationFailureReason", + ) + + class AwsMskFailureReason(proto.Message): + r"""Failure when ingesting from an Amazon MSK source. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + cluster_arn (str): + Optional. The ARN of the cluster of the topic + being ingested from. + kafka_topic (str): + Optional. The name of the Kafka topic being + ingested from. + partition_id (int): + Optional. The partition ID of the message + that failed to be ingested. + offset (int): + Optional. The offset within the partition of + the message that failed to be ingested. + api_violation_reason (google.pubsub_v1.types.IngestionFailureEvent.ApiViolationReason): + Optional. The Pub/Sub API limits prevented + the desired message from being published. + + This field is a member of `oneof`_ ``reason``. + schema_violation_reason (google.pubsub_v1.types.IngestionFailureEvent.SchemaViolationReason): + Optional. The Pub/Sub message failed schema + validation. + + This field is a member of `oneof`_ ``reason``. + message_transformation_failure_reason (google.pubsub_v1.types.IngestionFailureEvent.MessageTransformationFailureReason): + Optional. Failure encountered when applying a + message transformation to the Pub/Sub message. + + This field is a member of `oneof`_ ``reason``. + """ + + cluster_arn: str = proto.Field( + proto.STRING, + number=1, + ) + kafka_topic: str = proto.Field( + proto.STRING, + number=2, + ) + partition_id: int = proto.Field( + proto.INT64, + number=3, + ) + offset: int = proto.Field( + proto.INT64, + number=4, + ) + api_violation_reason: "IngestionFailureEvent.ApiViolationReason" = proto.Field( + proto.MESSAGE, + number=5, + oneof="reason", + message="IngestionFailureEvent.ApiViolationReason", + ) + schema_violation_reason: "IngestionFailureEvent.SchemaViolationReason" = ( + proto.Field( + proto.MESSAGE, + number=6, + oneof="reason", + message="IngestionFailureEvent.SchemaViolationReason", + ) + ) + message_transformation_failure_reason: "IngestionFailureEvent.MessageTransformationFailureReason" = proto.Field( + proto.MESSAGE, + number=7, + oneof="reason", + message="IngestionFailureEvent.MessageTransformationFailureReason", + ) + + class AzureEventHubsFailureReason(proto.Message): + r"""Failure when ingesting from an Azure Event Hubs source. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + namespace (str): + Optional. The namespace containing the event + hub being ingested from. + event_hub (str): + Optional. The name of the event hub being + ingested from. + partition_id (int): + Optional. The partition ID of the message + that failed to be ingested. + offset (int): + Optional. The offset within the partition of + the message that failed to be ingested. + api_violation_reason (google.pubsub_v1.types.IngestionFailureEvent.ApiViolationReason): + Optional. The Pub/Sub API limits prevented + the desired message from being published. + + This field is a member of `oneof`_ ``reason``. + schema_violation_reason (google.pubsub_v1.types.IngestionFailureEvent.SchemaViolationReason): + Optional. The Pub/Sub message failed schema + validation. + + This field is a member of `oneof`_ ``reason``. + message_transformation_failure_reason (google.pubsub_v1.types.IngestionFailureEvent.MessageTransformationFailureReason): + Optional. Failure encountered when applying a + message transformation to the Pub/Sub message. + + This field is a member of `oneof`_ ``reason``. + """ + + namespace: str = proto.Field( + proto.STRING, + number=1, + ) + event_hub: str = proto.Field( + proto.STRING, + number=2, + ) + partition_id: int = proto.Field( + proto.INT64, + number=3, + ) + offset: int = proto.Field( + proto.INT64, + number=4, + ) + api_violation_reason: "IngestionFailureEvent.ApiViolationReason" = proto.Field( + proto.MESSAGE, + number=5, + oneof="reason", + message="IngestionFailureEvent.ApiViolationReason", + ) + schema_violation_reason: "IngestionFailureEvent.SchemaViolationReason" = ( + proto.Field( + proto.MESSAGE, + number=6, + oneof="reason", + message="IngestionFailureEvent.SchemaViolationReason", + ) + ) + message_transformation_failure_reason: "IngestionFailureEvent.MessageTransformationFailureReason" = proto.Field( + proto.MESSAGE, + number=7, + oneof="reason", + message="IngestionFailureEvent.MessageTransformationFailureReason", + ) + + class ConfluentCloudFailureReason(proto.Message): + r"""Failure when ingesting from a Confluent Cloud source. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + cluster_id (str): + Optional. The cluster ID containing the topic + being ingested from. + kafka_topic (str): + Optional. The name of the Kafka topic being + ingested from. + partition_id (int): + Optional. The partition ID of the message + that failed to be ingested. + offset (int): + Optional. The offset within the partition of + the message that failed to be ingested. + api_violation_reason (google.pubsub_v1.types.IngestionFailureEvent.ApiViolationReason): + Optional. The Pub/Sub API limits prevented + the desired message from being published. + + This field is a member of `oneof`_ ``reason``. + schema_violation_reason (google.pubsub_v1.types.IngestionFailureEvent.SchemaViolationReason): + Optional. The Pub/Sub message failed schema + validation. + + This field is a member of `oneof`_ ``reason``. + message_transformation_failure_reason (google.pubsub_v1.types.IngestionFailureEvent.MessageTransformationFailureReason): + Optional. Failure encountered when applying a + message transformation to the Pub/Sub message. + + This field is a member of `oneof`_ ``reason``. + """ + + cluster_id: str = proto.Field( + proto.STRING, + number=1, + ) + kafka_topic: str = proto.Field( + proto.STRING, + number=2, + ) + partition_id: int = proto.Field( + proto.INT64, + number=3, + ) + offset: int = proto.Field( + proto.INT64, + number=4, + ) + api_violation_reason: "IngestionFailureEvent.ApiViolationReason" = proto.Field( + proto.MESSAGE, + number=5, + oneof="reason", + message="IngestionFailureEvent.ApiViolationReason", + ) + schema_violation_reason: "IngestionFailureEvent.SchemaViolationReason" = ( + proto.Field( + proto.MESSAGE, + number=6, + oneof="reason", + message="IngestionFailureEvent.SchemaViolationReason", + ) + ) + message_transformation_failure_reason: "IngestionFailureEvent.MessageTransformationFailureReason" = proto.Field( + proto.MESSAGE, + number=7, + oneof="reason", + message="IngestionFailureEvent.MessageTransformationFailureReason", + ) + + class AwsKinesisFailureReason(proto.Message): + r"""Failure when ingesting from an AWS Kinesis source. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + stream_arn (str): + Optional. The stream ARN of the Kinesis + stream being ingested from. + partition_key (str): + Optional. The partition key of the message + that failed to be ingested. + sequence_number (str): + Optional. The sequence number of the message + that failed to be ingested. + schema_violation_reason (google.pubsub_v1.types.IngestionFailureEvent.SchemaViolationReason): + Optional. The Pub/Sub message failed schema + validation. + + This field is a member of `oneof`_ ``reason``. + message_transformation_failure_reason (google.pubsub_v1.types.IngestionFailureEvent.MessageTransformationFailureReason): + Optional. Failure encountered when applying a + message transformation to the Pub/Sub message. + + This field is a member of `oneof`_ ``reason``. + api_violation_reason (google.pubsub_v1.types.IngestionFailureEvent.ApiViolationReason): + Optional. The message failed to be published + due to an API violation. This is only set when + the size of the data field of the Kinesis record + is zero. + + This field is a member of `oneof`_ ``reason``. + """ + + stream_arn: str = proto.Field( + proto.STRING, + number=1, + ) + partition_key: str = proto.Field( + proto.STRING, + number=2, + ) + sequence_number: str = proto.Field( + proto.STRING, + number=3, + ) + schema_violation_reason: "IngestionFailureEvent.SchemaViolationReason" = ( + proto.Field( + proto.MESSAGE, + number=4, + oneof="reason", + message="IngestionFailureEvent.SchemaViolationReason", + ) + ) + message_transformation_failure_reason: "IngestionFailureEvent.MessageTransformationFailureReason" = proto.Field( + proto.MESSAGE, + number=5, + oneof="reason", + message="IngestionFailureEvent.MessageTransformationFailureReason", + ) + api_violation_reason: "IngestionFailureEvent.ApiViolationReason" = proto.Field( + proto.MESSAGE, + number=6, + oneof="reason", + message="IngestionFailureEvent.ApiViolationReason", + ) + + topic: str = proto.Field( + proto.STRING, + number=1, + ) + error_message: str = proto.Field( + proto.STRING, + number=2, + ) + cloud_storage_failure: CloudStorageFailure = proto.Field( + proto.MESSAGE, + number=3, + oneof="failure", + message=CloudStorageFailure, + ) + aws_msk_failure: AwsMskFailureReason = proto.Field( + proto.MESSAGE, + number=4, + oneof="failure", + message=AwsMskFailureReason, + ) + azure_event_hubs_failure: AzureEventHubsFailureReason = proto.Field( + proto.MESSAGE, + number=5, + oneof="failure", + message=AzureEventHubsFailureReason, + ) + confluent_cloud_failure: ConfluentCloudFailureReason = proto.Field( + proto.MESSAGE, + number=6, + oneof="failure", + message=ConfluentCloudFailureReason, + ) + aws_kinesis_failure: AwsKinesisFailureReason = proto.Field( + proto.MESSAGE, + number=7, + oneof="failure", + message=AwsKinesisFailureReason, + ) + + +class JavaScriptUDF(proto.Message): + r"""User-defined JavaScript function that can transform or filter + a Pub/Sub message. + + Attributes: + function_name (str): + Required. Name of the JavasScript function + that should applied to Pub/Sub messages. + code (str): + Required. JavaScript code that contains a function + ``function_name`` with the below signature: + + :: + + /** + * Transforms a Pub/Sub message. + + * @return {(Object)>|null)} - To + * filter a message, return `null`. To transform a message return a map + * with the following keys: + * - (required) 'data' : {string} + * - (optional) 'attributes' : {Object} + * Returning empty `attributes` will remove all attributes from the + * message. + * + * @param {(Object)>} Pub/Sub + * message. Keys: + * - (required) 'data' : {string} + * - (required) 'attributes' : {Object} + * + * @param {Object} metadata - Pub/Sub message metadata. + * Keys: + * - (optional) 'message_id' : {string} + * - (optional) 'publish_time': {string} YYYY-MM-DDTHH:MM:SSZ format + * - (optional) 'ordering_key': {string} + */ + + function (message, metadata) { + } + """ + + function_name: str = proto.Field( + proto.STRING, + number=1, + ) + code: str = proto.Field( + proto.STRING, + number=2, + ) + + +class AIInference(proto.Message): + r"""Configuration for making inference requests against Vertex AI + models. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + endpoint (str): + Required. An endpoint to a Vertex AI model of the form + ``projects/{project}/locations/{location}/endpoints/{endpoint}`` + or + ``projects/{project}/locations/{location}/publishers/{publisher}/models/{model}``. + Vertex AI API requests will be sent to this endpoint. + unstructured_inference (google.pubsub_v1.types.AIInference.UnstructuredInference): + Optional. Requests and responses can be any + arbitrary JSON object. + + This field is a member of `oneof`_ ``inference_mode``. + service_account_email (str): + Optional. The service account to use to make prediction + requests against endpoints. The resource creator or updater + that specifies this field must have + ``iam.serviceAccounts.actAs`` permission on the service + account. If not specified, the Pub/Sub `service + agent `__, + service-{project_number}@gcp-sa-pubsub.iam.gserviceaccount.com, + is used. + """ + + class UnstructuredInference(proto.Message): + r"""Configuration for making inferences using arbitrary JSON + payloads. + + Attributes: + parameters (google.protobuf.struct_pb2.Struct): + Optional. A parameters object to be included + in each inference request. The parameters object + is combined with the data field of the Pub/Sub + message to form the inference request. + """ + + parameters: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=1, + message=struct_pb2.Struct, + ) + + endpoint: str = proto.Field( + proto.STRING, + number=1, + ) + unstructured_inference: UnstructuredInference = proto.Field( + proto.MESSAGE, + number=2, + oneof="inference_mode", + message=UnstructuredInference, + ) + service_account_email: str = proto.Field( + proto.STRING, + number=3, + ) + + +class MessageTransform(proto.Message): + r"""All supported message transforms types. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + javascript_udf (google.pubsub_v1.types.JavaScriptUDF): + Optional. JavaScript User Defined Function. If multiple + JavaScriptUDF's are specified on a resource, each must have + a unique ``function_name``. + + This field is a member of `oneof`_ ``transform``. + ai_inference (google.pubsub_v1.types.AIInference): + Optional. AI Inference. Specifies the Vertex + AI endpoint that inference requests built from + the Pub/Sub message data and provided parameters + will be sent to. + + This field is a member of `oneof`_ ``transform``. + enabled (bool): + Optional. This field is deprecated, use the ``disabled`` + field to disable transforms. + disabled (bool): + Optional. If true, the transform is disabled and will not be + applied to messages. Defaults to ``false``. + """ + + javascript_udf: "JavaScriptUDF" = proto.Field( + proto.MESSAGE, + number=2, + oneof="transform", + message="JavaScriptUDF", + ) + ai_inference: "AIInference" = proto.Field( + proto.MESSAGE, + number=6, + oneof="transform", + message="AIInference", + ) + enabled: bool = proto.Field( + proto.BOOL, + number=3, + ) + disabled: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class Topic(proto.Message): + r"""A topic resource. + + Attributes: + name (str): + Required. Identifier. The name of the topic. It must have + the format ``"projects/{project}/topics/{topic}"``. + ``{topic}`` must start with a letter, and contain only + letters (``[A-Za-z]``), numbers (``[0-9]``), dashes (``-``), + underscores (``_``), periods (``.``), tildes (``~``), plus + (``+``) or percent signs (``%``). It must be between 3 and + 255 characters in length, and it must not start with + ``"goog"``. + labels (MutableMapping[str, str]): + Optional. See [Creating and managing labels] + (https://cloud.google.com/pubsub/docs/labels). + message_storage_policy (google.pubsub_v1.types.MessageStoragePolicy): + Optional. Policy constraining the set of + Google Cloud Platform regions where messages + published to the topic may be stored. If not + present, then no constraints are in effect. + kms_key_name (str): + Optional. The resource name of the Cloud KMS CryptoKey to be + used to protect access to messages published on this topic. + + The expected format is + ``projects/*/locations/*/keyRings/*/cryptoKeys/*``. + schema_settings (google.pubsub_v1.types.SchemaSettings): + Optional. Settings for validating messages + published against a schema. + satisfies_pzs (bool): + Optional. Reserved for future use. This field + is set only in responses from the server; it is + ignored if it is set in any requests. + message_retention_duration (google.protobuf.duration_pb2.Duration): + Optional. Indicates the minimum duration to retain a message + after it is published to the topic. If this field is set, + messages published to the topic in the last + ``message_retention_duration`` are always available to + subscribers. For instance, it allows any attached + subscription to `seek to a + timestamp `__ + that is up to ``message_retention_duration`` in the past. If + this field is not set, message retention is controlled by + settings on individual subscriptions. Cannot be more than 31 + days or less than 10 minutes. + state (google.pubsub_v1.types.Topic.State): + Output only. An output-only field indicating + the state of the topic. + ingestion_data_source_settings (google.pubsub_v1.types.IngestionDataSourceSettings): + Optional. Settings for ingestion from a data + source into this topic. + message_transforms (MutableSequence[google.pubsub_v1.types.MessageTransform]): + Optional. Transforms to be applied to + messages published to the topic. Transforms are + applied in the order specified. + tags (MutableMapping[str, str]): + Optional. Input only. Immutable. Tag + keys/values directly bound to this resource. For + example: + + "123/environment": "production", + "123/costCenter": "marketing" + See + https://docs.cloud.google.com/pubsub/docs/tags + for more information on using tags with Pub/Sub + resources. + """ + + class State(proto.Enum): + r"""The state of the topic. + + Values: + STATE_UNSPECIFIED (0): + Default value. This value is unused. + ACTIVE (1): + The topic does not have any persistent + errors. + INGESTION_RESOURCE_ERROR (2): + Ingestion from the data source has + encountered a permanent error. See the more + detailed error state in the corresponding + ingestion source configuration. + """ + + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + INGESTION_RESOURCE_ERROR = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + message_storage_policy: "MessageStoragePolicy" = proto.Field( + proto.MESSAGE, + number=3, + message="MessageStoragePolicy", + ) + kms_key_name: str = proto.Field( + proto.STRING, + number=5, + ) + schema_settings: "SchemaSettings" = proto.Field( + proto.MESSAGE, + number=6, + message="SchemaSettings", + ) + satisfies_pzs: bool = proto.Field( + proto.BOOL, + number=7, + ) + message_retention_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=8, + message=duration_pb2.Duration, + ) + state: State = proto.Field( + proto.ENUM, + number=9, + enum=State, + ) + ingestion_data_source_settings: "IngestionDataSourceSettings" = proto.Field( + proto.MESSAGE, + number=10, + message="IngestionDataSourceSettings", + ) + message_transforms: MutableSequence["MessageTransform"] = proto.RepeatedField( + proto.MESSAGE, + number=13, + message="MessageTransform", + ) + tags: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=14, + ) + + +class PubsubMessage(proto.Message): + r"""A message that is published by publishers and consumed by + subscribers. The message must contain either a non-empty data field + or at least one attribute. Note that client libraries represent this + object differently depending on the language. See the corresponding + `client library + documentation `__ + for more information. See [quotas and limits] + (https://cloud.google.com/pubsub/quotas) for more information about + message limits. + + Attributes: + data (bytes): + Optional. The message data field. If this + field is empty, the message must contain at + least one attribute. + attributes (MutableMapping[str, str]): + Optional. Attributes for this message. If + this field is empty, the message must contain + non-empty data. This can be used to filter + messages on the subscription. + message_id (str): + ID of this message, assigned by the server when the message + is published. Guaranteed to be unique within the topic. This + value may be read by a subscriber that receives a + ``PubsubMessage`` via a ``Pull`` call or a push delivery. It + must not be populated by the publisher in a ``Publish`` + call. + publish_time (google.protobuf.timestamp_pb2.Timestamp): + The time at which the message was published, populated by + the server when it receives the ``Publish`` call. It must + not be populated by the publisher in a ``Publish`` call. + ordering_key (str): + Optional. If non-empty, identifies related messages for + which publish order should be respected. If a + ``Subscription`` has ``enable_message_ordering`` set to + ``true``, messages published with the same non-empty + ``ordering_key`` value will be delivered to subscribers in + the order in which they are received by the Pub/Sub system. + All ``PubsubMessage``\ s published in a given + ``PublishRequest`` must specify the same ``ordering_key`` + value. For more information, see `ordering + messages `__. + """ + + data: bytes = proto.Field( + proto.BYTES, + number=1, + ) + attributes: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + message_id: str = proto.Field( + proto.STRING, + number=3, + ) + publish_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + ordering_key: str = proto.Field( + proto.STRING, + number=5, + ) + + +class GetTopicRequest(proto.Message): + r"""Request for the GetTopic method. + + Attributes: + topic (str): + Required. The name of the topic to get. Format is + ``projects/{project}/topics/{topic}``. + """ + + topic: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateTopicRequest(proto.Message): + r"""Request for the UpdateTopic method. + + Attributes: + topic (google.pubsub_v1.types.Topic): + Required. The updated topic object. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Indicates which fields in the provided topic to + update. Must be specified and non-empty. Note that if + ``update_mask`` contains "message_storage_policy" but the + ``message_storage_policy`` is not set in the ``topic`` + provided above, then the updated value is determined by the + policy configured at the project or organization level. + """ + + topic: "Topic" = proto.Field( + proto.MESSAGE, + number=1, + message="Topic", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class PublishRequest(proto.Message): + r"""Request for the Publish method. + + Attributes: + topic (str): + Required. The messages in the request will be published on + this topic. Format is ``projects/{project}/topics/{topic}``. + messages (MutableSequence[google.pubsub_v1.types.PubsubMessage]): + Required. The messages to publish. + """ + + topic: str = proto.Field( + proto.STRING, + number=1, + ) + messages: MutableSequence["PubsubMessage"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="PubsubMessage", + ) + + +class PublishResponse(proto.Message): + r"""Response for the ``Publish`` method. + + Attributes: + message_ids (MutableSequence[str]): + Optional. The server-assigned ID of each + published message, in the same order as the + messages in the request. IDs are guaranteed to + be unique within the topic. + """ + + message_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +class ListTopicsRequest(proto.Message): + r"""Request for the ``ListTopics`` method. + + Attributes: + project (str): + Required. The name of the project in which to list topics. + Format is ``projects/{project-id}``. + page_size (int): + Optional. Maximum number of topics to return. + page_token (str): + Optional. The value returned by the last + ``ListTopicsResponse``; indicates that this is a + continuation of a prior ``ListTopics`` call, and that the + system should return the next page of data. + """ + + project: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListTopicsResponse(proto.Message): + r"""Response for the ``ListTopics`` method. + + Attributes: + topics (MutableSequence[google.pubsub_v1.types.Topic]): + Optional. The resulting topics. + next_page_token (str): + Optional. If not empty, indicates that there may be more + topics that match the request; this value should be passed + in a new ``ListTopicsRequest``. + """ + + @property + def raw_page(self): + return self + + topics: MutableSequence["Topic"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Topic", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListTopicSubscriptionsRequest(proto.Message): + r"""Request for the ``ListTopicSubscriptions`` method. + + Attributes: + topic (str): + Required. The name of the topic that subscriptions are + attached to. Format is + ``projects/{project}/topics/{topic}``. + page_size (int): + Optional. Maximum number of subscription + names to return. + page_token (str): + Optional. The value returned by the last + ``ListTopicSubscriptionsResponse``; indicates that this is a + continuation of a prior ``ListTopicSubscriptions`` call, and + that the system should return the next page of data. + """ + + topic: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListTopicSubscriptionsResponse(proto.Message): + r"""Response for the ``ListTopicSubscriptions`` method. + + Attributes: + subscriptions (MutableSequence[str]): + Optional. The names of subscriptions attached + to the topic specified in the request. + next_page_token (str): + Optional. If not empty, indicates that there may be more + subscriptions that match the request; this value should be + passed in a new ``ListTopicSubscriptionsRequest`` to get + more subscriptions. + """ + + @property + def raw_page(self): + return self + + subscriptions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListTopicSnapshotsRequest(proto.Message): + r"""Request for the ``ListTopicSnapshots`` method. + + Attributes: + topic (str): + Required. The name of the topic that snapshots are attached + to. Format is ``projects/{project}/topics/{topic}``. + page_size (int): + Optional. Maximum number of snapshot names to + return. + page_token (str): + Optional. The value returned by the last + ``ListTopicSnapshotsResponse``; indicates that this is a + continuation of a prior ``ListTopicSnapshots`` call, and + that the system should return the next page of data. + """ + + topic: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListTopicSnapshotsResponse(proto.Message): + r"""Response for the ``ListTopicSnapshots`` method. + + Attributes: + snapshots (MutableSequence[str]): + Optional. The names of the snapshots that + match the request. + next_page_token (str): + Optional. If not empty, indicates that there may be more + snapshots that match the request; this value should be + passed in a new ``ListTopicSnapshotsRequest`` to get more + snapshots. + """ + + @property + def raw_page(self): + return self + + snapshots: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteTopicRequest(proto.Message): + r"""Request for the ``DeleteTopic`` method. + + Attributes: + topic (str): + Required. Name of the topic to delete. Format is + ``projects/{project}/topics/{topic}``. + """ + + topic: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DetachSubscriptionRequest(proto.Message): + r"""Request for the DetachSubscription method. + + Attributes: + subscription (str): + Required. The subscription to detach. Format is + ``projects/{project}/subscriptions/{subscription}``. + """ + + subscription: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DetachSubscriptionResponse(proto.Message): + r"""Response for the DetachSubscription method. + Reserved for future use. + + """ + + +class Subscription(proto.Message): + r"""A subscription resource. If none of ``push_config``, + ``bigquery_config``, or ``cloud_storage_config`` is set, then the + subscriber will pull and ack messages using API methods. At most one + of these fields may be set. + + Attributes: + name (str): + Required. Identifier. The name of the subscription. It must + have the format + ``"projects/{project}/subscriptions/{subscription}"``. + ``{subscription}`` must start with a letter, and contain + only letters (``[A-Za-z]``), numbers (``[0-9]``), dashes + (``-``), underscores (``_``), periods (``.``), tildes + (``~``), plus (``+``) or percent signs (``%``). It must be + between 3 and 255 characters in length, and it must not + start with ``"goog"``. + topic (str): + Required. The name of the topic from which this subscription + is receiving messages. Format is + ``projects/{project}/topics/{topic}``. The value of this + field will be ``_deleted-topic_`` if the topic has been + deleted. + push_config (google.pubsub_v1.types.PushConfig): + Optional. If push delivery is used with this + subscription, this field is used to configure + it. + bigquery_config (google.pubsub_v1.types.BigQueryConfig): + Optional. If delivery to BigQuery is used + with this subscription, this field is used to + configure it. + cloud_storage_config (google.pubsub_v1.types.CloudStorageConfig): + Optional. If delivery to Google Cloud Storage + is used with this subscription, this field is + used to configure it. + bigtable_config (google.pubsub_v1.types.BigtableConfig): + Optional. If delivery to Bigtable is used + with this subscription, this field is used to + configure it. + ack_deadline_seconds (int): + Optional. The approximate amount of time (on a best-effort + basis) Pub/Sub waits for the subscriber to acknowledge + receipt before resending the message. In the interval after + the message is delivered and before it is acknowledged, it + is considered to be *outstanding*. During that time period, + the message will not be redelivered (on a best-effort + basis). + + For pull subscriptions, this value is used as the initial + value for the ack deadline. To override this value for a + given message, call ``ModifyAckDeadline`` with the + corresponding ``ack_id`` if using non-streaming pull or send + the ``ack_id`` in a ``StreamingModifyAckDeadlineRequest`` if + using streaming pull. The minimum custom deadline you can + specify is 10 seconds. The maximum custom deadline you can + specify is 600 seconds (10 minutes). If this parameter is 0, + a default value of 10 seconds is used. + + For push delivery, this value is also used to set the + request timeout for the call to the push endpoint. + + If the subscriber never acknowledges the message, the + Pub/Sub system will eventually redeliver the message. + retain_acked_messages (bool): + Optional. Indicates whether to retain acknowledged messages. + If true, then messages are not expunged from the + subscription's backlog, even if they are acknowledged, until + they fall out of the ``message_retention_duration`` window. + This must be true if you would like to [``Seek`` to a + timestamp] + (https://cloud.google.com/pubsub/docs/replay-overview#seek_to_a_time) + in the past to replay previously-acknowledged messages. + message_retention_duration (google.protobuf.duration_pb2.Duration): + Optional. How long to retain unacknowledged messages in the + subscription's backlog, from the moment a message is + published. If ``retain_acked_messages`` is true, then this + also configures the retention of acknowledged messages, and + thus configures how far back in time a ``Seek`` can be done. + Defaults to 7 days. Cannot be more than 31 days or less than + 10 minutes. + labels (MutableMapping[str, str]): + Optional. See `Creating and managing + labels `__. + enable_message_ordering (bool): + Optional. If true, messages published with the same + ``ordering_key`` in ``PubsubMessage`` will be delivered to + the subscribers in the order in which they are received by + the Pub/Sub system. Otherwise, they may be delivered in any + order. + expiration_policy (google.pubsub_v1.types.ExpirationPolicy): + Optional. A policy that specifies the conditions for this + subscription's expiration. A subscription is considered + active as long as any connected subscriber is successfully + consuming messages from the subscription or is issuing + operations on the subscription. If ``expiration_policy`` is + not set, a *default policy* with ``ttl`` of 31 days will be + used. The minimum allowed value for + ``expiration_policy.ttl`` is 1 day. If ``expiration_policy`` + is set, but ``expiration_policy.ttl`` is not set, the + subscription never expires. + filter (str): + Optional. An expression written in the Pub/Sub `filter + language `__. + If non-empty, then only ``PubsubMessage``\ s whose + ``attributes`` field matches the filter are delivered on + this subscription. If empty, then no messages are filtered + out. + dead_letter_policy (google.pubsub_v1.types.DeadLetterPolicy): + Optional. A policy that specifies the conditions for dead + lettering messages in this subscription. If + dead_letter_policy is not set, dead lettering is disabled. + + The Pub/Sub service account associated with this + subscriptions's parent project (i.e., + service-{project_number}@gcp-sa-pubsub.iam.gserviceaccount.com) + must have permission to Acknowledge() messages on this + subscription. + retry_policy (google.pubsub_v1.types.RetryPolicy): + Optional. A policy that specifies how Pub/Sub + retries message delivery for this subscription. + + If not set, the default retry policy is applied. + This generally implies that messages will be + retried as soon as possible for healthy + subscribers. RetryPolicy will be triggered on + NACKs or acknowledgment deadline exceeded events + for a given message. + detached (bool): + Optional. Indicates whether the subscription is detached + from its topic. Detached subscriptions don't receive + messages from their topic and don't retain any backlog. + ``Pull`` and ``StreamingPull`` requests will return + FAILED_PRECONDITION. If the subscription is a push + subscription, pushes to the endpoint will not be made. + enable_exactly_once_delivery (bool): + Optional. If true, Pub/Sub provides the following guarantees + for the delivery of a message with a given value of + ``message_id`` on this subscription: + + - The message sent to a subscriber is guaranteed not to be + resent before the message's acknowledgment deadline + expires. + - An acknowledged message will not be resent to a + subscriber. + + Note that subscribers may still receive multiple copies of a + message when ``enable_exactly_once_delivery`` is true if the + message was published multiple times by a publisher client. + These copies are considered distinct by Pub/Sub and have + distinct ``message_id`` values. + topic_message_retention_duration (google.protobuf.duration_pb2.Duration): + Output only. Indicates the minimum duration for which a + message is retained after it is published to the + subscription's topic. If this field is set, messages + published to the subscription's topic in the last + ``topic_message_retention_duration`` are always available to + subscribers. See the ``message_retention_duration`` field in + ``Topic``. This field is set only in responses from the + server; it is ignored if it is set in any requests. + state (google.pubsub_v1.types.Subscription.State): + Output only. An output-only field indicating + whether or not the subscription can receive + messages. + analytics_hub_subscription_info (google.pubsub_v1.types.Subscription.AnalyticsHubSubscriptionInfo): + Output only. Information about the associated + Analytics Hub subscription. Only set if the + subscription is created by Analytics Hub. + message_transforms (MutableSequence[google.pubsub_v1.types.MessageTransform]): + Optional. Transforms to be applied to + messages before they are delivered to + subscribers. Transforms are applied in the order + specified. + tags (MutableMapping[str, str]): + Optional. Input only. Immutable. Tag + keys/values directly bound to this resource. For + example: + + "123/environment": "production", + "123/costCenter": "marketing" + See + https://docs.cloud.google.com/pubsub/docs/tags + for more information on using tags with Pub/Sub + resources. + """ + + class State(proto.Enum): + r"""Possible states for a subscription. + + Values: + STATE_UNSPECIFIED (0): + Default value. This value is unused. + ACTIVE (1): + The subscription can actively receive + messages + RESOURCE_ERROR (2): + The subscription cannot receive messages + because of an error with the resource to which + it pushes messages. See the more detailed error + state in the corresponding configuration. + """ + + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + RESOURCE_ERROR = 2 + + class AnalyticsHubSubscriptionInfo(proto.Message): + r"""Information about an associated `Analytics Hub + subscription `__. + + Attributes: + listing (str): + Optional. The name of the associated Analytics Hub listing + resource. Pattern: + "projects/{project}/locations/{location}/dataExchanges/{data_exchange}/listings/{listing}". + subscription (str): + Optional. The name of the associated + Analytics Hub subscription resource. Pattern: + + "projects/{project}/locations/{location}/subscriptions/{subscription}". + """ + + listing: str = proto.Field( + proto.STRING, + number=1, + ) + subscription: str = proto.Field( + proto.STRING, + number=2, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + topic: str = proto.Field( + proto.STRING, + number=2, + ) + push_config: "PushConfig" = proto.Field( + proto.MESSAGE, + number=4, + message="PushConfig", + ) + bigquery_config: "BigQueryConfig" = proto.Field( + proto.MESSAGE, + number=18, + message="BigQueryConfig", + ) + cloud_storage_config: "CloudStorageConfig" = proto.Field( + proto.MESSAGE, + number=22, + message="CloudStorageConfig", + ) + bigtable_config: "BigtableConfig" = proto.Field( + proto.MESSAGE, + number=27, + message="BigtableConfig", + ) + ack_deadline_seconds: int = proto.Field( + proto.INT32, + number=5, + ) + retain_acked_messages: bool = proto.Field( + proto.BOOL, + number=7, + ) + message_retention_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=8, + message=duration_pb2.Duration, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=9, + ) + enable_message_ordering: bool = proto.Field( + proto.BOOL, + number=10, + ) + expiration_policy: "ExpirationPolicy" = proto.Field( + proto.MESSAGE, + number=11, + message="ExpirationPolicy", + ) + filter: str = proto.Field( + proto.STRING, + number=12, + ) + dead_letter_policy: "DeadLetterPolicy" = proto.Field( + proto.MESSAGE, + number=13, + message="DeadLetterPolicy", + ) + retry_policy: "RetryPolicy" = proto.Field( + proto.MESSAGE, + number=14, + message="RetryPolicy", + ) + detached: bool = proto.Field( + proto.BOOL, + number=15, + ) + enable_exactly_once_delivery: bool = proto.Field( + proto.BOOL, + number=16, + ) + topic_message_retention_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=17, + message=duration_pb2.Duration, + ) + state: State = proto.Field( + proto.ENUM, + number=19, + enum=State, + ) + analytics_hub_subscription_info: AnalyticsHubSubscriptionInfo = proto.Field( + proto.MESSAGE, + number=23, + message=AnalyticsHubSubscriptionInfo, + ) + message_transforms: MutableSequence["MessageTransform"] = proto.RepeatedField( + proto.MESSAGE, + number=25, + message="MessageTransform", + ) + tags: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=26, + ) + + +class RetryPolicy(proto.Message): + r"""A policy that specifies how Pub/Sub retries message delivery. + + Retry delay will be exponential based on provided minimum and + maximum backoffs. https://en.wikipedia.org/wiki/Exponential_backoff. + + RetryPolicy will be triggered on NACKs or acknowledgment deadline + exceeded events for a given message. + + Retry Policy is implemented on a best effort basis. At times, the + delay between consecutive deliveries may not match the + configuration. That is, delay can be more or less than configured + backoff. + + Attributes: + minimum_backoff (google.protobuf.duration_pb2.Duration): + Optional. The minimum delay between + consecutive deliveries of a given message. Value + should be between 0 and 600 seconds. Defaults to + 10 seconds. + maximum_backoff (google.protobuf.duration_pb2.Duration): + Optional. The maximum delay between + consecutive deliveries of a given message. Value + should be between 0 and 600 seconds. Defaults to + 600 seconds. + """ + + minimum_backoff: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + maximum_backoff: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + +class DeadLetterPolicy(proto.Message): + r"""Dead lettering is done on a best effort basis. The same + message might be dead lettered multiple times. + + If validation on any of the fields fails at subscription + creation/updation, the create/update subscription request will + fail. + + Attributes: + dead_letter_topic (str): + Optional. The name of the topic to which dead letter + messages should be published. Format is + ``projects/{project}/topics/{topic}``.The Pub/Sub service + account associated with the enclosing subscription's parent + project (i.e., + service-{project_number}@gcp-sa-pubsub.iam.gserviceaccount.com) + must have permission to Publish() to this topic. + + The operation will fail if the topic does not exist. Users + should ensure that there is a subscription attached to this + topic since messages published to a topic with no + subscriptions are lost. + max_delivery_attempts (int): + Optional. The maximum number of delivery attempts for any + message. The value must be between 5 and 100. + + The number of delivery attempts is defined as 1 + (the sum + of number of NACKs and number of times the acknowledgment + deadline has been exceeded for the message). + + A NACK is any call to ModifyAckDeadline with a 0 deadline. + Note that client libraries may automatically extend + ack_deadlines. + + This field will be honored on a best effort basis. + + If this parameter is 0, a default value of 5 is used. + """ + + dead_letter_topic: str = proto.Field( + proto.STRING, + number=1, + ) + max_delivery_attempts: int = proto.Field( + proto.INT32, + number=2, + ) + + +class ExpirationPolicy(proto.Message): + r"""A policy that specifies the conditions for resource + expiration (i.e., automatic resource deletion). + + Attributes: + ttl (google.protobuf.duration_pb2.Duration): + Optional. Specifies the "time-to-live" duration for an + associated resource. The resource expires if it is not + active for a period of ``ttl``. The definition of "activity" + depends on the type of the associated resource. The minimum + and maximum allowed values for ``ttl`` depend on the type of + the associated resource, as well. If ``ttl`` is not set, the + associated resource never expires. + """ + + ttl: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + + +class PushConfig(proto.Message): + r"""Configuration for a push delivery endpoint. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + push_endpoint (str): + Optional. A URL locating the endpoint to which messages + should be pushed. For example, a Webhook endpoint might use + ``https://example.com/push``. + attributes (MutableMapping[str, str]): + Optional. Endpoint configuration attributes that can be used + to control different aspects of the message delivery. + + The only currently supported attribute is + ``x-goog-version``, which you can use to change the format + of the pushed message. This attribute indicates the version + of the data expected by the endpoint. This controls the + shape of the pushed message (i.e., its fields and metadata). + + If not present during the ``CreateSubscription`` call, it + will default to the version of the Pub/Sub API used to make + such call. If not present in a ``ModifyPushConfig`` call, + its value will not be changed. ``GetSubscription`` calls + will always return a valid version, even if the subscription + was created without this attribute. + + The only supported values for the ``x-goog-version`` + attribute are: + + - ``v1beta1``: uses the push format defined in the v1beta1 + Pub/Sub API. + - ``v1`` or ``v1beta2``: uses the push format defined in the + v1 Pub/Sub API. + + For example: ``attributes { "x-goog-version": "v1" }`` + oidc_token (google.pubsub_v1.types.PushConfig.OidcToken): + Optional. If specified, Pub/Sub will generate and attach an + OIDC JWT token as an ``Authorization`` header in the HTTP + request for every pushed message. + + This field is a member of `oneof`_ ``authentication_method``. + pubsub_wrapper (google.pubsub_v1.types.PushConfig.PubsubWrapper): + Optional. When set, the payload to the push + endpoint is in the form of the JSON + representation of a PubsubMessage + (https://cloud.google.com/pubsub/docs/reference/rpc/google.pubsub.v1#pubsubmessage). + + This field is a member of `oneof`_ ``wrapper``. + no_wrapper (google.pubsub_v1.types.PushConfig.NoWrapper): + Optional. When set, the payload to the push + endpoint is not wrapped. + + This field is a member of `oneof`_ ``wrapper``. + """ + + class OidcToken(proto.Message): + r"""Contains information needed for generating an `OpenID Connect + token `__. + + Attributes: + service_account_email (str): + Optional. `Service account + email `__ + used for generating the OIDC token. For more information on + setting up authentication, see `Push + subscriptions `__. + audience (str): + Optional. Audience to be used when generating + OIDC token. The audience claim identifies the + recipients that the JWT is intended for. The + audience value is a single case-sensitive + string. Having multiple values (array) for the + audience field is not supported. More info about + the OIDC JWT token audience here: + + https://tools.ietf.org/html/rfc7519#section-4.1.3 + Note: if not specified, the Push endpoint URL + will be used. + """ + + service_account_email: str = proto.Field( + proto.STRING, + number=1, + ) + audience: str = proto.Field( + proto.STRING, + number=2, + ) + + class PubsubWrapper(proto.Message): + r"""The payload to the push endpoint is in the form of the JSON + representation of a PubsubMessage + (https://cloud.google.com/pubsub/docs/reference/rpc/google.pubsub.v1#pubsubmessage). + + """ + + class NoWrapper(proto.Message): + r"""Sets the ``data`` field as the HTTP body for delivery. + + Attributes: + write_metadata (bool): + Optional. When true, writes the Pub/Sub message metadata to + ``x-goog-pubsub-:`` headers of the HTTP request. + Writes the Pub/Sub message attributes to ``:`` + headers of the HTTP request. + """ + + write_metadata: bool = proto.Field( + proto.BOOL, + number=1, + ) + + push_endpoint: str = proto.Field( + proto.STRING, + number=1, + ) + attributes: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + oidc_token: OidcToken = proto.Field( + proto.MESSAGE, + number=3, + oneof="authentication_method", + message=OidcToken, + ) + pubsub_wrapper: PubsubWrapper = proto.Field( + proto.MESSAGE, + number=4, + oneof="wrapper", + message=PubsubWrapper, + ) + no_wrapper: NoWrapper = proto.Field( + proto.MESSAGE, + number=5, + oneof="wrapper", + message=NoWrapper, + ) + + +class BigQueryConfig(proto.Message): + r"""Configuration for a BigQuery subscription. + + Attributes: + table (str): + Optional. The name of the table to which to + write data, of the form + {projectId}.{datasetId}.{tableId} + use_topic_schema (bool): + Optional. When true, use the topic's schema as the columns + to write to in BigQuery, if it exists. ``use_topic_schema`` + and ``use_table_schema`` cannot be enabled at the same time. + write_metadata (bool): + Optional. When true, write the subscription name, + message_id, publish_time, attributes, and ordering_key to + additional columns in the table. The subscription name, + message_id, and publish_time fields are put in their own + columns while all other message properties (other than data) + are written to a JSON object in the attributes column. + drop_unknown_fields (bool): + Optional. When true and use_topic_schema is true, any fields + that are a part of the topic schema that are not part of the + BigQuery table schema are dropped when writing to BigQuery. + Otherwise, the schemas must be kept in sync and any messages + with extra fields are not written and remain in the + subscription's backlog. + state (google.pubsub_v1.types.BigQueryConfig.State): + Output only. An output-only field that + indicates whether or not the subscription can + receive messages. + use_table_schema (bool): + Optional. When true, use the BigQuery table's schema as the + columns to write to in BigQuery. ``use_table_schema`` and + ``use_topic_schema`` cannot be enabled at the same time. + service_account_email (str): + Optional. The service account to use to write to BigQuery. + The subscription creator or updater that specifies this + field must have ``iam.serviceAccounts.actAs`` permission on + the service account. If not specified, the Pub/Sub `service + agent `__, + service-{project_number}@gcp-sa-pubsub.iam.gserviceaccount.com, + is used. + """ + + class State(proto.Enum): + r"""Possible states for a BigQuery subscription. + + Values: + STATE_UNSPECIFIED (0): + Default value. This value is unused. + ACTIVE (1): + The subscription can actively send messages + to BigQuery + PERMISSION_DENIED (2): + Cannot write to the BigQuery table because of permission + denied errors. This can happen if + + - Pub/Sub SA has not been granted the `appropriate BigQuery + IAM + permissions `__ + - bigquery.googleapis.com API is not enabled for the project + (`instructions `__) + NOT_FOUND (3): + Cannot write to the BigQuery table because it + does not exist. + SCHEMA_MISMATCH (4): + Cannot write to the BigQuery table due to a + schema mismatch. + IN_TRANSIT_LOCATION_RESTRICTION (5): + Cannot write to the destination because enforce_in_transit + is set to true and the destination locations are not in the + allowed regions. + VERTEX_AI_LOCATION_RESTRICTION (6): + Cannot write to the BigQuery table because the table is not + in the same location as where Vertex AI models used in + ``message_transform``\ s are deployed. + """ + + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + PERMISSION_DENIED = 2 + NOT_FOUND = 3 + SCHEMA_MISMATCH = 4 + IN_TRANSIT_LOCATION_RESTRICTION = 5 + VERTEX_AI_LOCATION_RESTRICTION = 6 + + table: str = proto.Field( + proto.STRING, + number=1, + ) + use_topic_schema: bool = proto.Field( + proto.BOOL, + number=2, + ) + write_metadata: bool = proto.Field( + proto.BOOL, + number=3, + ) + drop_unknown_fields: bool = proto.Field( + proto.BOOL, + number=4, + ) + state: State = proto.Field( + proto.ENUM, + number=5, + enum=State, + ) + use_table_schema: bool = proto.Field( + proto.BOOL, + number=6, + ) + service_account_email: str = proto.Field( + proto.STRING, + number=7, + ) + + +class BigtableConfig(proto.Message): + r"""Configuration for a Bigtable subscription. The Pub/Sub + message will be written to a Bigtable row as follows: + + - row key: subscription name and message ID delimited by #. + - columns: message bytes written to a single column family + "data" with an empty-string column qualifier. + - cell timestamp: the message publish timestamp. + + Attributes: + table (str): + Optional. The unique name of the table to write messages to. + + Values are of the form + ``projects//instances//tables/``. + app_profile_id (str): + Optional. The app profile to use for the + Bigtable writes. If not specified, the "default" + application profile will be used. The app + profile must use single-cluster routing. + service_account_email (str): + Optional. The service account to use to write to Bigtable. + The subscription creator or updater that specifies this + field must have ``iam.serviceAccounts.actAs`` permission on + the service account. If not specified, the Pub/Sub `service + agent `__, + service-{project_number}@gcp-sa-pubsub.iam.gserviceaccount.com, + is used. + write_metadata (bool): + Optional. When true, write the subscription name, + message_id, publish_time, attributes, and ordering_key to + additional columns in the table under the pubsub_metadata + column family. The subscription name, message_id, and + publish_time fields are put in their own columns while all + other message properties (other than data) are written to a + JSON object in the attributes column. + state (google.pubsub_v1.types.BigtableConfig.State): + Output only. An output-only field that + indicates whether or not the subscription can + receive messages. + """ + + class State(proto.Enum): + r"""Possible states for a Bigtable subscription. + Note: more states could be added in the future. Please code + accordingly. + + Values: + STATE_UNSPECIFIED (0): + Default value. This value is unused. + ACTIVE (1): + The subscription can actively send messages + to Bigtable. + NOT_FOUND (2): + Cannot write to Bigtable because the + instance, table, or app profile does not exist. + APP_PROFILE_MISCONFIGURED (3): + Cannot write to Bigtable because the app + profile is not configured for single-cluster + routing. + PERMISSION_DENIED (4): + Cannot write to Bigtable because of permission denied + errors. This can happen if: + + - The Pub/Sub service agent has not been granted the + `appropriate Bigtable IAM permission + bigtable.tables.mutateRows <{$universe.dns_names.final_documentation_domain}/bigtable/docs/access-control#permissions>`__ + - The bigtable.googleapis.com API is not enabled for the + project + (`instructions <{$universe.dns_names.final_documentation_domain}/service-usage/docs/enable-disable>`__) + SCHEMA_MISMATCH (5): + Cannot write to Bigtable because of a missing + column family ("data") or if there is no + structured row key for the subscription name + + message ID. + IN_TRANSIT_LOCATION_RESTRICTION (6): + Cannot write to the destination because enforce_in_transit + is set to true and the destination locations are not in the + allowed regions. + VERTEX_AI_LOCATION_RESTRICTION (7): + Cannot write to Bigtable because the table is not in the + same location as where Vertex AI models used in + ``message_transform``\ s are deployed. + """ + + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + NOT_FOUND = 2 + APP_PROFILE_MISCONFIGURED = 3 + PERMISSION_DENIED = 4 + SCHEMA_MISMATCH = 5 + IN_TRANSIT_LOCATION_RESTRICTION = 6 + VERTEX_AI_LOCATION_RESTRICTION = 7 + + table: str = proto.Field( + proto.STRING, + number=1, + ) + app_profile_id: str = proto.Field( + proto.STRING, + number=2, + ) + service_account_email: str = proto.Field( + proto.STRING, + number=3, + ) + write_metadata: bool = proto.Field( + proto.BOOL, + number=5, + ) + state: State = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + + +class CloudStorageConfig(proto.Message): + r"""Configuration for a Cloud Storage subscription. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + bucket (str): + Required. User-provided name for the Cloud Storage bucket. + The bucket must be created by the user. The bucket name must + be without any prefix like "gs://". See the [bucket naming + requirements] + (https://cloud.google.com/storage/docs/buckets#naming). + filename_prefix (str): + Optional. User-provided prefix for Cloud Storage filename. + See the `object naming + requirements `__. + filename_suffix (str): + Optional. User-provided suffix for Cloud Storage filename. + See the `object naming + requirements `__. + Must not end in "/". + filename_datetime_format (str): + Optional. User-provided format string specifying how to + represent datetimes in Cloud Storage filenames. See the + `datetime format + guidance `__. + text_config (google.pubsub_v1.types.CloudStorageConfig.TextConfig): + Optional. If set, message data will be + written to Cloud Storage in text format. + + This field is a member of `oneof`_ ``output_format``. + avro_config (google.pubsub_v1.types.CloudStorageConfig.AvroConfig): + Optional. If set, message data will be + written to Cloud Storage in Avro format. + + This field is a member of `oneof`_ ``output_format``. + max_duration (google.protobuf.duration_pb2.Duration): + Optional. The maximum duration that can + elapse before a new Cloud Storage file is + created. Min 1 minute, max 10 minutes, default 5 + minutes. May not exceed the subscription's + acknowledgment deadline. + max_bytes (int): + Optional. The maximum bytes that can be written to a Cloud + Storage file before a new file is created. Min 1 KB, max 10 + GiB. The max_bytes limit may be exceeded in cases where + messages are larger than the limit. + max_messages (int): + Optional. The maximum number of messages that + can be written to a Cloud Storage file before a + new file is created. Min 1000 messages. + state (google.pubsub_v1.types.CloudStorageConfig.State): + Output only. An output-only field that + indicates whether or not the subscription can + receive messages. + service_account_email (str): + Optional. The service account to use to write to Cloud + Storage. The subscription creator or updater that specifies + this field must have ``iam.serviceAccounts.actAs`` + permission on the service account. If not specified, the + Pub/Sub `service + agent `__, + service-{project_number}@gcp-sa-pubsub.iam.gserviceaccount.com, + is used. + """ + + class State(proto.Enum): + r"""Possible states for a Cloud Storage subscription. + + Values: + STATE_UNSPECIFIED (0): + Default value. This value is unused. + ACTIVE (1): + The subscription can actively send messages + to Cloud Storage. + PERMISSION_DENIED (2): + Cannot write to the Cloud Storage bucket + because of permission denied errors. + NOT_FOUND (3): + Cannot write to the Cloud Storage bucket + because it does not exist. + IN_TRANSIT_LOCATION_RESTRICTION (4): + Cannot write to the destination because enforce_in_transit + is set to true and the destination locations are not in the + allowed regions. + SCHEMA_MISMATCH (5): + Cannot write to the Cloud Storage bucket due + to an incompatibility between the topic schema + and subscription settings. + VERTEX_AI_LOCATION_RESTRICTION (6): + Cannot write to the Cloud Storage bucket because the bucket + is not in the same location as where Vertex AI models used + in ``message_transform``\ s are deployed. + """ + + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + PERMISSION_DENIED = 2 + NOT_FOUND = 3 + IN_TRANSIT_LOCATION_RESTRICTION = 4 + SCHEMA_MISMATCH = 5 + VERTEX_AI_LOCATION_RESTRICTION = 6 + + class TextConfig(proto.Message): + r"""Configuration for writing message data in text format. + Message payloads will be written to files as raw text, separated + by a newline. + + """ + + class AvroConfig(proto.Message): + r"""Configuration for writing message data in Avro format. + Message payloads and metadata will be written to files as an + Avro binary. + + Attributes: + write_metadata (bool): + Optional. When true, write the subscription name, + message_id, publish_time, attributes, and ordering_key as + additional fields in the output. The subscription name, + message_id, and publish_time fields are put in their own + fields while all other message properties other than data + (for example, an ordering_key, if present) are added as + entries in the attributes map. + use_topic_schema (bool): + Optional. When true, the output Cloud Storage + file will be serialized using the topic schema, + if it exists. + """ + + write_metadata: bool = proto.Field( + proto.BOOL, + number=1, + ) + use_topic_schema: bool = proto.Field( + proto.BOOL, + number=2, + ) + + bucket: str = proto.Field( + proto.STRING, + number=1, + ) + filename_prefix: str = proto.Field( + proto.STRING, + number=2, + ) + filename_suffix: str = proto.Field( + proto.STRING, + number=3, + ) + filename_datetime_format: str = proto.Field( + proto.STRING, + number=10, + ) + text_config: TextConfig = proto.Field( + proto.MESSAGE, + number=4, + oneof="output_format", + message=TextConfig, + ) + avro_config: AvroConfig = proto.Field( + proto.MESSAGE, + number=5, + oneof="output_format", + message=AvroConfig, + ) + max_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=6, + message=duration_pb2.Duration, + ) + max_bytes: int = proto.Field( + proto.INT64, + number=7, + ) + max_messages: int = proto.Field( + proto.INT64, + number=8, + ) + state: State = proto.Field( + proto.ENUM, + number=9, + enum=State, + ) + service_account_email: str = proto.Field( + proto.STRING, + number=11, + ) + + +class ReceivedMessage(proto.Message): + r"""A message and its corresponding acknowledgment ID. + + Attributes: + ack_id (str): + Optional. This ID can be used to acknowledge + the received message. + message (google.pubsub_v1.types.PubsubMessage): + Optional. The message. + delivery_attempt (int): + Optional. The approximate number of times that Pub/Sub has + attempted to deliver the associated message to a subscriber. + + More precisely, this is 1 + (number of NACKs) + (number of + ack_deadline exceeds) for this message. + + A NACK is any call to ModifyAckDeadline with a 0 deadline. + An ack_deadline exceeds event is whenever a message is not + acknowledged within ack_deadline. Note that ack_deadline is + initially Subscription.ackDeadlineSeconds, but may get + extended automatically by the client library. + + Upon the first delivery of a given message, + ``delivery_attempt`` will have a value of 1. The value is + calculated at best effort and is approximate. + + If a DeadLetterPolicy is not set on the subscription, this + will be 0. + """ + + ack_id: str = proto.Field( + proto.STRING, + number=1, + ) + message: "PubsubMessage" = proto.Field( + proto.MESSAGE, + number=2, + message="PubsubMessage", + ) + delivery_attempt: int = proto.Field( + proto.INT32, + number=3, + ) + + +class GetSubscriptionRequest(proto.Message): + r"""Request for the GetSubscription method. + + Attributes: + subscription (str): + Required. The name of the subscription to get. Format is + ``projects/{project}/subscriptions/{sub}``. + """ + + subscription: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateSubscriptionRequest(proto.Message): + r"""Request for the UpdateSubscription method. + + Attributes: + subscription (google.pubsub_v1.types.Subscription): + Required. The updated subscription object. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Indicates which fields in the + provided subscription to update. Must be + specified and non-empty. + """ + + subscription: "Subscription" = proto.Field( + proto.MESSAGE, + number=1, + message="Subscription", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class ListSubscriptionsRequest(proto.Message): + r"""Request for the ``ListSubscriptions`` method. + + Attributes: + project (str): + Required. The name of the project in which to list + subscriptions. Format is ``projects/{project-id}``. + page_size (int): + Optional. Maximum number of subscriptions to + return. + page_token (str): + Optional. The value returned by the last + ``ListSubscriptionsResponse``; indicates that this is a + continuation of a prior ``ListSubscriptions`` call, and that + the system should return the next page of data. + """ + + project: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListSubscriptionsResponse(proto.Message): + r"""Response for the ``ListSubscriptions`` method. + + Attributes: + subscriptions (MutableSequence[google.pubsub_v1.types.Subscription]): + Optional. The subscriptions that match the + request. + next_page_token (str): + Optional. If not empty, indicates that there may be more + subscriptions that match the request; this value should be + passed in a new ``ListSubscriptionsRequest`` to get more + subscriptions. + """ + + @property + def raw_page(self): + return self + + subscriptions: MutableSequence["Subscription"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Subscription", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteSubscriptionRequest(proto.Message): + r"""Request for the DeleteSubscription method. + + Attributes: + subscription (str): + Required. The subscription to delete. Format is + ``projects/{project}/subscriptions/{sub}``. + """ + + subscription: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ModifyPushConfigRequest(proto.Message): + r"""Request for the ModifyPushConfig method. + + Attributes: + subscription (str): + Required. The name of the subscription. Format is + ``projects/{project}/subscriptions/{sub}``. + push_config (google.pubsub_v1.types.PushConfig): + Required. The push configuration for future deliveries. + + An empty ``pushConfig`` indicates that the Pub/Sub system + should stop pushing messages from the given subscription and + allow messages to be pulled and acknowledged - effectively + pausing the subscription if ``Pull`` or ``StreamingPull`` is + not called. + """ + + subscription: str = proto.Field( + proto.STRING, + number=1, + ) + push_config: "PushConfig" = proto.Field( + proto.MESSAGE, + number=2, + message="PushConfig", + ) + + +class PullRequest(proto.Message): + r"""Request for the ``Pull`` method. + + Attributes: + subscription (str): + Required. The subscription from which messages should be + pulled. Format is + ``projects/{project}/subscriptions/{sub}``. + return_immediately (bool): + Optional. If this field set to true, the system will respond + immediately even if it there are no messages available to + return in the ``Pull`` response. Otherwise, the system may + wait (for a bounded amount of time) until at least one + message is available, rather than returning no messages. + Warning: setting this field to ``true`` is discouraged + because it adversely impacts the performance of ``Pull`` + operations. We recommend that users do not set this field. + max_messages (int): + Required. The maximum number of messages to + return for this request. Must be a positive + integer. The Pub/Sub system may return fewer + than the number specified. + """ + + subscription: str = proto.Field( + proto.STRING, + number=1, + ) + return_immediately: bool = proto.Field( + proto.BOOL, + number=2, + ) + max_messages: int = proto.Field( + proto.INT32, + number=3, + ) + + +class PullResponse(proto.Message): + r"""Response for the ``Pull`` method. + + Attributes: + received_messages (MutableSequence[google.pubsub_v1.types.ReceivedMessage]): + Optional. Received Pub/Sub messages. The list will be empty + if there are no more messages available in the backlog, or + if no messages could be returned before the request timeout. + For JSON, the response can be entirely empty. The Pub/Sub + system may return fewer than the ``maxMessages`` requested + even if there are more messages available in the backlog. + """ + + received_messages: MutableSequence["ReceivedMessage"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="ReceivedMessage", + ) + + +class ModifyAckDeadlineRequest(proto.Message): + r"""Request for the ModifyAckDeadline method. + + Attributes: + subscription (str): + Required. The name of the subscription. Format is + ``projects/{project}/subscriptions/{sub}``. + ack_ids (MutableSequence[str]): + Required. List of acknowledgment IDs. + ack_deadline_seconds (int): + Required. The new ack deadline with respect to the time this + request was sent to the Pub/Sub system. For example, if the + value is 10, the new ack deadline will expire 10 seconds + after the ``ModifyAckDeadline`` call was made. Specifying + zero might immediately make the message available for + delivery to another subscriber client. This typically + results in an increase in the rate of message redeliveries + (that is, duplicates). The minimum deadline you can specify + is 0 seconds. The maximum deadline you can specify in a + single request is 600 seconds (10 minutes). + """ + + subscription: str = proto.Field( + proto.STRING, + number=1, + ) + ack_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + ack_deadline_seconds: int = proto.Field( + proto.INT32, + number=3, + ) + + +class AcknowledgeRequest(proto.Message): + r"""Request for the Acknowledge method. + + Attributes: + subscription (str): + Required. The subscription whose message is being + acknowledged. Format is + ``projects/{project}/subscriptions/{sub}``. + ack_ids (MutableSequence[str]): + Required. The acknowledgment ID for the messages being + acknowledged that was returned by the Pub/Sub system in the + ``Pull`` response. Must not be empty. + """ + + subscription: str = proto.Field( + proto.STRING, + number=1, + ) + ack_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class StreamingPullRequest(proto.Message): + r"""Request for the ``StreamingPull`` streaming RPC method. This request + is used to establish the initial stream as well as to stream + acknowledgments and ack deadline modifications from the client to + the server. + + Attributes: + subscription (str): + Required. The subscription for which to initialize the new + stream. This must be provided in the first request on the + stream, and must not be set in subsequent requests from + client to server. Format is + ``projects/{project}/subscriptions/{sub}``. + ack_ids (MutableSequence[str]): + Optional. List of acknowledgment IDs for acknowledging + previously received messages (received on this stream or a + different stream). If an ack ID has expired, the + corresponding message may be redelivered later. + Acknowledging a message more than once will not result in an + error. If the acknowledgment ID is malformed, the stream + will be aborted with status ``INVALID_ARGUMENT``. + modify_deadline_seconds (MutableSequence[int]): + Optional. The list of new ack deadlines for the IDs listed + in ``modify_deadline_ack_ids``. The size of this list must + be the same as the size of ``modify_deadline_ack_ids``. If + it differs the stream will be aborted with + ``INVALID_ARGUMENT``. Each element in this list is applied + to the element in the same position in + ``modify_deadline_ack_ids``. The new ack deadline is with + respect to the time this request was sent to the Pub/Sub + system. Must be >= 0. For example, if the value is 10, the + new ack deadline will expire 10 seconds after this request + is received. If the value is 0, the message is immediately + made available for another streaming or non-streaming pull + request. If the value is < 0 (an error), the stream will be + aborted with status ``INVALID_ARGUMENT``. + modify_deadline_ack_ids (MutableSequence[str]): + Optional. List of acknowledgment IDs whose deadline will be + modified based on the corresponding element in + ``modify_deadline_seconds``. This field can be used to + indicate that more time is needed to process a message by + the subscriber, or to make the message available for + redelivery if the processing was interrupted. + stream_ack_deadline_seconds (int): + Required. The ack deadline to use for the + stream. This must be provided in the first + request on the stream, but it can also be + updated on subsequent requests from client to + server. The minimum deadline you can specify is + 10 seconds. The maximum deadline you can specify + is 600 seconds (10 minutes). + client_id (str): + Optional. A unique identifier that is used to distinguish + client instances from each other. Only needs to be provided + on the initial request. When a stream disconnects and + reconnects for the same stream, the client_id should be set + to the same value so that state associated with the old + stream can be transferred to the new stream. The same + client_id should not be used for different client instances. + max_outstanding_messages (int): + Optional. Flow control settings for the maximum number of + outstanding messages. When there are + ``max_outstanding_messages`` currently sent to the streaming + pull client that have not yet been acked or nacked, the + server stops sending more messages. The sending of messages + resumes once the number of outstanding messages is less than + this value. If the value is <= 0, there is no limit to the + number of outstanding messages. This property can only be + set on the initial StreamingPullRequest. If it is set on a + subsequent request, the stream will be aborted with status + ``INVALID_ARGUMENT``. + max_outstanding_bytes (int): + Optional. Flow control settings for the maximum number of + outstanding bytes. When there are ``max_outstanding_bytes`` + or more worth of messages currently sent to the streaming + pull client that have not yet been acked or nacked, the + server will stop sending more messages. The sending of + messages resumes once the number of outstanding bytes is + less than this value. If the value is <= 0, there is no + limit to the number of outstanding bytes. This property can + only be set on the initial StreamingPullRequest. If it is + set on a subsequent request, the stream will be aborted with + status ``INVALID_ARGUMENT``. + protocol_version (int): + Optional. The protocol version used by the client. This + property can only be set on the initial + StreamingPullRequest. If it is set on a subsequent request, + the stream will be aborted with status ``INVALID_ARGUMENT``. + """ + + subscription: str = proto.Field( + proto.STRING, + number=1, + ) + ack_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + modify_deadline_seconds: MutableSequence[int] = proto.RepeatedField( + proto.INT32, + number=3, + ) + modify_deadline_ack_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + stream_ack_deadline_seconds: int = proto.Field( + proto.INT32, + number=5, + ) + client_id: str = proto.Field( + proto.STRING, + number=6, + ) + max_outstanding_messages: int = proto.Field( + proto.INT64, + number=7, + ) + max_outstanding_bytes: int = proto.Field( + proto.INT64, + number=8, + ) + protocol_version: int = proto.Field( + proto.INT64, + number=10, + ) + + +class StreamingPullResponse(proto.Message): + r"""Response for the ``StreamingPull`` method. This response is used to + stream messages from the server to the client. + + Attributes: + received_messages (MutableSequence[google.pubsub_v1.types.ReceivedMessage]): + Optional. Received Pub/Sub messages. + acknowledge_confirmation (google.pubsub_v1.types.StreamingPullResponse.AcknowledgeConfirmation): + Optional. This field will only be set if + ``enable_exactly_once_delivery`` is set to ``true`` and is + not guaranteed to be populated. + modify_ack_deadline_confirmation (google.pubsub_v1.types.StreamingPullResponse.ModifyAckDeadlineConfirmation): + Optional. This field will only be set if + ``enable_exactly_once_delivery`` is set to ``true`` and is + not guaranteed to be populated. + subscription_properties (google.pubsub_v1.types.StreamingPullResponse.SubscriptionProperties): + Optional. Properties associated with this + subscription. + """ + + class AcknowledgeConfirmation(proto.Message): + r"""Acknowledgment IDs sent in one or more previous requests to + acknowledge a previously received message. + + Attributes: + ack_ids (MutableSequence[str]): + Optional. Successfully processed + acknowledgment IDs. + invalid_ack_ids (MutableSequence[str]): + Optional. List of acknowledgment IDs that + were malformed or whose acknowledgment deadline + has expired. + unordered_ack_ids (MutableSequence[str]): + Optional. List of acknowledgment IDs that + were out of order. + temporary_failed_ack_ids (MutableSequence[str]): + Optional. List of acknowledgment IDs that + failed processing with temporary issues. + """ + + ack_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + invalid_ack_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + unordered_ack_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + temporary_failed_ack_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + + class ModifyAckDeadlineConfirmation(proto.Message): + r"""Acknowledgment IDs sent in one or more previous requests to + modify the deadline for a specific message. + + Attributes: + ack_ids (MutableSequence[str]): + Optional. Successfully processed + acknowledgment IDs. + invalid_ack_ids (MutableSequence[str]): + Optional. List of acknowledgment IDs that + were malformed or whose acknowledgment deadline + has expired. + temporary_failed_ack_ids (MutableSequence[str]): + Optional. List of acknowledgment IDs that + failed processing with temporary issues. + """ + + ack_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + invalid_ack_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + temporary_failed_ack_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + class SubscriptionProperties(proto.Message): + r"""Subscription properties sent as part of the response. + + Attributes: + exactly_once_delivery_enabled (bool): + Optional. True iff exactly once delivery is + enabled for this subscription. + message_ordering_enabled (bool): + Optional. True iff message ordering is + enabled for this subscription. + """ + + exactly_once_delivery_enabled: bool = proto.Field( + proto.BOOL, + number=1, + ) + message_ordering_enabled: bool = proto.Field( + proto.BOOL, + number=2, + ) + + received_messages: MutableSequence["ReceivedMessage"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="ReceivedMessage", + ) + acknowledge_confirmation: AcknowledgeConfirmation = proto.Field( + proto.MESSAGE, + number=5, + message=AcknowledgeConfirmation, + ) + modify_ack_deadline_confirmation: ModifyAckDeadlineConfirmation = proto.Field( + proto.MESSAGE, + number=3, + message=ModifyAckDeadlineConfirmation, + ) + subscription_properties: SubscriptionProperties = proto.Field( + proto.MESSAGE, + number=4, + message=SubscriptionProperties, + ) + + +class CreateSnapshotRequest(proto.Message): + r"""Request for the ``CreateSnapshot`` method. + + Attributes: + name (str): + Required. User-provided name for this snapshot. If the name + is not provided in the request, the server will assign a + random name for this snapshot on the same project as the + subscription. Note that for REST API requests, you must + specify a name. See the `resource name + rules `__. + Format is ``projects/{project}/snapshots/{snap}``. + subscription (str): + Required. The subscription whose backlog the snapshot + retains. Specifically, the created snapshot is guaranteed to + retain: (a) The existing backlog on the subscription. More + precisely, this is defined as the messages in the + subscription's backlog that are unacknowledged upon the + successful completion of the ``CreateSnapshot`` request; as + well as: (b) Any messages published to the subscription's + topic following the successful completion of the + CreateSnapshot request. Format is + ``projects/{project}/subscriptions/{sub}``. + labels (MutableMapping[str, str]): + Optional. See `Creating and managing + labels `__. + tags (MutableMapping[str, str]): + Optional. Input only. Immutable. Tag + keys/values directly bound to this resource. For + example: + + "123/environment": "production", + "123/costCenter": "marketing" + See + https://docs.cloud.google.com/pubsub/docs/tags + for more information on using tags with Pub/Sub + resources. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + subscription: str = proto.Field( + proto.STRING, + number=2, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=3, + ) + tags: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + + +class UpdateSnapshotRequest(proto.Message): + r"""Request for the UpdateSnapshot method. + + Attributes: + snapshot (google.pubsub_v1.types.Snapshot): + Required. The updated snapshot object. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Indicates which fields in the + provided snapshot to update. Must be specified + and non-empty. + """ + + snapshot: "Snapshot" = proto.Field( + proto.MESSAGE, + number=1, + message="Snapshot", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class Snapshot(proto.Message): + r"""A snapshot resource. Snapshots are used in + `Seek `__ + operations, which allow you to manage message acknowledgments in + bulk. That is, you can set the acknowledgment state of messages in + an existing subscription to the state captured by a snapshot. + + Attributes: + name (str): + Optional. The name of the snapshot. + topic (str): + Optional. The name of the topic from which + this snapshot is retaining messages. + expire_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. The snapshot is guaranteed to exist up until this + time. A newly-created snapshot expires no later than 7 days + from the time of its creation. Its exact lifetime is + determined at creation by the existing backlog in the source + subscription. Specifically, the lifetime of the snapshot is + ``7 days - (age of oldest unacked message in the subscription)``. + For example, consider a subscription whose oldest unacked + message is 3 days old. If a snapshot is created from this + subscription, the snapshot -- which will always capture this + 3-day-old backlog as long as the snapshot exists -- will + expire in 4 days. The service will refuse to create a + snapshot that would expire in less than 1 hour after + creation. + labels (MutableMapping[str, str]): + Optional. See [Creating and managing labels] + (https://cloud.google.com/pubsub/docs/labels). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + topic: str = proto.Field( + proto.STRING, + number=2, + ) + expire_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + + +class GetSnapshotRequest(proto.Message): + r"""Request for the GetSnapshot method. + + Attributes: + snapshot (str): + Required. The name of the snapshot to get. Format is + ``projects/{project}/snapshots/{snap}``. + """ + + snapshot: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListSnapshotsRequest(proto.Message): + r"""Request for the ``ListSnapshots`` method. + + Attributes: + project (str): + Required. The name of the project in which to list + snapshots. Format is ``projects/{project-id}``. + page_size (int): + Optional. Maximum number of snapshots to + return. + page_token (str): + Optional. The value returned by the last + ``ListSnapshotsResponse``; indicates that this is a + continuation of a prior ``ListSnapshots`` call, and that the + system should return the next page of data. + """ + + project: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListSnapshotsResponse(proto.Message): + r"""Response for the ``ListSnapshots`` method. + + Attributes: + snapshots (MutableSequence[google.pubsub_v1.types.Snapshot]): + Optional. The resulting snapshots. + next_page_token (str): + Optional. If not empty, indicates that there may be more + snapshot that match the request; this value should be passed + in a new ``ListSnapshotsRequest``. + """ + + @property + def raw_page(self): + return self + + snapshots: MutableSequence["Snapshot"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Snapshot", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteSnapshotRequest(proto.Message): + r"""Request for the ``DeleteSnapshot`` method. + + Attributes: + snapshot (str): + Required. The name of the snapshot to delete. Format is + ``projects/{project}/snapshots/{snap}``. + """ + + snapshot: str = proto.Field( + proto.STRING, + number=1, + ) + + +class SeekRequest(proto.Message): + r"""Request for the ``Seek`` method. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + subscription (str): + Required. The subscription to affect. + time (google.protobuf.timestamp_pb2.Timestamp): + Optional. The time to seek to. Messages retained in the + subscription that were published before this time are marked + as acknowledged, and messages retained in the subscription + that were published after this time are marked as + unacknowledged. Note that this operation affects only those + messages retained in the subscription (configured by the + combination of ``message_retention_duration`` and + ``retain_acked_messages``). For example, if ``time`` + corresponds to a point before the message retention window + (or to a point before the system's notion of the + subscription creation time), only retained messages will be + marked as unacknowledged, and already-expunged messages will + not be restored. + + This field is a member of `oneof`_ ``target``. + snapshot (str): + Optional. The snapshot to seek to. The snapshot's topic must + be the same as that of the provided subscription. Format is + ``projects/{project}/snapshots/{snap}``. + + This field is a member of `oneof`_ ``target``. + """ + + subscription: str = proto.Field( + proto.STRING, + number=1, + ) + time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + oneof="target", + message=timestamp_pb2.Timestamp, + ) + snapshot: str = proto.Field( + proto.STRING, + number=3, + oneof="target", + ) + + +class SeekResponse(proto.Message): + r"""Response for the ``Seek`` method (this response is empty).""" + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/types/schema.py b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/types/schema.py new file mode 100644 index 0000000000000000000000000000000000000000..978c28291570da89569ec66f694fa203ea5a1c64 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/pubsub_v1/types/schema.py @@ -0,0 +1,512 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed 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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.pubsub.v1", + manifest={ + "SchemaView", + "Encoding", + "Schema", + "CreateSchemaRequest", + "GetSchemaRequest", + "ListSchemasRequest", + "ListSchemasResponse", + "ListSchemaRevisionsRequest", + "ListSchemaRevisionsResponse", + "CommitSchemaRequest", + "RollbackSchemaRequest", + "DeleteSchemaRevisionRequest", + "DeleteSchemaRequest", + "ValidateSchemaRequest", + "ValidateSchemaResponse", + "ValidateMessageRequest", + "ValidateMessageResponse", + }, +) + + +class SchemaView(proto.Enum): + r"""View of Schema object fields to be returned by GetSchema and + ListSchemas. + + Values: + SCHEMA_VIEW_UNSPECIFIED (0): + The default / unset value. + The API will default to the BASIC view. + BASIC (1): + Include the name and type of the schema, but + not the definition. + FULL (2): + Include all Schema object fields. + """ + + SCHEMA_VIEW_UNSPECIFIED = 0 + BASIC = 1 + FULL = 2 + + +class Encoding(proto.Enum): + r"""Possible encoding types for messages. + + Values: + ENCODING_UNSPECIFIED (0): + Unspecified + JSON (1): + JSON encoding + BINARY (2): + Binary encoding, as defined by the schema + type. For some schema types, binary encoding may + not be available. + """ + + ENCODING_UNSPECIFIED = 0 + JSON = 1 + BINARY = 2 + + +class Schema(proto.Message): + r"""A schema resource. + + Attributes: + name (str): + Required. Name of the schema. Format is + ``projects/{project}/schemas/{schema}``. + type_ (google.pubsub_v1.types.Schema.Type): + The type of the schema definition. + definition (str): + The definition of the schema. This should contain a string + representing the full definition of the schema that is a + valid schema definition of the type specified in ``type``. + revision_id (str): + Output only. Immutable. The revision ID of + the schema. + revision_create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp that the revision + was created. + """ + + class Type(proto.Enum): + r"""Possible schema definition types. + + Values: + TYPE_UNSPECIFIED (0): + Default value. This value is unused. + PROTOCOL_BUFFER (1): + A Protocol Buffer schema definition. + AVRO (2): + An Avro schema definition. + """ + + TYPE_UNSPECIFIED = 0 + PROTOCOL_BUFFER = 1 + AVRO = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + type_: Type = proto.Field( + proto.ENUM, + number=2, + enum=Type, + ) + definition: str = proto.Field( + proto.STRING, + number=3, + ) + revision_id: str = proto.Field( + proto.STRING, + number=4, + ) + revision_create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + + +class CreateSchemaRequest(proto.Message): + r"""Request for the CreateSchema method. + + Attributes: + parent (str): + Required. The name of the project in which to create the + schema. Format is ``projects/{project-id}``. + schema (google.pubsub_v1.types.Schema): + Required. The schema object to create. + + This schema's ``name`` parameter is ignored. The schema + object returned by CreateSchema will have a ``name`` made + using the given ``parent`` and ``schema_id``. + schema_id (str): + The ID to use for the schema, which will become the final + component of the schema's resource name. + + See + https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names + for resource name constraints. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + schema: "Schema" = proto.Field( + proto.MESSAGE, + number=2, + message="Schema", + ) + schema_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class GetSchemaRequest(proto.Message): + r"""Request for the GetSchema method. + + Attributes: + name (str): + Required. The name of the schema to get. Format is + ``projects/{project}/schemas/{schema}``. + view (google.pubsub_v1.types.SchemaView): + The set of fields to return in the response. If not set, + returns a Schema with all fields filled out. Set to + ``BASIC`` to omit the ``definition``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + view: "SchemaView" = proto.Field( + proto.ENUM, + number=2, + enum="SchemaView", + ) + + +class ListSchemasRequest(proto.Message): + r"""Request for the ``ListSchemas`` method. + + Attributes: + parent (str): + Required. The name of the project in which to list schemas. + Format is ``projects/{project-id}``. + view (google.pubsub_v1.types.SchemaView): + The set of Schema fields to return in the response. If not + set, returns Schemas with ``name`` and ``type``, but not + ``definition``. Set to ``FULL`` to retrieve all fields. + page_size (int): + Maximum number of schemas to return. + page_token (str): + The value returned by the last ``ListSchemasResponse``; + indicates that this is a continuation of a prior + ``ListSchemas`` call, and that the system should return the + next page of data. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + view: "SchemaView" = proto.Field( + proto.ENUM, + number=2, + enum="SchemaView", + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + page_token: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListSchemasResponse(proto.Message): + r"""Response for the ``ListSchemas`` method. + + Attributes: + schemas (MutableSequence[google.pubsub_v1.types.Schema]): + The resulting schemas. + next_page_token (str): + If not empty, indicates that there may be more schemas that + match the request; this value should be passed in a new + ``ListSchemasRequest``. + """ + + @property + def raw_page(self): + return self + + schemas: MutableSequence["Schema"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Schema", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListSchemaRevisionsRequest(proto.Message): + r"""Request for the ``ListSchemaRevisions`` method. + + Attributes: + name (str): + Required. The name of the schema to list + revisions for. + view (google.pubsub_v1.types.SchemaView): + The set of Schema fields to return in the response. If not + set, returns Schemas with ``name`` and ``type``, but not + ``definition``. Set to ``FULL`` to retrieve all fields. + page_size (int): + The maximum number of revisions to return per + page. + page_token (str): + The page token, received from a previous + ListSchemaRevisions call. Provide this to + retrieve the subsequent page. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + view: "SchemaView" = proto.Field( + proto.ENUM, + number=2, + enum="SchemaView", + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + page_token: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListSchemaRevisionsResponse(proto.Message): + r"""Response for the ``ListSchemaRevisions`` method. + + Attributes: + schemas (MutableSequence[google.pubsub_v1.types.Schema]): + The revisions of the schema. + next_page_token (str): + A token that can be sent as ``page_token`` to retrieve the + next page. If this field is empty, there are no subsequent + pages. + """ + + @property + def raw_page(self): + return self + + schemas: MutableSequence["Schema"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Schema", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class CommitSchemaRequest(proto.Message): + r"""Request for CommitSchema method. + + Attributes: + name (str): + Required. The name of the schema we are revising. Format is + ``projects/{project}/schemas/{schema}``. + schema (google.pubsub_v1.types.Schema): + Required. The schema revision to commit. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + schema: "Schema" = proto.Field( + proto.MESSAGE, + number=2, + message="Schema", + ) + + +class RollbackSchemaRequest(proto.Message): + r"""Request for the ``RollbackSchema`` method. + + Attributes: + name (str): + Required. The schema being rolled back with + revision id. + revision_id (str): + Required. The revision ID to roll back to. + It must be a revision of the same schema. + + Example: c7cfa2a8 + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + revision_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteSchemaRevisionRequest(proto.Message): + r"""Request for the ``DeleteSchemaRevision`` method. + + Attributes: + name (str): + Required. The name of the schema revision to be deleted, + with a revision ID explicitly included. + + Example: ``projects/123/schemas/my-schema@c7cfa2a8`` + revision_id (str): + Optional. This field is deprecated and should not be used + for specifying the revision ID. The revision ID should be + specified via the ``name`` parameter. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + revision_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteSchemaRequest(proto.Message): + r"""Request for the ``DeleteSchema`` method. + + Attributes: + name (str): + Required. Name of the schema to delete. Format is + ``projects/{project}/schemas/{schema}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ValidateSchemaRequest(proto.Message): + r"""Request for the ``ValidateSchema`` method. + + Attributes: + parent (str): + Required. The name of the project in which to validate + schemas. Format is ``projects/{project-id}``. + schema (google.pubsub_v1.types.Schema): + Required. The schema object to validate. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + schema: "Schema" = proto.Field( + proto.MESSAGE, + number=2, + message="Schema", + ) + + +class ValidateSchemaResponse(proto.Message): + r"""Response for the ``ValidateSchema`` method. Empty for now.""" + + +class ValidateMessageRequest(proto.Message): + r"""Request for the ``ValidateMessage`` method. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent (str): + Required. The name of the project in which to validate + schemas. Format is ``projects/{project-id}``. + name (str): + Name of the schema against which to validate. + + Format is ``projects/{project}/schemas/{schema}``. + + This field is a member of `oneof`_ ``schema_spec``. + schema (google.pubsub_v1.types.Schema): + Ad-hoc schema against which to validate + + This field is a member of `oneof`_ ``schema_spec``. + message (bytes): + Message to validate against the provided ``schema_spec``. + encoding (google.pubsub_v1.types.Encoding): + The encoding expected for messages + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + name: str = proto.Field( + proto.STRING, + number=2, + oneof="schema_spec", + ) + schema: "Schema" = proto.Field( + proto.MESSAGE, + number=3, + oneof="schema_spec", + message="Schema", + ) + message: bytes = proto.Field( + proto.BYTES, + number=4, + ) + encoding: "Encoding" = proto.Field( + proto.ENUM, + number=5, + enum="Encoding", + ) + + +class ValidateMessageResponse(proto.Message): + r"""Response for the ``ValidateMessage`` method. Empty for now.""" + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/resumable_media/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/resumable_media/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..eaade3e8792fe82fa7e15c02225270d6a626af3f --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/resumable_media/__init__.py @@ -0,0 +1,60 @@ +# Copyright 2017 Google Inc. +# +# Licensed 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. + +"""Utilities for Google Media Downloads and Resumable Uploads. + +This package has some general purposes modules, e.g. +:mod:`~google.resumable_media.common`, but the majority of the +public interface will be contained in subpackages. + +=========== +Subpackages +=========== + +Each subpackage is tailored to a specific transport library: + +* the :mod:`~google.resumable_media.requests` subpackage uses the ``requests`` + transport library. + +.. _requests: http://docs.python-requests.org/ + +========== +Installing +========== + +To install with `pip`_: + +.. code-block:: console + + $ pip install --upgrade google-resumable-media + +.. _pip: https://pip.pypa.io/ +""" + +from google.resumable_media.common import DataCorruption +from google.resumable_media.common import InvalidResponse +from google.resumable_media.common import PERMANENT_REDIRECT +from google.resumable_media.common import RetryStrategy +from google.resumable_media.common import TOO_MANY_REQUESTS +from google.resumable_media.common import UPLOAD_CHUNK_SIZE + + +__all__ = [ + "DataCorruption", + "InvalidResponse", + "PERMANENT_REDIRECT", + "RetryStrategy", + "TOO_MANY_REQUESTS", + "UPLOAD_CHUNK_SIZE", +] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/resumable_media/__pycache__/__init__.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/resumable_media/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..317f628ee6f37a5bbbf30f6dd8c10099dd49f849 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/resumable_media/__pycache__/__init__.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/resumable_media/__pycache__/common.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/resumable_media/__pycache__/common.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ed90f7bf046b8116ff782e4b0ab2d95f73b350eb Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/resumable_media/__pycache__/common.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/resumable_media/_download.py b/loan-advisor-agent/.venv/Lib/site-packages/google/resumable_media/_download.py new file mode 100644 index 0000000000000000000000000000000000000000..5ca41ba5422e5be616e64c0b9a5f56c8dfe80997 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/resumable_media/_download.py @@ -0,0 +1,558 @@ +# Copyright 2017 Google Inc. +# +# Licensed 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. + +"""Virtual bases classes for downloading media from Google APIs.""" + +import http.client +import re + +from google.resumable_media import _helpers +from google.resumable_media import common + + +_CONTENT_RANGE_RE = re.compile( + r"bytes (?P\d+)-(?P\d+)/(?P\d+)", + flags=re.IGNORECASE, +) +_ACCEPTABLE_STATUS_CODES = (http.client.OK, http.client.PARTIAL_CONTENT) +_GET = "GET" +_ZERO_CONTENT_RANGE_HEADER = "bytes */0" + + +class DownloadBase(object): + """Base class for download helpers. + + Defines core shared behavior across different download types. + + Args: + media_url (str): The URL containing the media to be downloaded. + stream (IO[bytes]): A write-able stream (i.e. file-like object) that + the downloaded resource can be written to. + start (int): The first byte in a range to be downloaded. + end (int): The last byte in a range to be downloaded. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with the request, e.g. headers for encrypted data. + + Attributes: + media_url (str): The URL containing the media to be downloaded. + start (Optional[int]): The first byte in a range to be downloaded. + end (Optional[int]): The last byte in a range to be downloaded. + """ + + def __init__(self, media_url, stream=None, start=None, end=None, headers=None): + self.media_url = media_url + self._stream = stream + self.start = start + self.end = end + if headers is None: + headers = {} + self._headers = headers + self._finished = False + self._retry_strategy = common.RetryStrategy() + + @property + def finished(self): + """bool: Flag indicating if the download has completed.""" + return self._finished + + @staticmethod + def _get_status_code(response): + """Access the status code from an HTTP response. + + Args: + response (object): The HTTP response object. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + @staticmethod + def _get_headers(response): + """Access the headers from an HTTP response. + + Args: + response (object): The HTTP response object. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + @staticmethod + def _get_body(response): + """Access the response body from an HTTP response. + + Args: + response (object): The HTTP response object. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + +class Download(DownloadBase): + """Helper to manage downloading a resource from a Google API. + + "Slices" of the resource can be retrieved by specifying a range + with ``start`` and / or ``end``. However, in typical usage, neither + ``start`` nor ``end`` is expected to be provided. + + Args: + media_url (str): The URL containing the media to be downloaded. + stream (IO[bytes]): A write-able stream (i.e. file-like object) that + the downloaded resource can be written to. + start (int): The first byte in a range to be downloaded. If not + provided, but ``end`` is provided, will download from the + beginning to ``end`` of the media. + end (int): The last byte in a range to be downloaded. If not + provided, but ``start`` is provided, will download from the + ``start`` to the end of the media. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with the request, e.g. headers for encrypted data. + checksum Optional([str]): The type of checksum to compute to verify + the integrity of the object. The response headers must contain + a checksum of the requested type. If the headers lack an + appropriate checksum (for instance in the case of transcoded or + ranged downloads where the remote service does not know the + correct checksum) an INFO-level log will be emitted. Supported + values are "md5", "crc32c" and None. + """ + + def __init__( + self, media_url, stream=None, start=None, end=None, headers=None, checksum="md5" + ): + super(Download, self).__init__( + media_url, stream=stream, start=start, end=end, headers=headers + ) + self.checksum = checksum + self._bytes_downloaded = 0 + self._expected_checksum = None + self._checksum_object = None + self._object_generation = None + + def _prepare_request(self): + """Prepare the contents of an HTTP request. + + This is everything that must be done before a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + Returns: + Tuple[str, str, NoneType, Mapping[str, str]]: The quadruple + + * HTTP verb for the request (always GET) + * the URL for the request + * the body of the request (always :data:`None`) + * headers for the request + + Raises: + ValueError: If the current :class:`Download` has already + finished. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + if self.finished: + raise ValueError("A download can only be used once.") + + add_bytes_range(self.start, self.end, self._headers) + return _GET, self.media_url, None, self._headers + + def _process_response(self, response): + """Process the response from an HTTP request. + + This is everything that must be done after a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + Args: + response (object): The HTTP response object. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + # Tombstone the current Download so it cannot be used again. + self._finished = True + _helpers.require_status_code( + response, _ACCEPTABLE_STATUS_CODES, self._get_status_code + ) + + def consume(self, transport, timeout=None): + """Consume the resource to be downloaded. + + If a ``stream`` is attached to this download, then the downloaded + resource will be written to the stream. + + Args: + transport (object): An object which can make authenticated + requests. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + +class ChunkedDownload(DownloadBase): + """Download a resource in chunks from a Google API. + + Args: + media_url (str): The URL containing the media to be downloaded. + chunk_size (int): The number of bytes to be retrieved in each + request. + stream (IO[bytes]): A write-able stream (i.e. file-like object) that + will be used to concatenate chunks of the resource as they are + downloaded. + start (int): The first byte in a range to be downloaded. If not + provided, defaults to ``0``. + end (int): The last byte in a range to be downloaded. If not + provided, will download to the end of the media. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with each request, e.g. headers for data encryption + key headers. + + Attributes: + media_url (str): The URL containing the media to be downloaded. + start (Optional[int]): The first byte in a range to be downloaded. + end (Optional[int]): The last byte in a range to be downloaded. + chunk_size (int): The number of bytes to be retrieved in each request. + + Raises: + ValueError: If ``start`` is negative. + """ + + def __init__(self, media_url, chunk_size, stream, start=0, end=None, headers=None): + if start < 0: + raise ValueError( + "On a chunked download the starting value cannot be negative." + ) + super(ChunkedDownload, self).__init__( + media_url, stream=stream, start=start, end=end, headers=headers + ) + self.chunk_size = chunk_size + self._bytes_downloaded = 0 + self._total_bytes = None + self._invalid = False + + @property + def bytes_downloaded(self): + """int: Number of bytes that have been downloaded.""" + return self._bytes_downloaded + + @property + def total_bytes(self): + """Optional[int]: The total number of bytes to be downloaded.""" + return self._total_bytes + + @property + def invalid(self): + """bool: Indicates if the download is in an invalid state. + + This will occur if a call to :meth:`consume_next_chunk` fails. + """ + return self._invalid + + def _get_byte_range(self): + """Determines the byte range for the next request. + + Returns: + Tuple[int, int]: The pair of begin and end byte for the next + chunked request. + """ + curr_start = self.start + self.bytes_downloaded + curr_end = curr_start + self.chunk_size - 1 + # Make sure ``curr_end`` does not exceed ``end``. + if self.end is not None: + curr_end = min(curr_end, self.end) + # Make sure ``curr_end`` does not exceed ``total_bytes - 1``. + if self.total_bytes is not None: + curr_end = min(curr_end, self.total_bytes - 1) + return curr_start, curr_end + + def _prepare_request(self): + """Prepare the contents of an HTTP request. + + This is everything that must be done before a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + .. note: + + This method will be used multiple times, so ``headers`` will + be mutated in between requests. However, we don't make a copy + since the same keys are being updated. + + Returns: + Tuple[str, str, NoneType, Mapping[str, str]]: The quadruple + + * HTTP verb for the request (always GET) + * the URL for the request + * the body of the request (always :data:`None`) + * headers for the request + + Raises: + ValueError: If the current download has finished. + ValueError: If the current download is invalid. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + if self.finished: + raise ValueError("Download has finished.") + if self.invalid: + raise ValueError("Download is invalid and cannot be re-used.") + + curr_start, curr_end = self._get_byte_range() + add_bytes_range(curr_start, curr_end, self._headers) + return _GET, self.media_url, None, self._headers + + def _make_invalid(self): + """Simple setter for ``invalid``. + + This is intended to be passed along as a callback to helpers that + raise an exception so they can mark this instance as invalid before + raising. + """ + self._invalid = True + + def _process_response(self, response): + """Process the response from an HTTP request. + + This is everything that must be done after a request that doesn't + require network I/O. This is based on the `sans-I/O`_ philosophy. + + For the time being, this **does require** some form of I/O to write + a chunk to ``stream``. However, this will (almost) certainly not be + network I/O. + + Updates the current state after consuming a chunk. First, + increments ``bytes_downloaded`` by the number of bytes in the + ``content-length`` header. + + If ``total_bytes`` is already set, this assumes (but does not check) + that we already have the correct value and doesn't bother to check + that it agrees with the headers. + + We expect the **total** length to be in the ``content-range`` header, + but this header is only present on requests which sent the ``range`` + header. This response header should be of the form + ``bytes {start}-{end}/{total}`` and ``{end} - {start} + 1`` + should be the same as the ``Content-Length``. + + Args: + response (object): The HTTP response object (need headers). + + Raises: + ~google.resumable_media.common.InvalidResponse: If the number + of bytes in the body doesn't match the content length header. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + # Verify the response before updating the current instance. + if _check_for_zero_content_range( + response, self._get_status_code, self._get_headers + ): + self._finished = True + return + + _helpers.require_status_code( + response, + _ACCEPTABLE_STATUS_CODES, + self._get_status_code, + callback=self._make_invalid, + ) + headers = self._get_headers(response) + response_body = self._get_body(response) + + start_byte, end_byte, total_bytes = get_range_info( + response, self._get_headers, callback=self._make_invalid + ) + + transfer_encoding = headers.get("transfer-encoding") + + if transfer_encoding is None: + content_length = _helpers.header_required( + response, + "content-length", + self._get_headers, + callback=self._make_invalid, + ) + num_bytes = int(content_length) + if len(response_body) != num_bytes: + self._make_invalid() + raise common.InvalidResponse( + response, + "Response is different size than content-length", + "Expected", + num_bytes, + "Received", + len(response_body), + ) + else: + # 'content-length' header not allowed with chunked encoding. + num_bytes = end_byte - start_byte + 1 + + # First update ``bytes_downloaded``. + self._bytes_downloaded += num_bytes + # If the end byte is past ``end`` or ``total_bytes - 1`` we are done. + if self.end is not None and end_byte >= self.end: + self._finished = True + elif end_byte >= total_bytes - 1: + self._finished = True + # NOTE: We only use ``total_bytes`` if not already known. + if self.total_bytes is None: + self._total_bytes = total_bytes + # Write the response body to the stream. + self._stream.write(response_body) + + def consume_next_chunk(self, transport, timeout=None): + """Consume the next chunk of the resource to be downloaded. + + Args: + transport (object): An object which can make authenticated + requests. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + +def add_bytes_range(start, end, headers): + """Add a bytes range to a header dictionary. + + Some possible inputs and the corresponding bytes ranges:: + + >>> headers = {} + >>> add_bytes_range(None, None, headers) + >>> headers + {} + >>> add_bytes_range(500, 999, headers) + >>> headers['range'] + 'bytes=500-999' + >>> add_bytes_range(None, 499, headers) + >>> headers['range'] + 'bytes=0-499' + >>> add_bytes_range(-500, None, headers) + >>> headers['range'] + 'bytes=-500' + >>> add_bytes_range(9500, None, headers) + >>> headers['range'] + 'bytes=9500-' + + Args: + start (Optional[int]): The first byte in a range. Can be zero, + positive, negative or :data:`None`. + end (Optional[int]): The last byte in a range. Assumed to be + positive. + headers (Mapping[str, str]): A headers mapping which can have the + bytes range added if at least one of ``start`` or ``end`` + is not :data:`None`. + """ + if start is None: + if end is None: + # No range to add. + return + else: + # NOTE: This assumes ``end`` is non-negative. + bytes_range = "0-{:d}".format(end) + else: + if end is None: + if start < 0: + bytes_range = "{:d}".format(start) + else: + bytes_range = "{:d}-".format(start) + else: + # NOTE: This is invalid if ``start < 0``. + bytes_range = "{:d}-{:d}".format(start, end) + + headers[_helpers.RANGE_HEADER] = "bytes=" + bytes_range + + +def get_range_info(response, get_headers, callback=_helpers.do_nothing): + """Get the start, end and total bytes from a content range header. + + Args: + response (object): An HTTP response object. + get_headers (Callable[Any, Mapping[str, str]]): Helper to get headers + from an HTTP response. + callback (Optional[Callable]): A callback that takes no arguments, + to be executed when an exception is being raised. + + Returns: + Tuple[int, int, int]: The start byte, end byte and total bytes. + + Raises: + ~google.resumable_media.common.InvalidResponse: If the + ``Content-Range`` header is not of the form + ``bytes {start}-{end}/{total}``. + """ + content_range = _helpers.header_required( + response, _helpers.CONTENT_RANGE_HEADER, get_headers, callback=callback + ) + match = _CONTENT_RANGE_RE.match(content_range) + if match is None: + callback() + raise common.InvalidResponse( + response, + "Unexpected content-range header", + content_range, + 'Expected to be of the form "bytes {start}-{end}/{total}"', + ) + + return ( + int(match.group("start_byte")), + int(match.group("end_byte")), + int(match.group("total_bytes")), + ) + + +def _check_for_zero_content_range(response, get_status_code, get_headers): + """Validate if response status code is 416 and content range is zero. + + This is the special case for handling zero bytes files. + + Args: + response (object): An HTTP response object. + get_status_code (Callable[Any, int]): Helper to get a status code + from a response. + get_headers (Callable[Any, Mapping[str, str]]): Helper to get headers + from an HTTP response. + + Returns: + bool: True if content range total bytes is zero, false otherwise. + """ + if get_status_code(response) == http.client.REQUESTED_RANGE_NOT_SATISFIABLE: + content_range = _helpers.header_required( + response, + _helpers.CONTENT_RANGE_HEADER, + get_headers, + callback=_helpers.do_nothing, + ) + if content_range == _ZERO_CONTENT_RANGE_HEADER: + return True + return False diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/resumable_media/_helpers.py b/loan-advisor-agent/.venv/Lib/site-packages/google/resumable_media/_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..e80d9909b6bfcb80dd2059363ff62c64be8bd0d0 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/resumable_media/_helpers.py @@ -0,0 +1,434 @@ +# Copyright 2017 Google Inc. +# +# Licensed 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. + +"""Shared utilities used by both downloads and uploads.""" + +from __future__ import absolute_import + +import base64 +import hashlib +import logging +import random +import warnings + +from urllib.parse import parse_qs +from urllib.parse import urlencode +from urllib.parse import urlsplit +from urllib.parse import urlunsplit + +from google.resumable_media import common + + +RANGE_HEADER = "range" +CONTENT_RANGE_HEADER = "content-range" +CONTENT_ENCODING_HEADER = "content-encoding" + +_SLOW_CRC32C_WARNING = ( + "Currently using crcmod in pure python form. This is a slow " + "implementation. Python 3 has a faster implementation, `google-crc32c`, " + "which will be used if it is installed." +) +_GENERATION_HEADER = "x-goog-generation" +_HASH_HEADER = "x-goog-hash" +_STORED_CONTENT_ENCODING_HEADER = "x-goog-stored-content-encoding" + +_MISSING_CHECKSUM = """\ +No {checksum_type} checksum was returned from the service while downloading {} +(which happens for composite objects), so client-side content integrity +checking is not being performed.""" +_LOGGER = logging.getLogger(__name__) + + +def do_nothing(): + """Simple default callback.""" + + +def header_required(response, name, get_headers, callback=do_nothing): + """Checks that a specific header is in a headers dictionary. + + Args: + response (object): An HTTP response object, expected to have a + ``headers`` attribute that is a ``Mapping[str, str]``. + name (str): The name of a required header. + get_headers (Callable[Any, Mapping[str, str]]): Helper to get headers + from an HTTP response. + callback (Optional[Callable]): A callback that takes no arguments, + to be executed when an exception is being raised. + + Returns: + str: The desired header. + + Raises: + ~google.resumable_media.common.InvalidResponse: If the header + is missing. + """ + headers = get_headers(response) + if name not in headers: + callback() + raise common.InvalidResponse( + response, "Response headers must contain header", name + ) + + return headers[name] + + +def require_status_code(response, status_codes, get_status_code, callback=do_nothing): + """Require a response has a status code among a list. + + Args: + response (object): The HTTP response object. + status_codes (tuple): The acceptable status codes. + get_status_code (Callable[Any, int]): Helper to get a status code + from a response. + callback (Optional[Callable]): A callback that takes no arguments, + to be executed when an exception is being raised. + + Returns: + int: The status code. + + Raises: + ~google.resumable_media.common.InvalidResponse: If the status code + is not one of the values in ``status_codes``. + """ + status_code = get_status_code(response) + if status_code not in status_codes: + if status_code not in common.RETRYABLE: + callback() + raise common.InvalidResponse( + response, + "Request failed with status code", + status_code, + "Expected one of", + *status_codes, + ) + return status_code + + +def calculate_retry_wait(base_wait, max_sleep, multiplier=2.0): + """Calculate the amount of time to wait before a retry attempt. + + Wait time grows exponentially with the number of attempts, until + ``max_sleep``. + + A random amount of jitter (between 0 and 1 seconds) is added to spread out + retry attempts from different clients. + + Args: + base_wait (float): The "base" wait time (i.e. without any jitter) + that will be multiplied until it reaches the maximum sleep. + max_sleep (float): Maximum value that a sleep time is allowed to be. + multiplier (float): Multiplier to apply to the base wait. + + Returns: + Tuple[float, float]: The new base wait time as well as the wait time + to be applied (with a random amount of jitter between 0 and 1 seconds + added). + """ + new_base_wait = multiplier * base_wait + if new_base_wait > max_sleep: + new_base_wait = max_sleep + + jitter_ms = random.randint(0, 1000) + return new_base_wait, new_base_wait + 0.001 * jitter_ms + + +def _get_crc32c_object(): + """Get crc32c object + Attempt to use the Google-CRC32c package. If it isn't available, try + to use CRCMod. CRCMod might be using a 'slow' varietal. If so, warn... + """ + try: + import google_crc32c # type: ignore + + crc_obj = google_crc32c.Checksum() + except ImportError: + try: + import crcmod # type: ignore + + crc_obj = crcmod.predefined.Crc("crc-32c") + _is_fast_crcmod() + + except ImportError: + raise ImportError("Failed to import either `google-crc32c` or `crcmod`") + + return crc_obj + + +def _is_fast_crcmod(): + # Determine if this is using the slow form of crcmod. + nested_crcmod = __import__( + "crcmod.crcmod", + globals(), + locals(), + ["_usingExtension"], + 0, + ) + fast_crc = getattr(nested_crcmod, "_usingExtension", False) + if not fast_crc: + warnings.warn(_SLOW_CRC32C_WARNING, RuntimeWarning, stacklevel=2) + return fast_crc + + +def _get_metadata_key(checksum_type): + if checksum_type == "md5": + return "md5Hash" + else: + return checksum_type + + +def prepare_checksum_digest(digest_bytestring): + """Convert a checksum object into a digest encoded for an HTTP header. + + Args: + bytes: A checksum digest bytestring. + + Returns: + str: A base64 string representation of the input. + """ + encoded_digest = base64.b64encode(digest_bytestring) + # NOTE: ``b64encode`` returns ``bytes``, but HTTP headers expect ``str``. + return encoded_digest.decode("utf-8") + + +def _get_expected_checksum(response, get_headers, media_url, checksum_type): + """Get the expected checksum and checksum object for the download response. + + Args: + response (~requests.Response): The HTTP response object. + get_headers (callable: response->dict): returns response headers. + media_url (str): The URL containing the media to be downloaded. + checksum_type Optional(str): The checksum type to read from the headers, + exactly as it will appear in the headers (case-sensitive). Must be + "md5", "crc32c" or None. + + Returns: + Tuple (Optional[str], object): The expected checksum of the response, + if it can be detected from the ``X-Goog-Hash`` header, and the + appropriate checksum object for the expected checksum. + """ + if checksum_type not in ["md5", "crc32c", None]: + raise ValueError("checksum must be ``'md5'``, ``'crc32c'`` or ``None``") + elif checksum_type in ["md5", "crc32c"]: + headers = get_headers(response) + expected_checksum = _parse_checksum_header( + headers.get(_HASH_HEADER), response, checksum_label=checksum_type + ) + + if expected_checksum is None: + msg = _MISSING_CHECKSUM.format( + media_url, checksum_type=checksum_type.upper() + ) + _LOGGER.info(msg) + checksum_object = _DoNothingHash() + else: + if checksum_type == "md5": + checksum_object = hashlib.md5() + else: + checksum_object = _get_crc32c_object() + else: + expected_checksum = None + checksum_object = _DoNothingHash() + + return (expected_checksum, checksum_object) + + +def _get_uploaded_checksum_from_headers(response, get_headers, checksum_type): + """Get the computed checksum and checksum object from the response headers. + + Args: + response (~requests.Response): The HTTP response object. + get_headers (callable: response->dict): returns response headers. + checksum_type Optional(str): The checksum type to read from the headers, + exactly as it will appear in the headers (case-sensitive). Must be + "md5", "crc32c" or None. + + Returns: + Tuple (Optional[str], object): The checksum of the response, + if it can be detected from the ``X-Goog-Hash`` header, and the + appropriate checksum object for the expected checksum. + """ + if checksum_type not in ["md5", "crc32c", None]: + raise ValueError("checksum must be ``'md5'``, ``'crc32c'`` or ``None``") + elif checksum_type in ["md5", "crc32c"]: + headers = get_headers(response) + remote_checksum = _parse_checksum_header( + headers.get(_HASH_HEADER), response, checksum_label=checksum_type + ) + else: + remote_checksum = None + + return remote_checksum + + +def _parse_checksum_header(header_value, response, checksum_label): + """Parses the checksum header from an ``X-Goog-Hash`` value. + + .. _header reference: https://cloud.google.com/storage/docs/\ + xml-api/reference-headers#xgooghash + + Expects ``header_value`` (if not :data:`None`) to be in one of the three + following formats: + + * ``crc32c=n03x6A==`` + * ``md5=Ojk9c3dhfxgoKVVHYwFbHQ==`` + * ``crc32c=n03x6A==,md5=Ojk9c3dhfxgoKVVHYwFbHQ==`` + + See the `header reference`_ for more information. + + Args: + header_value (Optional[str]): The ``X-Goog-Hash`` header from + a download response. + response (~requests.Response): The HTTP response object. + checksum_label (str): The label of the header value to read, as in the + examples above. Typically "md5" or "crc32c" + + Returns: + Optional[str]: The expected checksum of the response, if it + can be detected from the ``X-Goog-Hash`` header; otherwise, None. + + Raises: + ~google.resumable_media.common.InvalidResponse: If there are + multiple checksums of the requested type in ``header_value``. + """ + if header_value is None: + return None + + matches = [] + for checksum in header_value.split(","): + name, value = checksum.split("=", 1) + # Official docs say "," is the separator, but real-world responses have encountered ", " + if name.lstrip() == checksum_label: + matches.append(value) + + if len(matches) == 0: + return None + elif len(matches) == 1: + return matches[0] + else: + raise common.InvalidResponse( + response, + "X-Goog-Hash header had multiple ``{}`` values.".format(checksum_label), + header_value, + matches, + ) + + +def _get_checksum_object(checksum_type): + """Respond with a checksum object for a supported type, if not None. + + Raises ValueError if checksum_type is unsupported. + """ + if checksum_type == "md5": + return hashlib.md5() + elif checksum_type == "crc32c": + return _get_crc32c_object() + elif checksum_type is None: + return None + else: + raise ValueError("checksum must be ``'md5'``, ``'crc32c'`` or ``None``") + + +def _parse_generation_header(response, get_headers): + """Parses the generation header from an ``X-Goog-Generation`` value. + + Args: + response (~requests.Response): The HTTP response object. + get_headers (callable: response->dict): returns response headers. + + Returns: + Optional[long]: The object generation from the response, if it + can be detected from the ``X-Goog-Generation`` header; otherwise, None. + """ + headers = get_headers(response) + object_generation = headers.get(_GENERATION_HEADER, None) + + if object_generation is None: + return None + else: + return int(object_generation) + + +def _get_generation_from_url(media_url): + """Retrieve the object generation query param specified in the media url. + + Args: + media_url (str): The URL containing the media to be downloaded. + + Returns: + long: The object generation from the media url if exists; otherwise, None. + """ + + _, _, _, query, _ = urlsplit(media_url) + query_params = parse_qs(query) + object_generation = query_params.get("generation", None) + + if object_generation is None: + return None + else: + return int(object_generation[0]) + + +def add_query_parameters(media_url, query_params): + """Add query parameters to a base url. + + Args: + media_url (str): The URL containing the media to be downloaded. + query_params (dict): Names and values of the query parameters to add. + + Returns: + str: URL with additional query strings appended. + """ + + if len(query_params) == 0: + return media_url + + scheme, netloc, path, query, frag = urlsplit(media_url) + params = parse_qs(query) + new_params = {**params, **query_params} + query = urlencode(new_params, doseq=True) + return urlunsplit((scheme, netloc, path, query, frag)) + + +def _is_decompressive_transcoding(response, get_headers): + """Returns True if the object was served decompressed. This happens when the + "x-goog-stored-content-encoding" header is "gzip" and "content-encoding" header + is not "gzip". See more at: https://cloud.google.com/storage/docs/transcoding#transcoding_and_gzip + Args: + response (~requests.Response): The HTTP response object. + get_headers (callable: response->dict): returns response headers. + Returns: + bool: Returns True if decompressive transcoding has occurred; otherwise, False. + """ + headers = get_headers(response) + return ( + headers.get(_STORED_CONTENT_ENCODING_HEADER) == "gzip" + and headers.get(CONTENT_ENCODING_HEADER) != "gzip" + ) + + +class _DoNothingHash(object): + """Do-nothing hash object. + + Intended as a stand-in for ``hashlib.md5`` or a crc32c checksum + implementation in cases where it isn't necessary to compute the hash. + """ + + def update(self, unused_chunk): + """Do-nothing ``update`` method. + + Intended to match the interface of ``hashlib.md5`` and other checksums. + + Args: + unused_chunk (bytes): A chunk of data. + """ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/resumable_media/_upload.py b/loan-advisor-agent/.venv/Lib/site-packages/google/resumable_media/_upload.py new file mode 100644 index 0000000000000000000000000000000000000000..e176fb391d8c96643fb82e2b1a7e2e8336147f7e --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/resumable_media/_upload.py @@ -0,0 +1,1531 @@ +# Copyright 2017 Google Inc. +# +# Licensed 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. + +"""Virtual bases classes for uploading media via Google APIs. + +Supported here are: + +* simple (media) uploads +* multipart uploads that contain both metadata and a small file as payload +* resumable uploads (with metadata as well) +""" + +import http.client +import json +import os +import random +import re +import sys +import urllib.parse + +from google import resumable_media +from google.resumable_media import _helpers +from google.resumable_media import common + +from xml.etree import ElementTree + + +_CONTENT_TYPE_HEADER = "content-type" +_CONTENT_RANGE_TEMPLATE = "bytes {:d}-{:d}/{:d}" +_RANGE_UNKNOWN_TEMPLATE = "bytes {:d}-{:d}/*" +_EMPTY_RANGE_TEMPLATE = "bytes */{:d}" +_BOUNDARY_WIDTH = len(str(sys.maxsize - 1)) +_BOUNDARY_FORMAT = "==============={{:0{:d}d}}==".format(_BOUNDARY_WIDTH) +_MULTIPART_SEP = b"--" +_CRLF = b"\r\n" +_MULTIPART_BEGIN = b"\r\ncontent-type: application/json; charset=UTF-8\r\n\r\n" +_RELATED_HEADER = b'multipart/related; boundary="' +_BYTES_RANGE_RE = re.compile(r"bytes=0-(?P\d+)", flags=re.IGNORECASE) +_STREAM_ERROR_TEMPLATE = ( + "Bytes stream is in unexpected state. " + "The local stream has had {:d} bytes read from it while " + "{:d} bytes have already been updated (they should match)." +) +_STREAM_READ_PAST_TEMPLATE = ( + "{:d} bytes have been read from the stream, which exceeds the expected total {:d}." +) +_DELETE = "DELETE" +_POST = "POST" +_PUT = "PUT" +_UPLOAD_CHECKSUM_MISMATCH_MESSAGE = ( + "The computed ``{}`` checksum, ``{}``, and the checksum reported by the " + "remote host, ``{}``, did not match." +) +_UPLOAD_METADATA_NO_APPROPRIATE_CHECKSUM_MESSAGE = ( + "Response metadata had no ``{}`` value; checksum could not be validated." +) +_UPLOAD_HEADER_NO_APPROPRIATE_CHECKSUM_MESSAGE = ( + "Response headers had no ``{}`` value; checksum could not be validated." +) +_MPU_INITIATE_QUERY = "?uploads" +_MPU_PART_QUERY_TEMPLATE = "?partNumber={part}&uploadId={upload_id}" +_S3_COMPAT_XML_NAMESPACE = "{http://s3.amazonaws.com/doc/2006-03-01/}" +_UPLOAD_ID_NODE = "UploadId" +_MPU_FINAL_QUERY_TEMPLATE = "?uploadId={upload_id}" + + +class UploadBase(object): + """Base class for upload helpers. + + Defines core shared behavior across different upload types. + + Args: + upload_url (str): The URL where the content will be uploaded. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with the request, e.g. headers for encrypted data. + + Attributes: + upload_url (str): The URL where the content will be uploaded. + """ + + def __init__(self, upload_url, headers=None): + self.upload_url = upload_url + if headers is None: + headers = {} + self._headers = headers + self._finished = False + self._retry_strategy = common.RetryStrategy() + + @property + def finished(self): + """bool: Flag indicating if the upload has completed.""" + return self._finished + + def _process_response(self, response): + """Process the response from an HTTP request. + + This is everything that must be done after a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + Args: + response (object): The HTTP response object. + + Raises: + ~google.resumable_media.common.InvalidResponse: If the status + code is not 200. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + # Tombstone the current upload so it cannot be used again (in either + # failure or success). + self._finished = True + _helpers.require_status_code(response, (http.client.OK,), self._get_status_code) + + @staticmethod + def _get_status_code(response): + """Access the status code from an HTTP response. + + Args: + response (object): The HTTP response object. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + @staticmethod + def _get_headers(response): + """Access the headers from an HTTP response. + + Args: + response (object): The HTTP response object. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + @staticmethod + def _get_body(response): + """Access the response body from an HTTP response. + + Args: + response (object): The HTTP response object. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + +class SimpleUpload(UploadBase): + """Upload a resource to a Google API. + + A **simple** media upload sends no metadata and completes the upload + in a single request. + + Args: + upload_url (str): The URL where the content will be uploaded. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with the request, e.g. headers for encrypted data. + + Attributes: + upload_url (str): The URL where the content will be uploaded. + """ + + def _prepare_request(self, data, content_type): + """Prepare the contents of an HTTP request. + + This is everything that must be done before a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + .. note: + + This method will be used only once, so ``headers`` will be + mutated by having a new key added to it. + + Args: + data (bytes): The resource content to be uploaded. + content_type (str): The content type for the request. + + Returns: + Tuple[str, str, bytes, Mapping[str, str]]: The quadruple + + * HTTP verb for the request (always POST) + * the URL for the request + * the body of the request + * headers for the request + + Raises: + ValueError: If the current upload has already finished. + TypeError: If ``data`` isn't bytes. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + if self.finished: + raise ValueError("An upload can only be used once.") + + if not isinstance(data, bytes): + raise TypeError("`data` must be bytes, received", type(data)) + self._headers[_CONTENT_TYPE_HEADER] = content_type + return _POST, self.upload_url, data, self._headers + + def transmit(self, transport, data, content_type, timeout=None): + """Transmit the resource to be uploaded. + + Args: + transport (object): An object which can make authenticated + requests. + data (bytes): The resource content to be uploaded. + content_type (str): The content type of the resource, e.g. a JPEG + image has content type ``image/jpeg``. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + +class MultipartUpload(UploadBase): + """Upload a resource with metadata to a Google API. + + A **multipart** upload sends both metadata and the resource in a single + (multipart) request. + + Args: + upload_url (str): The URL where the content will be uploaded. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with the request, e.g. headers for encrypted data. + checksum (Optional([str])): The type of checksum to compute to verify + the integrity of the object. The request metadata will be amended + to include the computed value. Using this option will override a + manually-set checksum value. Supported values are "md5", "crc32c" + and None. The default is None. + + Attributes: + upload_url (str): The URL where the content will be uploaded. + """ + + def __init__(self, upload_url, headers=None, checksum=None): + super(MultipartUpload, self).__init__(upload_url, headers=headers) + self._checksum_type = checksum + + def _prepare_request(self, data, metadata, content_type): + """Prepare the contents of an HTTP request. + + This is everything that must be done before a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + .. note: + + This method will be used only once, so ``headers`` will be + mutated by having a new key added to it. + + Args: + data (bytes): The resource content to be uploaded. + metadata (Mapping[str, str]): The resource metadata, such as an + ACL list. + content_type (str): The content type of the resource, e.g. a JPEG + image has content type ``image/jpeg``. + + Returns: + Tuple[str, str, bytes, Mapping[str, str]]: The quadruple + + * HTTP verb for the request (always POST) + * the URL for the request + * the body of the request + * headers for the request + + Raises: + ValueError: If the current upload has already finished. + TypeError: If ``data`` isn't bytes. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + if self.finished: + raise ValueError("An upload can only be used once.") + + if not isinstance(data, bytes): + raise TypeError("`data` must be bytes, received", type(data)) + + checksum_object = _helpers._get_checksum_object(self._checksum_type) + if checksum_object is not None: + checksum_object.update(data) + actual_checksum = _helpers.prepare_checksum_digest(checksum_object.digest()) + metadata_key = _helpers._get_metadata_key(self._checksum_type) + metadata[metadata_key] = actual_checksum + + content, multipart_boundary = construct_multipart_request( + data, metadata, content_type + ) + multipart_content_type = _RELATED_HEADER + multipart_boundary + b'"' + self._headers[_CONTENT_TYPE_HEADER] = multipart_content_type + + return _POST, self.upload_url, content, self._headers + + def transmit(self, transport, data, metadata, content_type, timeout=None): + """Transmit the resource to be uploaded. + + Args: + transport (object): An object which can make authenticated + requests. + data (bytes): The resource content to be uploaded. + metadata (Mapping[str, str]): The resource metadata, such as an + ACL list. + content_type (str): The content type of the resource, e.g. a JPEG + image has content type ``image/jpeg``. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + +class ResumableUpload(UploadBase): + """Initiate and fulfill a resumable upload to a Google API. + + A **resumable** upload sends an initial request with the resource metadata + and then gets assigned an upload ID / upload URL to send bytes to. + Using the upload URL, the upload is then done in chunks (determined by + the user) until all bytes have been uploaded. + + Args: + upload_url (str): The URL where the resumable upload will be initiated. + chunk_size (int): The size of each chunk used to upload the resource. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with every request. + checksum (Optional([str])): The type of checksum to compute to verify + the integrity of the object. After the upload is complete, the + server-computed checksum of the resulting object will be read + and google.resumable_media.common.DataCorruption will be raised on + a mismatch. The corrupted file will not be deleted from the remote + host automatically. Supported values are "md5", "crc32c" and None. + The default is None. + + Attributes: + upload_url (str): The URL where the content will be uploaded. + + Raises: + ValueError: If ``chunk_size`` is not a multiple of + :data:`.UPLOAD_CHUNK_SIZE`. + """ + + def __init__(self, upload_url, chunk_size, checksum=None, headers=None): + super(ResumableUpload, self).__init__(upload_url, headers=headers) + if chunk_size % resumable_media.UPLOAD_CHUNK_SIZE != 0: + raise ValueError( + "{} KB must divide chunk size".format( + resumable_media.UPLOAD_CHUNK_SIZE / 1024 + ) + ) + self._chunk_size = chunk_size + self._stream = None + self._content_type = None + self._bytes_uploaded = 0 + self._bytes_checksummed = 0 + self._checksum_type = checksum + self._checksum_object = None + self._total_bytes = None + self._resumable_url = None + self._invalid = False + + @property + def invalid(self): + """bool: Indicates if the upload is in an invalid state. + + This will occur if a call to :meth:`transmit_next_chunk` fails. + To recover from such a failure, call :meth:`recover`. + """ + return self._invalid + + @property + def chunk_size(self): + """int: The size of each chunk used to upload the resource.""" + return self._chunk_size + + @property + def resumable_url(self): + """Optional[str]: The URL of the in-progress resumable upload.""" + return self._resumable_url + + @property + def bytes_uploaded(self): + """int: Number of bytes that have been uploaded.""" + return self._bytes_uploaded + + @property + def total_bytes(self): + """Optional[int]: The total number of bytes to be uploaded. + + If this upload is initiated (via :meth:`initiate`) with + ``stream_final=True``, this value will be populated based on the size + of the ``stream`` being uploaded. (By default ``stream_final=True``.) + + If this upload is initiated with ``stream_final=False``, + :attr:`total_bytes` will be :data:`None` since it cannot be + determined from the stream. + """ + return self._total_bytes + + def _prepare_initiate_request( + self, stream, metadata, content_type, total_bytes=None, stream_final=True + ): + """Prepare the contents of HTTP request to initiate upload. + + This is everything that must be done before a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + Args: + stream (IO[bytes]): The stream (i.e. file-like object) that will + be uploaded. The stream **must** be at the beginning (i.e. + ``stream.tell() == 0``). + metadata (Mapping[str, str]): The resource metadata, such as an + ACL list. + content_type (str): The content type of the resource, e.g. a JPEG + image has content type ``image/jpeg``. + total_bytes (Optional[int]): The total number of bytes to be + uploaded. If specified, the upload size **will not** be + determined from the stream (even if ``stream_final=True``). + stream_final (Optional[bool]): Indicates if the ``stream`` is + "final" (i.e. no more bytes will be added to it). In this case + we determine the upload size from the size of the stream. If + ``total_bytes`` is passed, this argument will be ignored. + + Returns: + Tuple[str, str, bytes, Mapping[str, str]]: The quadruple + + * HTTP verb for the request (always POST) + * the URL for the request + * the body of the request + * headers for the request + + Raises: + ValueError: If the current upload has already been initiated. + ValueError: If ``stream`` is not at the beginning. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + if self.resumable_url is not None: + raise ValueError("This upload has already been initiated.") + if stream.tell() != 0: + raise ValueError("Stream must be at beginning.") + + self._stream = stream + self._content_type = content_type + + # Signed URL requires content type set directly - not through x-upload-content-type + parse_result = urllib.parse.urlparse(self.upload_url) + parsed_query = urllib.parse.parse_qs(parse_result.query) + if "x-goog-signature" in parsed_query or "X-Goog-Signature" in parsed_query: + # Deconstruct **self._headers first so that content type defined here takes priority + headers = {**self._headers, _CONTENT_TYPE_HEADER: content_type} + else: + # Deconstruct **self._headers first so that content type defined here takes priority + headers = { + **self._headers, + _CONTENT_TYPE_HEADER: "application/json; charset=UTF-8", + "x-upload-content-type": content_type, + } + # Set the total bytes if possible. + if total_bytes is not None: + self._total_bytes = total_bytes + elif stream_final: + self._total_bytes = get_total_bytes(stream) + # Add the total bytes to the headers if set. + if self._total_bytes is not None: + content_length = "{:d}".format(self._total_bytes) + headers["x-upload-content-length"] = content_length + + payload = json.dumps(metadata).encode("utf-8") + return _POST, self.upload_url, payload, headers + + def _process_initiate_response(self, response): + """Process the response from an HTTP request that initiated upload. + + This is everything that must be done after a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + This method takes the URL from the ``Location`` header and stores it + for future use. Within that URL, we assume the ``upload_id`` query + parameter has been included, but we do not check. + + Args: + response (object): The HTTP response object (need headers). + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + _helpers.require_status_code( + response, + (http.client.OK, http.client.CREATED), + self._get_status_code, + callback=self._make_invalid, + ) + self._resumable_url = _helpers.header_required( + response, "location", self._get_headers + ) + + def initiate( + self, + transport, + stream, + metadata, + content_type, + total_bytes=None, + stream_final=True, + timeout=None, + ): + """Initiate a resumable upload. + + By default, this method assumes your ``stream`` is in a "final" + state ready to transmit. However, ``stream_final=False`` can be used + to indicate that the size of the resource is not known. This can happen + if bytes are being dynamically fed into ``stream``, e.g. if the stream + is attached to application logs. + + If ``stream_final=False`` is used, :attr:`chunk_size` bytes will be + read from the stream every time :meth:`transmit_next_chunk` is called. + If one of those reads produces strictly fewer bites than the chunk + size, the upload will be concluded. + + Args: + transport (object): An object which can make authenticated + requests. + stream (IO[bytes]): The stream (i.e. file-like object) that will + be uploaded. The stream **must** be at the beginning (i.e. + ``stream.tell() == 0``). + metadata (Mapping[str, str]): The resource metadata, such as an + ACL list. + content_type (str): The content type of the resource, e.g. a JPEG + image has content type ``image/jpeg``. + total_bytes (Optional[int]): The total number of bytes to be + uploaded. If specified, the upload size **will not** be + determined from the stream (even if ``stream_final=True``). + stream_final (Optional[bool]): Indicates if the ``stream`` is + "final" (i.e. no more bytes will be added to it). In this case + we determine the upload size from the size of the stream. If + ``total_bytes`` is passed, this argument will be ignored. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + def _prepare_request(self): + """Prepare the contents of HTTP request to upload a chunk. + + This is everything that must be done before a request that doesn't + require network I/O. This is based on the `sans-I/O`_ philosophy. + + For the time being, this **does require** some form of I/O to read + a chunk from ``stream`` (via :func:`get_next_chunk`). However, this + will (almost) certainly not be network I/O. + + Returns: + Tuple[str, str, bytes, Mapping[str, str]]: The quadruple + + * HTTP verb for the request (always PUT) + * the URL for the request + * the body of the request + * headers for the request + + The headers incorporate the ``_headers`` on the current instance. + + Raises: + ValueError: If the current upload has finished. + ValueError: If the current upload is in an invalid state. + ValueError: If the current upload has not been initiated. + ValueError: If the location in the stream (i.e. ``stream.tell()``) + does not agree with ``bytes_uploaded``. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + if self.finished: + raise ValueError("Upload has finished.") + if self.invalid: + raise ValueError( + "Upload is in an invalid state. To recover call `recover()`." + ) + if self.resumable_url is None: + raise ValueError( + "This upload has not been initiated. Please call " + "initiate() before beginning to transmit chunks." + ) + + start_byte, payload, content_range = get_next_chunk( + self._stream, self._chunk_size, self._total_bytes + ) + if start_byte != self.bytes_uploaded: + msg = _STREAM_ERROR_TEMPLATE.format(start_byte, self.bytes_uploaded) + raise ValueError(msg) + + self._update_checksum(start_byte, payload) + + headers = { + **self._headers, + _CONTENT_TYPE_HEADER: self._content_type, + _helpers.CONTENT_RANGE_HEADER: content_range, + } + return _PUT, self.resumable_url, payload, headers + + def _update_checksum(self, start_byte, payload): + """Update the checksum with the payload if not already updated. + + Because error recovery can result in bytes being transmitted more than + once, the checksum tracks the number of bytes checked in + self._bytes_checksummed and skips bytes that have already been summed. + """ + if not self._checksum_type: + return + + if not self._checksum_object: + self._checksum_object = _helpers._get_checksum_object(self._checksum_type) + + if start_byte < self._bytes_checksummed: + offset = self._bytes_checksummed - start_byte + data = payload[offset:] + else: + data = payload + + self._checksum_object.update(data) + self._bytes_checksummed += len(data) + + def _make_invalid(self): + """Simple setter for ``invalid``. + + This is intended to be passed along as a callback to helpers that + raise an exception so they can mark this instance as invalid before + raising. + """ + self._invalid = True + + def _process_resumable_response(self, response, bytes_sent): + """Process the response from an HTTP request. + + This is everything that must be done after a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + Args: + response (object): The HTTP response object. + bytes_sent (int): The number of bytes sent in the request that + ``response`` was returned for. + + Raises: + ~google.resumable_media.common.InvalidResponse: If the status + code is 308 and the ``range`` header is not of the form + ``bytes 0-{end}``. + ~google.resumable_media.common.InvalidResponse: If the status + code is not 200 or 308. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + status_code = _helpers.require_status_code( + response, + (http.client.OK, http.client.PERMANENT_REDIRECT), + self._get_status_code, + callback=self._make_invalid, + ) + if status_code == http.client.OK: + # NOTE: We use the "local" information of ``bytes_sent`` to update + # ``bytes_uploaded``, but do not verify this against other + # state. However, there may be some other information: + # + # * a ``size`` key in JSON response body + # * the ``total_bytes`` attribute (if set) + # * ``stream.tell()`` (relying on fact that ``initiate()`` + # requires stream to be at the beginning) + self._bytes_uploaded = self._bytes_uploaded + bytes_sent + # Tombstone the current upload so it cannot be used again. + self._finished = True + # Validate the checksum. This can raise an exception on failure. + self._validate_checksum(response) + else: + bytes_range = _helpers.header_required( + response, + _helpers.RANGE_HEADER, + self._get_headers, + callback=self._make_invalid, + ) + match = _BYTES_RANGE_RE.match(bytes_range) + if match is None: + self._make_invalid() + raise common.InvalidResponse( + response, + 'Unexpected "range" header', + bytes_range, + 'Expected to be of the form "bytes=0-{end}"', + ) + self._bytes_uploaded = int(match.group("end_byte")) + 1 + + def _validate_checksum(self, response): + """Check the computed checksum, if any, against the recieved metadata. + + Args: + response (object): The HTTP response object. + + Raises: + ~google.resumable_media.common.DataCorruption: If the checksum + computed locally and the checksum reported by the remote host do + not match. + """ + if self._checksum_type is None: + return + metadata_key = _helpers._get_metadata_key(self._checksum_type) + metadata = response.json() + remote_checksum = metadata.get(metadata_key) + if remote_checksum is None: + raise common.InvalidResponse( + response, + _UPLOAD_METADATA_NO_APPROPRIATE_CHECKSUM_MESSAGE.format(metadata_key), + self._get_headers(response), + ) + local_checksum = _helpers.prepare_checksum_digest( + self._checksum_object.digest() + ) + if local_checksum != remote_checksum: + raise common.DataCorruption( + response, + _UPLOAD_CHECKSUM_MISMATCH_MESSAGE.format( + self._checksum_type.upper(), local_checksum, remote_checksum + ), + ) + + def transmit_next_chunk(self, transport, timeout=None): + """Transmit the next chunk of the resource to be uploaded. + + If the current upload was initiated with ``stream_final=False``, + this method will dynamically determine if the upload has completed. + The upload will be considered complete if the stream produces + fewer than :attr:`chunk_size` bytes when a chunk is read from it. + + Args: + transport (object): An object which can make authenticated + requests. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + def _prepare_recover_request(self): + """Prepare the contents of HTTP request to recover from failure. + + This is everything that must be done before a request that doesn't + require network I/O. This is based on the `sans-I/O`_ philosophy. + + We assume that the :attr:`resumable_url` is set (i.e. the only way + the upload can end up :attr:`invalid` is if it has been initiated. + + Returns: + Tuple[str, str, NoneType, Mapping[str, str]]: The quadruple + + * HTTP verb for the request (always PUT) + * the URL for the request + * the body of the request (always :data:`None`) + * headers for the request + + The headers **do not** incorporate the ``_headers`` on the + current instance. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + headers = {_helpers.CONTENT_RANGE_HEADER: "bytes */*"} + return _PUT, self.resumable_url, None, headers + + def _process_recover_response(self, response): + """Process the response from an HTTP request to recover from failure. + + This is everything that must be done after a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + Args: + response (object): The HTTP response object. + + Raises: + ~google.resumable_media.common.InvalidResponse: If the status + code is not 308. + ~google.resumable_media.common.InvalidResponse: If the status + code is 308 and the ``range`` header is not of the form + ``bytes 0-{end}``. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + _helpers.require_status_code( + response, (http.client.PERMANENT_REDIRECT,), self._get_status_code + ) + headers = self._get_headers(response) + if _helpers.RANGE_HEADER in headers: + bytes_range = headers[_helpers.RANGE_HEADER] + match = _BYTES_RANGE_RE.match(bytes_range) + if match is None: + raise common.InvalidResponse( + response, + 'Unexpected "range" header', + bytes_range, + 'Expected to be of the form "bytes=0-{end}"', + ) + self._bytes_uploaded = int(match.group("end_byte")) + 1 + else: + # In this case, the upload has not "begun". + self._bytes_uploaded = 0 + + self._stream.seek(self._bytes_uploaded) + self._invalid = False + + def recover(self, transport): + """Recover from a failure. + + This method should be used when a :class:`ResumableUpload` is in an + :attr:`~ResumableUpload.invalid` state due to a request failure. + + This will verify the progress with the server and make sure the + current upload is in a valid state before :meth:`transmit_next_chunk` + can be used again. + + Args: + transport (object): An object which can make authenticated + requests. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + +class XMLMPUContainer(UploadBase): + """Initiate and close an upload using the XML MPU API. + + An XML MPU sends an initial request and then receives an upload ID. + Using the upload ID, the upload is then done in numbered parts and the + parts can be uploaded concurrently. + + In order to avoid concurrency issues with this container object, the + uploading of individual parts is handled separately, by XMLMPUPart objects + spawned from this container class. The XMLMPUPart objects are not + necessarily in the same process as the container, so they do not update the + container automatically. + + MPUs are sometimes referred to as "Multipart Uploads", which is ambiguous + given the JSON multipart upload, so the abbreviation "MPU" will be used + throughout. + + See: https://cloud.google.com/storage/docs/multipart-uploads + + Args: + upload_url (str): The URL of the object (without query parameters). The + initiate, PUT, and finalization requests will all use this URL, with + varying query parameters. + filename (str): The name (path) of the file to upload. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with every request. + + Attributes: + upload_url (str): The URL where the content will be uploaded. + upload_id (Optional(str)): The ID of the upload from the initialization + response. + """ + + def __init__(self, upload_url, filename, headers=None, upload_id=None): + super().__init__(upload_url, headers=headers) + self._filename = filename + self._upload_id = upload_id + self._parts = {} + + @property + def upload_id(self): + return self._upload_id + + def register_part(self, part_number, etag): + """Register an uploaded part by part number and corresponding etag. + + XMLMPUPart objects represent individual parts, and their part number + and etag can be registered to the container object with this method + and therefore incorporated in the finalize() call to finish the upload. + + This method accepts part_number and etag, but not XMLMPUPart objects + themselves, to reduce the complexity involved in running XMLMPUPart + uploads in separate processes. + + Args: + part_number (int): The part number. Parts are assembled into the + final uploaded object with finalize() in order of their part + numbers. + etag (str): The etag included in the server response after upload. + """ + self._parts[part_number] = etag + + def _prepare_initiate_request(self, content_type): + """Prepare the contents of HTTP request to initiate upload. + + This is everything that must be done before a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + Args: + content_type (str): The content type of the resource, e.g. a JPEG + image has content type ``image/jpeg``. + + Returns: + Tuple[str, str, bytes, Mapping[str, str]]: The quadruple + + * HTTP verb for the request (always POST) + * the URL for the request + * the body of the request + * headers for the request + + Raises: + ValueError: If the current upload has already been initiated. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + if self.upload_id is not None: + raise ValueError("This upload has already been initiated.") + + initiate_url = self.upload_url + _MPU_INITIATE_QUERY + + headers = { + **self._headers, + _CONTENT_TYPE_HEADER: content_type, + } + return _POST, initiate_url, None, headers + + def _process_initiate_response(self, response): + """Process the response from an HTTP request that initiated the upload. + + This is everything that must be done after a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + This method takes the URL from the ``Location`` header and stores it + for future use. Within that URL, we assume the ``upload_id`` query + parameter has been included, but we do not check. + + Args: + response (object): The HTTP response object. + + Raises: + ~google.resumable_media.common.InvalidResponse: If the status + code is not 200. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + _helpers.require_status_code(response, (http.client.OK,), self._get_status_code) + root = ElementTree.fromstring(response.text) + self._upload_id = root.find(_S3_COMPAT_XML_NAMESPACE + _UPLOAD_ID_NODE).text + + def initiate( + self, + transport, + content_type, + timeout=None, + ): + """Initiate an MPU and record the upload ID. + + Args: + transport (object): An object which can make authenticated + requests. + content_type (str): The content type of the resource, e.g. a JPEG + image has content type ``image/jpeg``. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + def _prepare_finalize_request(self): + """Prepare the contents of an HTTP request to finalize the upload. + + All of the parts must be registered before calling this method. + + Returns: + Tuple[str, str, bytes, Mapping[str, str]]: The quadruple + + * HTTP verb for the request (always POST) + * the URL for the request + * the body of the request + * headers for the request + + Raises: + ValueError: If the upload has not been initiated. + """ + if self.upload_id is None: + raise ValueError("This upload has not yet been initiated.") + + final_query = _MPU_FINAL_QUERY_TEMPLATE.format(upload_id=self._upload_id) + finalize_url = self.upload_url + final_query + final_xml_root = ElementTree.Element("CompleteMultipartUpload") + for part_number, etag in self._parts.items(): + part = ElementTree.SubElement(final_xml_root, "Part") # put in a loop + ElementTree.SubElement(part, "PartNumber").text = str(part_number) + ElementTree.SubElement(part, "ETag").text = etag + payload = ElementTree.tostring(final_xml_root) + return _POST, finalize_url, payload, self._headers + + def _process_finalize_response(self, response): + """Process the response from an HTTP request that finalized the upload. + + This is everything that must be done after a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + Args: + response (object): The HTTP response object. + + Raises: + ~google.resumable_media.common.InvalidResponse: If the status + code is not 200. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + + _helpers.require_status_code(response, (http.client.OK,), self._get_status_code) + self._finished = True + + def finalize( + self, + transport, + timeout=None, + ): + """Finalize an MPU request with all the parts. + + Args: + transport (object): An object which can make authenticated + requests. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + def _prepare_cancel_request(self): + """Prepare the contents of an HTTP request to cancel the upload. + + Returns: + Tuple[str, str, bytes, Mapping[str, str]]: The quadruple + + * HTTP verb for the request (always DELETE) + * the URL for the request + * the body of the request + * headers for the request + + Raises: + ValueError: If the upload has not been initiated. + """ + if self.upload_id is None: + raise ValueError("This upload has not yet been initiated.") + + cancel_query = _MPU_FINAL_QUERY_TEMPLATE.format(upload_id=self._upload_id) + cancel_url = self.upload_url + cancel_query + return _DELETE, cancel_url, None, self._headers + + def _process_cancel_response(self, response): + """Process the response from an HTTP request that canceled the upload. + + This is everything that must be done after a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + Args: + response (object): The HTTP response object. + + Raises: + ~google.resumable_media.common.InvalidResponse: If the status + code is not 204. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + + _helpers.require_status_code( + response, (http.client.NO_CONTENT,), self._get_status_code + ) + + def cancel( + self, + transport, + timeout=None, + ): + """Cancel an MPU request and permanently delete any uploaded parts. + + This cannot be undone. + + Args: + transport (object): An object which can make authenticated + requests. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + +class XMLMPUPart(UploadBase): + """Upload a single part of an existing XML MPU container. + + An XML MPU sends an initial request and then receives an upload ID. + Using the upload ID, the upload is then done in numbered parts and the + parts can be uploaded concurrently. + + In order to avoid concurrency issues with the container object, the + uploading of individual parts is handled separately by multiple objects + of this class. Once a part is uploaded, it can be registered with the + container with `container.register_part(part.part_number, part.etag)`. + + MPUs are sometimes referred to as "Multipart Uploads", which is ambiguous + given the JSON multipart upload, so the abbreviation "MPU" will be used + throughout. + + See: https://cloud.google.com/storage/docs/multipart-uploads + + Args: + upload_url (str): The URL of the object (without query parameters). + upload_id (str): The ID of the upload from the initialization response. + filename (str): The name (path) of the file to upload. + start (int): The byte index of the beginning of the part. + end (int): The byte index of the end of the part. + part_number (int): The part number. Part numbers will be assembled in + sequential order when the container is finalized. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with every request. + checksum (Optional([str])): The type of checksum to compute to verify + the integrity of the object. The request headers will be amended + to include the computed value. Supported values are "md5", "crc32c" + and None. The default is None. + + Attributes: + upload_url (str): The URL of the object (without query parameters). + upload_id (str): The ID of the upload from the initialization response. + filename (str): The name (path) of the file to upload. + start (int): The byte index of the beginning of the part. + end (int): The byte index of the end of the part. + part_number (int): The part number. Part numbers will be assembled in + sequential order when the container is finalized. + etag (Optional(str)): The etag returned by the service after upload. + """ + + def __init__( + self, + upload_url, + upload_id, + filename, + start, + end, + part_number, + headers=None, + checksum=None, + ): + super().__init__(upload_url, headers=headers) + self._filename = filename + self._start = start + self._end = end + self._upload_id = upload_id + self._part_number = part_number + self._etag = None + self._checksum_type = checksum + self._checksum_object = None + + @property + def part_number(self): + return self._part_number + + @property + def upload_id(self): + return self._upload_id + + @property + def filename(self): + return self._filename + + @property + def etag(self): + return self._etag + + @property + def start(self): + return self._start + + @property + def end(self): + return self._end + + def _prepare_upload_request(self): + """Prepare the contents of HTTP request to upload a part. + + This is everything that must be done before a request that doesn't + require network I/O. This is based on the `sans-I/O`_ philosophy. + + For the time being, this **does require** some form of I/O to read + a part from ``stream`` (via :func:`get_part_payload`). However, this + will (almost) certainly not be network I/O. + + Returns: + Tuple[str, str, bytes, Mapping[str, str]]: The quadruple + + * HTTP verb for the request (always PUT) + * the URL for the request + * the body of the request + * headers for the request + + The headers incorporate the ``_headers`` on the current instance. + + Raises: + ValueError: If the current upload has finished. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + if self.finished: + raise ValueError("This part has already been uploaded.") + + with open(self._filename, "br") as f: + f.seek(self._start) + payload = f.read(self._end - self._start) + + self._checksum_object = _helpers._get_checksum_object(self._checksum_type) + if self._checksum_object is not None: + self._checksum_object.update(payload) + + part_query = _MPU_PART_QUERY_TEMPLATE.format( + part=self._part_number, upload_id=self._upload_id + ) + upload_url = self.upload_url + part_query + return _PUT, upload_url, payload, self._headers + + def _process_upload_response(self, response): + """Process the response from an HTTP request. + + This is everything that must be done after a request that doesn't + require network I/O (or other I/O). This is based on the `sans-I/O`_ + philosophy. + + Args: + response (object): The HTTP response object. + + Raises: + ~google.resumable_media.common.InvalidResponse: If the status + code is not 200 or the response is missing data. + + .. _sans-I/O: https://sans-io.readthedocs.io/ + """ + _helpers.require_status_code( + response, + (http.client.OK,), + self._get_status_code, + ) + + self._validate_checksum(response) + + etag = _helpers.header_required(response, "etag", self._get_headers) + self._etag = etag + self._finished = True + + def upload( + self, + transport, + timeout=None, + ): + """Upload the part. + + Args: + transport (object): An object which can make authenticated + requests. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Raises: + NotImplementedError: Always, since virtual. + """ + raise NotImplementedError("This implementation is virtual.") + + def _validate_checksum(self, response): + """Check the computed checksum, if any, against the response headers. + + Args: + response (object): The HTTP response object. + + Raises: + ~google.resumable_media.common.DataCorruption: If the checksum + computed locally and the checksum reported by the remote host do + not match. + """ + if self._checksum_type is None: + return + + remote_checksum = _helpers._get_uploaded_checksum_from_headers( + response, self._get_headers, self._checksum_type + ) + + if remote_checksum is None: + metadata_key = _helpers._get_metadata_key(self._checksum_type) + raise common.InvalidResponse( + response, + _UPLOAD_METADATA_NO_APPROPRIATE_CHECKSUM_MESSAGE.format(metadata_key), + self._get_headers(response), + ) + local_checksum = _helpers.prepare_checksum_digest( + self._checksum_object.digest() + ) + if local_checksum != remote_checksum: + raise common.DataCorruption( + response, + _UPLOAD_CHECKSUM_MISMATCH_MESSAGE.format( + self._checksum_type.upper(), local_checksum, remote_checksum + ), + ) + + +def get_boundary(): + """Get a random boundary for a multipart request. + + Returns: + bytes: The boundary used to separate parts of a multipart request. + """ + random_int = random.randrange(sys.maxsize) + boundary = _BOUNDARY_FORMAT.format(random_int) + # NOTE: Neither % formatting nor .format() are available for byte strings + # in Python 3.4, so we must use unicode strings as templates. + return boundary.encode("utf-8") + + +def construct_multipart_request(data, metadata, content_type): + """Construct a multipart request body. + + Args: + data (bytes): The resource content (UTF-8 encoded as bytes) + to be uploaded. + metadata (Mapping[str, str]): The resource metadata, such as an + ACL list. + content_type (str): The content type of the resource, e.g. a JPEG + image has content type ``image/jpeg``. + + Returns: + Tuple[bytes, bytes]: The multipart request body and the boundary used + between each part. + """ + multipart_boundary = get_boundary() + json_bytes = json.dumps(metadata).encode("utf-8") + content_type = content_type.encode("utf-8") + # Combine the two parts into a multipart payload. + # NOTE: We'd prefer a bytes template but are restricted by Python 3.4. + boundary_sep = _MULTIPART_SEP + multipart_boundary + content = ( + boundary_sep + + _MULTIPART_BEGIN + + json_bytes + + _CRLF + + boundary_sep + + _CRLF + + b"content-type: " + + content_type + + _CRLF + + _CRLF + + data # Empty line between headers and body. + + _CRLF + + boundary_sep + + _MULTIPART_SEP + ) + + return content, multipart_boundary + + +def get_total_bytes(stream): + """Determine the total number of bytes in a stream. + + Args: + stream (IO[bytes]): The stream (i.e. file-like object). + + Returns: + int: The number of bytes. + """ + current_position = stream.tell() + # NOTE: ``.seek()`` **should** return the same value that ``.tell()`` + # returns, but in Python 2, ``file`` objects do not. + stream.seek(0, os.SEEK_END) + end_position = stream.tell() + # Go back to the initial position. + stream.seek(current_position) + + return end_position + + +def get_next_chunk(stream, chunk_size, total_bytes): + """Get a chunk from an I/O stream. + + The ``stream`` may have fewer bytes remaining than ``chunk_size`` + so it may not always be the case that + ``end_byte == start_byte + chunk_size - 1``. + + Args: + stream (IO[bytes]): The stream (i.e. file-like object). + chunk_size (int): The size of the chunk to be read from the ``stream``. + total_bytes (Optional[int]): The (expected) total number of bytes + in the ``stream``. + + Returns: + Tuple[int, bytes, str]: Triple of: + + * the start byte index + * the content in between the start and end bytes (inclusive) + * content range header for the chunk (slice) that has been read + + Raises: + ValueError: If ``total_bytes == 0`` but ``stream.read()`` yields + non-empty content. + ValueError: If there is no data left to consume. This corresponds + exactly to the case ``end_byte < start_byte``, which can only + occur if ``end_byte == start_byte - 1``. + """ + start_byte = stream.tell() + if total_bytes is not None and start_byte + chunk_size >= total_bytes > 0: + payload = stream.read(total_bytes - start_byte) + else: + payload = stream.read(chunk_size) + end_byte = stream.tell() - 1 + + num_bytes_read = len(payload) + if total_bytes is None: + if num_bytes_read < chunk_size: + # We now **KNOW** the total number of bytes. + total_bytes = end_byte + 1 + elif total_bytes == 0: + # NOTE: We also expect ``start_byte == 0`` here but don't check + # because ``_prepare_initiate_request()`` requires the + # stream to be at the beginning. + if num_bytes_read != 0: + raise ValueError( + "Stream specified as empty, but produced non-empty content." + ) + else: + if num_bytes_read == 0: + raise ValueError( + "Stream is already exhausted. There is no content remaining." + ) + + content_range = get_content_range(start_byte, end_byte, total_bytes) + return start_byte, payload, content_range + + +def get_content_range(start_byte, end_byte, total_bytes): + """Convert start, end and total into content range header. + + If ``total_bytes`` is not known, uses "bytes {start}-{end}/*". + If we are dealing with an empty range (i.e. ``end_byte < start_byte``) + then "bytes */{total}" is used. + + This function **ASSUMES** that if the size is not known, the caller will + not also pass an empty range. + + Args: + start_byte (int): The start (inclusive) of the byte range. + end_byte (int): The end (inclusive) of the byte range. + total_bytes (Optional[int]): The number of bytes in the byte + range (if known). + + Returns: + str: The content range header. + """ + if total_bytes is None: + return _RANGE_UNKNOWN_TEMPLATE.format(start_byte, end_byte) + elif end_byte < start_byte: + return _EMPTY_RANGE_TEMPLATE.format(total_bytes) + else: + return _CONTENT_RANGE_TEMPLATE.format(start_byte, end_byte, total_bytes) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/resumable_media/common.py b/loan-advisor-agent/.venv/Lib/site-packages/google/resumable_media/common.py new file mode 100644 index 0000000000000000000000000000000000000000..216ba04097a816f5080013ecb976be6394d42d4e --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/resumable_media/common.py @@ -0,0 +1,179 @@ +# Copyright 2017 Google Inc. +# +# Licensed 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. + +"""Common utilities for Google Media Downloads and Resumable Uploads. + +Includes custom exception types, useful constants and shared helpers. +""" + +import http.client + +_SLEEP_RETRY_ERROR_MSG = ( + "At most one of `max_cumulative_retry` and `max_retries` can be specified." +) + +UPLOAD_CHUNK_SIZE = 262144 # 256 * 1024 +"""int: Chunks in a resumable upload must come in multiples of 256 KB.""" + +PERMANENT_REDIRECT = http.client.PERMANENT_REDIRECT # type: ignore +"""int: Permanent redirect status code. + +.. note:: + This is a backward-compatibility alias. + +It is used by Google services to indicate some (but not all) of +a resumable upload has been completed. + +For more information, see `RFC 7238`_. + +.. _RFC 7238: https://tools.ietf.org/html/rfc7238 +""" + +TOO_MANY_REQUESTS = http.client.TOO_MANY_REQUESTS +"""int: Status code indicating rate-limiting. + +.. note:: + This is a backward-compatibility alias. + +For more information, see `RFC 6585`_. + +.. _RFC 6585: https://tools.ietf.org/html/rfc6585#section-4 +""" + +MAX_SLEEP = 64.0 +"""float: Maximum amount of time allowed between requests. + +Used during the retry process for sleep after a failed request. +Chosen since it is the power of two nearest to one minute. +""" + +MAX_CUMULATIVE_RETRY = 600.0 +"""float: Maximum total sleep time allowed during retry process. + +This is provided (10 minutes) as a default. When the cumulative sleep +exceeds this limit, no more retries will occur. +""" + +RETRYABLE = ( + http.client.TOO_MANY_REQUESTS, # 429 + http.client.REQUEST_TIMEOUT, # 408 + http.client.INTERNAL_SERVER_ERROR, # 500 + http.client.BAD_GATEWAY, # 502 + http.client.SERVICE_UNAVAILABLE, # 503 + http.client.GATEWAY_TIMEOUT, # 504 +) +"""iterable: HTTP status codes that indicate a retryable error. + +Connection errors are also retried, but are not listed as they are +exceptions, not status codes. +""" + + +class InvalidResponse(Exception): + """Error class for responses which are not in the correct state. + + Args: + response (object): The HTTP response which caused the failure. + args (tuple): The positional arguments typically passed to an + exception class. + """ + + def __init__(self, response, *args): + super(InvalidResponse, self).__init__(*args) + self.response = response + """object: The HTTP response object that caused the failure.""" + + +class DataCorruption(Exception): + """Error class for corrupt media transfers. + + Args: + response (object): The HTTP response which caused the failure. + args (tuple): The positional arguments typically passed to an + exception class. + """ + + def __init__(self, response, *args): + super(DataCorruption, self).__init__(*args) + self.response = response + """object: The HTTP response object that caused the failure.""" + + +class RetryStrategy(object): + """Configuration class for retrying failed requests. + + At most one of ``max_cumulative_retry`` and ``max_retries`` can be + specified (they are both caps on the total number of retries). If + neither are specified, then ``max_cumulative_retry`` is set as + :data:`MAX_CUMULATIVE_RETRY`. + + Args: + max_sleep (Optional[float]): The maximum amount of time to sleep after + a failed request. Default is :attr:`MAX_SLEEP`. + max_cumulative_retry (Optional[float]): The maximum **total** amount of + time to sleep during retry process. + max_retries (Optional[int]): The number of retries to attempt. + initial_delay (Optional[float]): The initial delay. Default 1.0 second. + muiltiplier (Optional[float]): Exponent of the backoff. Default is 2.0. + + Attributes: + max_sleep (float): Maximum amount of time allowed between requests. + max_cumulative_retry (Optional[float]): Maximum total sleep time + allowed during retry process. + max_retries (Optional[int]): The number retries to attempt. + initial_delay (Optional[float]): The initial delay. Default 1.0 second. + muiltiplier (Optional[float]): Exponent of the backoff. Default is 2.0. + + Raises: + ValueError: If both of ``max_cumulative_retry`` and ``max_retries`` + are passed. + """ + + def __init__( + self, + max_sleep=MAX_SLEEP, + max_cumulative_retry=None, + max_retries=None, + initial_delay=1.0, + multiplier=2.0, + ): + if max_cumulative_retry is not None and max_retries is not None: + raise ValueError(_SLEEP_RETRY_ERROR_MSG) + if max_cumulative_retry is None and max_retries is None: + max_cumulative_retry = MAX_CUMULATIVE_RETRY + + self.max_sleep = max_sleep + self.max_cumulative_retry = max_cumulative_retry + self.max_retries = max_retries + self.initial_delay = initial_delay + self.multiplier = multiplier + + def retry_allowed(self, total_sleep, num_retries): + """Check if another retry is allowed. + + Args: + total_sleep (float): With another retry, the amount of sleep that + will be accumulated by the caller. + num_retries (int): With another retry, the number of retries that + will be attempted by the caller. + + Returns: + bool: Indicating if another retry is allowed (depending on either + the cumulative sleep allowed or the maximum number of retries + allowed. + """ + if self.max_cumulative_retry is None: + return num_retries <= self.max_retries + else: + return total_sleep <= self.max_cumulative_retry diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/resumable_media/py.typed b/loan-advisor-agent/.venv/Lib/site-packages/google/resumable_media/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..7705b065b00d1990fff0bfa83bc916b3f239a6f2 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/resumable_media/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-resumable_media package uses inline types. diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/resumable_media/requests/__init__.py b/loan-advisor-agent/.venv/Lib/site-packages/google/resumable_media/requests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c46a02c4543c86b55769b28c133f267162ca06be --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/resumable_media/requests/__init__.py @@ -0,0 +1,686 @@ +# Copyright 2017 Google Inc. +# +# Licensed 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. + +"""``requests`` utilities for Google Media Downloads and Resumable Uploads. + +This sub-package assumes callers will use the `requests`_ library +as transport and `google-auth`_ for sending authenticated HTTP traffic +with ``requests``. + +.. _requests: http://docs.python-requests.org/ +.. _google-auth: https://google-auth.readthedocs.io/ + +==================== +Authorized Transport +==================== + +To use ``google-auth`` and ``requests`` to create an authorized transport +that has read-only access to Google Cloud Storage (GCS): + +.. testsetup:: get-credentials + + import google.auth + import google.auth.credentials as creds_mod + import mock + + def mock_default(scopes=None): + credentials = mock.Mock(spec=creds_mod.Credentials) + return credentials, 'mock-project' + + # Patch the ``default`` function on the module. + original_default = google.auth.default + google.auth.default = mock_default + +.. doctest:: get-credentials + + >>> import google.auth + >>> import google.auth.transport.requests as tr_requests + >>> + >>> ro_scope = 'https://www.googleapis.com/auth/devstorage.read_only' + >>> credentials, _ = google.auth.default(scopes=(ro_scope,)) + >>> transport = tr_requests.AuthorizedSession(credentials) + >>> transport + + +.. testcleanup:: get-credentials + + # Put back the correct ``default`` function on the module. + google.auth.default = original_default + +================ +Simple Downloads +================ + +To download an object from Google Cloud Storage, construct the media URL +for the GCS object and download it with an authorized transport that has +access to the resource: + +.. testsetup:: basic-download + + import mock + import requests + import http.client + + bucket = 'bucket-foo' + blob_name = 'file.txt' + + fake_response = requests.Response() + fake_response.status_code = int(http.client.OK) + fake_response.headers['Content-Length'] = '1364156' + fake_content = mock.MagicMock(spec=['__len__']) + fake_content.__len__.return_value = 1364156 + fake_response._content = fake_content + + get_method = mock.Mock(return_value=fake_response, spec=[]) + transport = mock.Mock(request=get_method, spec=['request']) + +.. doctest:: basic-download + + >>> from google.resumable_media.requests import Download + >>> + >>> url_template = ( + ... 'https://www.googleapis.com/download/storage/v1/b/' + ... '{bucket}/o/{blob_name}?alt=media') + >>> media_url = url_template.format( + ... bucket=bucket, blob_name=blob_name) + >>> + >>> download = Download(media_url) + >>> response = download.consume(transport) + >>> download.finished + True + >>> response + + >>> response.headers['Content-Length'] + '1364156' + >>> len(response.content) + 1364156 + +To download only a portion of the bytes in the object, +specify ``start`` and ``end`` byte positions (both optional): + +.. testsetup:: basic-download-with-slice + + import mock + import requests + import http.client + + from google.resumable_media.requests import Download + + media_url = 'http://test.invalid' + start = 4096 + end = 8191 + slice_size = end - start + 1 + + fake_response = requests.Response() + fake_response.status_code = int(http.client.PARTIAL_CONTENT) + fake_response.headers['Content-Length'] = '{:d}'.format(slice_size) + content_range = 'bytes {:d}-{:d}/1364156'.format(start, end) + fake_response.headers['Content-Range'] = content_range + fake_content = mock.MagicMock(spec=['__len__']) + fake_content.__len__.return_value = slice_size + fake_response._content = fake_content + + get_method = mock.Mock(return_value=fake_response, spec=[]) + transport = mock.Mock(request=get_method, spec=['request']) + +.. doctest:: basic-download-with-slice + + >>> download = Download(media_url, start=4096, end=8191) + >>> response = download.consume(transport) + >>> download.finished + True + >>> response + + >>> response.headers['Content-Length'] + '4096' + >>> response.headers['Content-Range'] + 'bytes 4096-8191/1364156' + >>> len(response.content) + 4096 + +================= +Chunked Downloads +================= + +For very large objects or objects of unknown size, it may make more sense +to download the object in chunks rather than all at once. This can be done +to avoid dropped connections with a poor internet connection or can allow +multiple chunks to be downloaded in parallel to speed up the total +download. + +A :class:`.ChunkedDownload` uses the same media URL and authorized +transport that a basic :class:`.Download` would use, but also +requires a chunk size and a write-able byte ``stream``. The chunk size is used +to determine how much of the resouce to consume with each request and the +stream is to allow the resource to be written out (e.g. to disk) without +having to fit in memory all at once. + +.. testsetup:: chunked-download + + import io + + import mock + import requests + import http.client + + media_url = 'http://test.invalid' + + fifty_mb = 50 * 1024 * 1024 + one_gb = 1024 * 1024 * 1024 + fake_response = requests.Response() + fake_response.status_code = int(http.client.PARTIAL_CONTENT) + fake_response.headers['Content-Length'] = '{:d}'.format(fifty_mb) + content_range = 'bytes 0-{:d}/{:d}'.format(fifty_mb - 1, one_gb) + fake_response.headers['Content-Range'] = content_range + fake_content_begin = b'The beginning of the chunk...' + fake_content = fake_content_begin + b'1' * (fifty_mb - 29) + fake_response._content = fake_content + + get_method = mock.Mock(return_value=fake_response, spec=[]) + transport = mock.Mock(request=get_method, spec=['request']) + +.. doctest:: chunked-download + + >>> from google.resumable_media.requests import ChunkedDownload + >>> + >>> chunk_size = 50 * 1024 * 1024 # 50MB + >>> stream = io.BytesIO() + >>> download = ChunkedDownload( + ... media_url, chunk_size, stream) + >>> # Check the state of the download before starting. + >>> download.bytes_downloaded + 0 + >>> download.total_bytes is None + True + >>> response = download.consume_next_chunk(transport) + >>> # Check the state of the download after consuming one chunk. + >>> download.finished + False + >>> download.bytes_downloaded # chunk_size + 52428800 + >>> download.total_bytes # 1GB + 1073741824 + >>> response + + >>> response.headers['Content-Length'] + '52428800' + >>> response.headers['Content-Range'] + 'bytes 0-52428799/1073741824' + >>> len(response.content) == chunk_size + True + >>> stream.seek(0) + 0 + >>> stream.read(29) + b'The beginning of the chunk...' + +The download will change it's ``finished`` status to :data:`True` +once the final chunk is consumed. In some cases, the final chunk may +not be the same size as the other chunks: + +.. testsetup:: chunked-download-end + + import mock + import requests + import http.client + + from google.resumable_media.requests import ChunkedDownload + + media_url = 'http://test.invalid' + + fifty_mb = 50 * 1024 * 1024 + one_gb = 1024 * 1024 * 1024 + stream = mock.Mock(spec=['write']) + download = ChunkedDownload(media_url, fifty_mb, stream) + download._bytes_downloaded = 20 * fifty_mb + download._total_bytes = one_gb + + fake_response = requests.Response() + fake_response.status_code = int(http.client.PARTIAL_CONTENT) + slice_size = one_gb - 20 * fifty_mb + fake_response.headers['Content-Length'] = '{:d}'.format(slice_size) + content_range = 'bytes {:d}-{:d}/{:d}'.format( + 20 * fifty_mb, one_gb - 1, one_gb) + fake_response.headers['Content-Range'] = content_range + fake_content = mock.MagicMock(spec=['__len__']) + fake_content.__len__.return_value = slice_size + fake_response._content = fake_content + + get_method = mock.Mock(return_value=fake_response, spec=[]) + transport = mock.Mock(request=get_method, spec=['request']) + +.. doctest:: chunked-download-end + + >>> # The state of the download in progress. + >>> download.finished + False + >>> download.bytes_downloaded # 20 chunks at 50MB + 1048576000 + >>> download.total_bytes # 1GB + 1073741824 + >>> response = download.consume_next_chunk(transport) + >>> # The state of the download after consuming the final chunk. + >>> download.finished + True + >>> download.bytes_downloaded == download.total_bytes + True + >>> response + + >>> response.headers['Content-Length'] + '25165824' + >>> response.headers['Content-Range'] + 'bytes 1048576000-1073741823/1073741824' + >>> len(response.content) < download.chunk_size + True + +In addition, a :class:`.ChunkedDownload` can also take optional +``start`` and ``end`` byte positions. + +Usually, no checksum is returned with a chunked download. Even if one is returned, +it is not validated. If you need to validate the checksum, you can do so +by buffering the chunks and validating the checksum against the completed download. + +============== +Simple Uploads +============== + +Among the three supported upload classes, the simplest is +:class:`.SimpleUpload`. A simple upload should be used when the resource +being uploaded is small and when there is no metadata (other than the name) +associated with the resource. + +.. testsetup:: simple-upload + + import json + + import mock + import requests + import http.client + + bucket = 'some-bucket' + blob_name = 'file.txt' + + fake_response = requests.Response() + fake_response.status_code = int(http.client.OK) + payload = { + 'bucket': bucket, + 'contentType': 'text/plain', + 'md5Hash': 'M0XLEsX9/sMdiI+4pB4CAQ==', + 'name': blob_name, + 'size': '27', + } + fake_response._content = json.dumps(payload).encode('utf-8') + + post_method = mock.Mock(return_value=fake_response, spec=[]) + transport = mock.Mock(request=post_method, spec=['request']) + +.. doctest:: simple-upload + :options: +NORMALIZE_WHITESPACE + + >>> from google.resumable_media.requests import SimpleUpload + >>> + >>> url_template = ( + ... 'https://www.googleapis.com/upload/storage/v1/b/{bucket}/o?' + ... 'uploadType=media&' + ... 'name={blob_name}') + >>> upload_url = url_template.format( + ... bucket=bucket, blob_name=blob_name) + >>> + >>> upload = SimpleUpload(upload_url) + >>> data = b'Some not too large content.' + >>> content_type = 'text/plain' + >>> response = upload.transmit(transport, data, content_type) + >>> upload.finished + True + >>> response + + >>> json_response = response.json() + >>> json_response['bucket'] == bucket + True + >>> json_response['name'] == blob_name + True + >>> json_response['contentType'] == content_type + True + >>> json_response['md5Hash'] + 'M0XLEsX9/sMdiI+4pB4CAQ==' + >>> int(json_response['size']) == len(data) + True + +In the rare case that an upload fails, an :exc:`.InvalidResponse` +will be raised: + +.. testsetup:: simple-upload-fail + + import time + + import mock + import requests + import http.client + + from google import resumable_media + from google.resumable_media import _helpers + from google.resumable_media.requests import SimpleUpload as constructor + + upload_url = 'http://test.invalid' + data = b'Some not too large content.' + content_type = 'text/plain' + + fake_response = requests.Response() + fake_response.status_code = int(http.client.SERVICE_UNAVAILABLE) + + post_method = mock.Mock(return_value=fake_response, spec=[]) + transport = mock.Mock(request=post_method, spec=['request']) + + time_sleep = time.sleep + def dont_sleep(seconds): + raise RuntimeError('No sleep', seconds) + + def SimpleUpload(*args, **kwargs): + upload = constructor(*args, **kwargs) + # Mock the cumulative sleep to avoid retries (and `time.sleep()`). + upload._retry_strategy = resumable_media.RetryStrategy( + max_cumulative_retry=-1.0) + return upload + + time.sleep = dont_sleep + +.. doctest:: simple-upload-fail + :options: +NORMALIZE_WHITESPACE + + >>> upload = SimpleUpload(upload_url) + >>> error = None + >>> try: + ... upload.transmit(transport, data, content_type) + ... except resumable_media.InvalidResponse as caught_exc: + ... error = caught_exc + ... + >>> error + InvalidResponse('Request failed with status code', 503, + 'Expected one of', ) + >>> error.response + + >>> + >>> upload.finished + True + +.. testcleanup:: simple-upload-fail + + # Put back the correct ``sleep`` function on the ``time`` module. + time.sleep = time_sleep + +Even in the case of failure, we see that the upload is +:attr:`~.SimpleUpload.finished`, i.e. it cannot be re-used. + +================= +Multipart Uploads +================= + +After the simple upload, the :class:`.MultipartUpload` can be used to +achieve essentially the same task. However, a multipart upload allows some +metadata about the resource to be sent along as well. (This is the "multi": +we send a first part with the metadata and a second part with the actual +bytes in the resource.) + +Usage is similar to the simple upload, but :meth:`~.MultipartUpload.transmit` +accepts an extra required argument: ``metadata``. + +.. testsetup:: multipart-upload + + import json + + import mock + import requests + import http.client + + bucket = 'some-bucket' + blob_name = 'file.txt' + data = b'Some not too large content.' + content_type = 'text/plain' + + fake_response = requests.Response() + fake_response.status_code = int(http.client.OK) + payload = { + 'bucket': bucket, + 'name': blob_name, + 'metadata': {'color': 'grurple'}, + } + fake_response._content = json.dumps(payload).encode('utf-8') + + post_method = mock.Mock(return_value=fake_response, spec=[]) + transport = mock.Mock(request=post_method, spec=['request']) + +.. doctest:: multipart-upload + + >>> from google.resumable_media.requests import MultipartUpload + >>> + >>> url_template = ( + ... 'https://www.googleapis.com/upload/storage/v1/b/{bucket}/o?' + ... 'uploadType=multipart') + >>> upload_url = url_template.format(bucket=bucket) + >>> + >>> upload = MultipartUpload(upload_url) + >>> metadata = { + ... 'name': blob_name, + ... 'metadata': { + ... 'color': 'grurple', + ... }, + ... } + >>> response = upload.transmit(transport, data, metadata, content_type) + >>> upload.finished + True + >>> response + + >>> json_response = response.json() + >>> json_response['bucket'] == bucket + True + >>> json_response['name'] == blob_name + True + >>> json_response['metadata'] == metadata['metadata'] + True + +As with the simple upload, in the case of failure an :exc:`.InvalidResponse` +is raised, enclosing the :attr:`~.InvalidResponse.response` that caused +the failure and the ``upload`` object cannot be re-used after a failure. + +================= +Resumable Uploads +================= + +A :class:`.ResumableUpload` deviates from the other two upload classes: +it transmits a resource over the course of multiple requests. This +is intended to be used in cases where: + +* the size of the resource is not known (i.e. it is generated on the fly) +* requests must be short-lived +* the client has request **size** limitations +* the resource is too large to fit into memory + +In general, a resource should be sent in a **single** request to avoid +latency and reduce QPS. See `GCS best practices`_ for more things to +consider when using a resumable upload. + +.. _GCS best practices: https://cloud.google.com/storage/docs/\ + best-practices#uploading + +After creating a :class:`.ResumableUpload` instance, a +**resumable upload session** must be initiated to let the server know that +a series of chunked upload requests will be coming and to obtain an +``upload_id`` for the session. In contrast to the other two upload classes, +:meth:`~.ResumableUpload.initiate` takes a byte ``stream`` as input rather +than raw bytes as ``data``. This can be a file object, a :class:`~io.BytesIO` +object or any other stream implementing the same interface. + +.. testsetup:: resumable-initiate + + import io + + import mock + import requests + import http.client + + bucket = 'some-bucket' + blob_name = 'file.txt' + data = b'Some resumable bytes.' + content_type = 'text/plain' + + fake_response = requests.Response() + fake_response.status_code = int(http.client.OK) + fake_response._content = b'' + upload_id = 'ABCdef189XY_super_serious' + resumable_url_template = ( + 'https://www.googleapis.com/upload/storage/v1/b/{bucket}' + '/o?uploadType=resumable&upload_id={upload_id}') + resumable_url = resumable_url_template.format( + bucket=bucket, upload_id=upload_id) + fake_response.headers['location'] = resumable_url + fake_response.headers['x-guploader-uploadid'] = upload_id + + post_method = mock.Mock(return_value=fake_response, spec=[]) + transport = mock.Mock(request=post_method, spec=['request']) + +.. doctest:: resumable-initiate + + >>> from google.resumable_media.requests import ResumableUpload + >>> + >>> url_template = ( + ... 'https://www.googleapis.com/upload/storage/v1/b/{bucket}/o?' + ... 'uploadType=resumable') + >>> upload_url = url_template.format(bucket=bucket) + >>> + >>> chunk_size = 1024 * 1024 # 1MB + >>> upload = ResumableUpload(upload_url, chunk_size) + >>> stream = io.BytesIO(data) + >>> # The upload doesn't know how "big" it is until seeing a stream. + >>> upload.total_bytes is None + True + >>> metadata = {'name': blob_name} + >>> response = upload.initiate(transport, stream, metadata, content_type) + >>> response + + >>> upload.resumable_url == response.headers['Location'] + True + >>> upload.total_bytes == len(data) + True + >>> upload_id = response.headers['X-GUploader-UploadID'] + >>> upload_id + 'ABCdef189XY_super_serious' + >>> upload.resumable_url == upload_url + '&upload_id=' + upload_id + True + +Once a :class:`.ResumableUpload` has been initiated, the resource is +transmitted in chunks until completion: + +.. testsetup:: resumable-transmit + + import io + import json + + import mock + import requests + import http.client + + from google import resumable_media + import google.resumable_media.requests.upload as upload_mod + + data = b'01234567891' + stream = io.BytesIO(data) + # Create an "already initiated" upload. + upload_url = 'http://test.invalid' + chunk_size = 256 * 1024 # 256KB + upload = upload_mod.ResumableUpload(upload_url, chunk_size) + upload._resumable_url = 'http://test.invalid?upload_id=mocked' + upload._stream = stream + upload._content_type = 'text/plain' + upload._total_bytes = len(data) + + # After-the-fact update the chunk size so that len(data) + # is split into three. + upload._chunk_size = 4 + # Make three fake responses. + fake_response0 = requests.Response() + fake_response0.status_code = http.client.PERMANENT_REDIRECT + fake_response0.headers['range'] = 'bytes=0-3' + + fake_response1 = requests.Response() + fake_response1.status_code = http.client.PERMANENT_REDIRECT + fake_response1.headers['range'] = 'bytes=0-7' + + fake_response2 = requests.Response() + fake_response2.status_code = int(http.client.OK) + bucket = 'some-bucket' + blob_name = 'file.txt' + payload = { + 'bucket': bucket, + 'name': blob_name, + 'size': '{:d}'.format(len(data)), + } + fake_response2._content = json.dumps(payload).encode('utf-8') + + # Use the fake responses to mock a transport. + responses = [fake_response0, fake_response1, fake_response2] + put_method = mock.Mock(side_effect=responses, spec=[]) + transport = mock.Mock(request=put_method, spec=['request']) + +.. doctest:: resumable-transmit + + >>> response0 = upload.transmit_next_chunk(transport) + >>> response0 + + >>> upload.finished + False + >>> upload.bytes_uploaded == upload.chunk_size + True + >>> + >>> response1 = upload.transmit_next_chunk(transport) + >>> response1 + + >>> upload.finished + False + >>> upload.bytes_uploaded == 2 * upload.chunk_size + True + >>> + >>> response2 = upload.transmit_next_chunk(transport) + >>> response2 + + >>> upload.finished + True + >>> upload.bytes_uploaded == upload.total_bytes + True + >>> json_response = response2.json() + >>> json_response['bucket'] == bucket + True + >>> json_response['name'] == blob_name + True +""" + +from google.resumable_media.requests.download import ChunkedDownload +from google.resumable_media.requests.download import Download +from google.resumable_media.requests.upload import MultipartUpload +from google.resumable_media.requests.download import RawChunkedDownload +from google.resumable_media.requests.download import RawDownload +from google.resumable_media.requests.upload import ResumableUpload +from google.resumable_media.requests.upload import SimpleUpload +from google.resumable_media.requests.upload import XMLMPUContainer +from google.resumable_media.requests.upload import XMLMPUPart + +__all__ = [ + "ChunkedDownload", + "Download", + "MultipartUpload", + "RawChunkedDownload", + "RawDownload", + "ResumableUpload", + "SimpleUpload", + "XMLMPUContainer", + "XMLMPUPart", +] diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/resumable_media/requests/_request_helpers.py b/loan-advisor-agent/.venv/Lib/site-packages/google/resumable_media/requests/_request_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..051f0bae075d1b3301a6faefa69547de54a55cd1 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/resumable_media/requests/_request_helpers.py @@ -0,0 +1,180 @@ +# Copyright 2017 Google Inc. +# +# Licensed 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. + +"""Shared utilities used by both downloads and uploads. + +This utilities are explicitly catered to ``requests``-like transports. +""" + +import http.client +import requests.exceptions +import urllib3.exceptions # type: ignore + +import time + +from google.resumable_media import common +from google.resumable_media import _helpers + +_DEFAULT_RETRY_STRATEGY = common.RetryStrategy() +_SINGLE_GET_CHUNK_SIZE = 8192 +# The number of seconds to wait to establish a connection +# (connect() call on socket). Avoid setting this to a multiple of 3 to not +# Align with TCP Retransmission timing. (typically 2.5-3s) +_DEFAULT_CONNECT_TIMEOUT = 61 +# The number of seconds to wait between bytes sent from the server. +_DEFAULT_READ_TIMEOUT = 60 + +_CONNECTION_ERROR_CLASSES = ( + http.client.BadStatusLine, + http.client.IncompleteRead, + http.client.ResponseNotReady, + requests.exceptions.ConnectionError, + requests.exceptions.ChunkedEncodingError, + requests.exceptions.Timeout, + urllib3.exceptions.PoolError, + urllib3.exceptions.ProtocolError, + urllib3.exceptions.SSLError, + urllib3.exceptions.TimeoutError, + ConnectionError, # Python 3.x only, superclass of ConnectionResetError. +) + + +class RequestsMixin(object): + """Mix-in class implementing ``requests``-specific behavior. + + These are methods that are more general purpose, with implementations + specific to the types defined in ``requests``. + """ + + @staticmethod + def _get_status_code(response): + """Access the status code from an HTTP response. + + Args: + response (~requests.Response): The HTTP response object. + + Returns: + int: The status code. + """ + return response.status_code + + @staticmethod + def _get_headers(response): + """Access the headers from an HTTP response. + + Args: + response (~requests.Response): The HTTP response object. + + Returns: + ~requests.structures.CaseInsensitiveDict: The header mapping (keys + are case-insensitive). + """ + return response.headers + + @staticmethod + def _get_body(response): + """Access the response body from an HTTP response. + + Args: + response (~requests.Response): The HTTP response object. + + Returns: + bytes: The body of the ``response``. + """ + return response.content + + +class RawRequestsMixin(RequestsMixin): + @staticmethod + def _get_body(response): + """Access the response body from an HTTP response. + + Args: + response (~requests.Response): The HTTP response object. + + Returns: + bytes: The body of the ``response``. + """ + if response._content is False: + response._content = b"".join( + response.raw.stream(_SINGLE_GET_CHUNK_SIZE, decode_content=False) + ) + response._content_consumed = True + return response._content + + +def wait_and_retry(func, get_status_code, retry_strategy): + """Attempts to retry a call to ``func`` until success. + + Expects ``func`` to return an HTTP response and uses ``get_status_code`` + to check if the response is retry-able. + + ``func`` is expected to raise a failure status code as a + common.InvalidResponse, at which point this method will check the code + against the common.RETRIABLE list of retriable status codes. + + Will retry until :meth:`~.RetryStrategy.retry_allowed` (on the current + ``retry_strategy``) returns :data:`False`. Uses + :func:`_helpers.calculate_retry_wait` to double the wait time (with jitter) + after each attempt. + + Args: + func (Callable): A callable that takes no arguments and produces + an HTTP response which will be checked as retry-able. + get_status_code (Callable[Any, int]): Helper to get a status code + from a response. + retry_strategy (~google.resumable_media.common.RetryStrategy): The + strategy to use if the request fails and must be retried. + + Returns: + object: The return value of ``func``. + """ + total_sleep = 0.0 + num_retries = 0 + # base_wait will be multiplied by the multiplier on the first retry. + base_wait = float(retry_strategy.initial_delay) / retry_strategy.multiplier + + # Set the retriable_exception_type if possible. We expect requests to be + # present here and the transport to be using requests.exceptions errors, + # but due to loose coupling with the transport layer we can't guarantee it. + + while True: # return on success or when retries exhausted. + error = None + try: + response = func() + except _CONNECTION_ERROR_CLASSES as e: + error = e # Fall through to retry, if there are retries left. + except common.InvalidResponse as e: + # An InvalidResponse is only retriable if its status code matches. + # The `process_response()` method on a Download or Upload method + # will convert the status code into an exception. + if get_status_code(e.response) in common.RETRYABLE: + error = e # Fall through to retry, if there are retries left. + else: + raise # If the status code is not retriable, raise w/o retry. + else: + return response + + base_wait, wait_time = _helpers.calculate_retry_wait( + base_wait, retry_strategy.max_sleep, retry_strategy.multiplier + ) + num_retries += 1 + total_sleep += wait_time + + # Check if (another) retry is allowed. If retries are exhausted and + # no acceptable response was received, raise the retriable error. + if not retry_strategy.retry_allowed(total_sleep, num_retries): + raise error + + time.sleep(wait_time) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/resumable_media/requests/download.py b/loan-advisor-agent/.venv/Lib/site-packages/google/resumable_media/requests/download.py new file mode 100644 index 0000000000000000000000000000000000000000..be017f549c27721b91c914c379dada2342e3ba10 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/resumable_media/requests/download.py @@ -0,0 +1,739 @@ +# Copyright 2017 Google Inc. +# +# Licensed 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. + +"""Support for downloading media from Google APIs.""" + +import urllib3.response # type: ignore +import http + +from google.resumable_media import _download +from google.resumable_media import common +from google.resumable_media import _helpers +from google.resumable_media.requests import _request_helpers + + +_CHECKSUM_MISMATCH = """\ +Checksum mismatch while downloading: + + {} + +The X-Goog-Hash header indicated an {checksum_type} checksum of: + + {} + +but the actual {checksum_type} checksum of the downloaded contents was: + + {} +""" + +_STREAM_SEEK_ERROR = """\ +Incomplete download for: +{} +Error writing to stream while handling a gzip-compressed file download. +Please restart the download. +""" + +_RESPONSE_HEADERS_INFO = """\ + +The X-Goog-Stored-Content-Length is {}. The X-Goog-Stored-Content-Encoding is {}. + +The download request read {} bytes of data. +If the download was incomplete, please check the network connection and restart the download. +""" + + +class Download(_request_helpers.RequestsMixin, _download.Download): + """Helper to manage downloading a resource from a Google API. + + "Slices" of the resource can be retrieved by specifying a range + with ``start`` and / or ``end``. However, in typical usage, neither + ``start`` nor ``end`` is expected to be provided. + + Args: + media_url (str): The URL containing the media to be downloaded. + stream (IO[bytes]): A write-able stream (i.e. file-like object) that + the downloaded resource can be written to. + start (int): The first byte in a range to be downloaded. If not + provided, but ``end`` is provided, will download from the + beginning to ``end`` of the media. + end (int): The last byte in a range to be downloaded. If not + provided, but ``start`` is provided, will download from the + ``start`` to the end of the media. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with the request, e.g. headers for encrypted data. + checksum Optional([str]): The type of checksum to compute to verify + the integrity of the object. The response headers must contain + a checksum of the requested type. If the headers lack an + appropriate checksum (for instance in the case of transcoded or + ranged downloads where the remote service does not know the + correct checksum) an INFO-level log will be emitted. Supported + values are "md5", "crc32c" and None. The default is "md5". + + Attributes: + media_url (str): The URL containing the media to be downloaded. + start (Optional[int]): The first byte in a range to be downloaded. + end (Optional[int]): The last byte in a range to be downloaded. + """ + + def _write_to_stream(self, response): + """Write response body to a write-able stream. + + .. note: + + This method assumes that the ``_stream`` attribute is set on the + current download. + + Args: + response (~requests.Response): The HTTP response object. + + Raises: + ~google.resumable_media.common.DataCorruption: If the download's + checksum doesn't agree with server-computed checksum. + """ + + # Retrieve the expected checksum only once for the download request, + # then compute and validate the checksum when the full download completes. + # Retried requests are range requests, and there's no way to detect + # data corruption for that byte range alone. + if self._expected_checksum is None and self._checksum_object is None: + # `_get_expected_checksum()` may return None even if a checksum was + # requested, in which case it will emit an info log _MISSING_CHECKSUM. + # If an invalid checksum type is specified, this will raise ValueError. + expected_checksum, checksum_object = _helpers._get_expected_checksum( + response, self._get_headers, self.media_url, checksum_type=self.checksum + ) + self._expected_checksum = expected_checksum + self._checksum_object = checksum_object + else: + expected_checksum = self._expected_checksum + checksum_object = self._checksum_object + + with response: + # NOTE: In order to handle compressed streams gracefully, we try + # to insert our checksum object into the decompression stream. If + # the stream is indeed compressed, this will delegate the checksum + # object to the decoder and return a _DoNothingHash here. + local_checksum_object = _add_decoder(response.raw, checksum_object) + body_iter = response.iter_content( + chunk_size=_request_helpers._SINGLE_GET_CHUNK_SIZE, decode_unicode=False + ) + for chunk in body_iter: + self._stream.write(chunk) + self._bytes_downloaded += len(chunk) + local_checksum_object.update(chunk) + + # Don't validate the checksum for partial responses. + if ( + expected_checksum is not None + and response.status_code != http.client.PARTIAL_CONTENT + ): + actual_checksum = _helpers.prepare_checksum_digest(checksum_object.digest()) + + if actual_checksum != expected_checksum: + headers = self._get_headers(response) + x_goog_encoding = headers.get("x-goog-stored-content-encoding") + x_goog_length = headers.get("x-goog-stored-content-length") + content_length_msg = _RESPONSE_HEADERS_INFO.format( + x_goog_length, x_goog_encoding, self._bytes_downloaded + ) + if ( + x_goog_length + and self._bytes_downloaded < int(x_goog_length) + and x_goog_encoding != "gzip" + ): + # The library will attempt to trigger a retry by raising a ConnectionError, if + # (a) bytes_downloaded is less than response header x-goog-stored-content-length, and + # (b) the object is not gzip-compressed when stored in Cloud Storage. + raise ConnectionError(content_length_msg) + else: + msg = _CHECKSUM_MISMATCH.format( + self.media_url, + expected_checksum, + actual_checksum, + checksum_type=self.checksum.upper(), + ) + msg += content_length_msg + raise common.DataCorruption(response, msg) + + def consume( + self, + transport, + timeout=( + _request_helpers._DEFAULT_CONNECT_TIMEOUT, + _request_helpers._DEFAULT_READ_TIMEOUT, + ), + ): + """Consume the resource to be downloaded. + + If a ``stream`` is attached to this download, then the downloaded + resource will be written to the stream. + + Args: + transport (~requests.Session): A ``requests`` object which can + make authenticated requests. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Returns: + ~requests.Response: The HTTP response returned by ``transport``. + + Raises: + ~google.resumable_media.common.DataCorruption: If the download's + checksum doesn't agree with server-computed checksum. + ValueError: If the current :class:`Download` has already + finished. + """ + method, _, payload, headers = self._prepare_request() + # NOTE: We assume "payload is None" but pass it along anyway. + request_kwargs = { + "data": payload, + "headers": headers, + "timeout": timeout, + } + if self._stream is not None: + request_kwargs["stream"] = True + + # Assign object generation if generation is specified in the media url. + if self._object_generation is None: + self._object_generation = _helpers._get_generation_from_url(self.media_url) + + # Wrap the request business logic in a function to be retried. + def retriable_request(): + url = self.media_url + + # To restart an interrupted download, read from the offset of last byte + # received using a range request, and set object generation query param. + if self._bytes_downloaded > 0: + _download.add_bytes_range( + (self.start or 0) + self._bytes_downloaded, self.end, self._headers + ) + request_kwargs["headers"] = self._headers + + # Set object generation query param to ensure the same object content is requested. + if ( + self._object_generation is not None + and _helpers._get_generation_from_url(self.media_url) is None + ): + query_param = {"generation": self._object_generation} + url = _helpers.add_query_parameters(self.media_url, query_param) + + result = transport.request(method, url, **request_kwargs) + + # If a generation hasn't been specified, and this is the first response we get, let's record the + # generation. In future requests we'll specify the generation query param to avoid data races. + if self._object_generation is None: + self._object_generation = _helpers._parse_generation_header( + result, self._get_headers + ) + + self._process_response(result) + + # With decompressive transcoding, GCS serves back the whole file regardless of the range request, + # thus we reset the stream position to the start of the stream. + # See: https://cloud.google.com/storage/docs/transcoding#range + if self._stream is not None: + if _helpers._is_decompressive_transcoding(result, self._get_headers): + try: + self._stream.seek(0) + except Exception as exc: + msg = _STREAM_SEEK_ERROR.format(url) + raise Exception(msg) from exc + self._bytes_downloaded = 0 + + self._write_to_stream(result) + + return result + + return _request_helpers.wait_and_retry( + retriable_request, self._get_status_code, self._retry_strategy + ) + + +class RawDownload(_request_helpers.RawRequestsMixin, _download.Download): + """Helper to manage downloading a raw resource from a Google API. + + "Slices" of the resource can be retrieved by specifying a range + with ``start`` and / or ``end``. However, in typical usage, neither + ``start`` nor ``end`` is expected to be provided. + + Args: + media_url (str): The URL containing the media to be downloaded. + stream (IO[bytes]): A write-able stream (i.e. file-like object) that + the downloaded resource can be written to. + start (int): The first byte in a range to be downloaded. If not + provided, but ``end`` is provided, will download from the + beginning to ``end`` of the media. + end (int): The last byte in a range to be downloaded. If not + provided, but ``start`` is provided, will download from the + ``start`` to the end of the media. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with the request, e.g. headers for encrypted data. + checksum Optional([str]): The type of checksum to compute to verify + the integrity of the object. The response headers must contain + a checksum of the requested type. If the headers lack an + appropriate checksum (for instance in the case of transcoded or + ranged downloads where the remote service does not know the + correct checksum) an INFO-level log will be emitted. Supported + values are "md5", "crc32c" and None. The default is "md5". + Attributes: + media_url (str): The URL containing the media to be downloaded. + start (Optional[int]): The first byte in a range to be downloaded. + end (Optional[int]): The last byte in a range to be downloaded. + """ + + def _write_to_stream(self, response): + """Write response body to a write-able stream. + + .. note: + + This method assumes that the ``_stream`` attribute is set on the + current download. + + Args: + response (~requests.Response): The HTTP response object. + + Raises: + ~google.resumable_media.common.DataCorruption: If the download's + checksum doesn't agree with server-computed checksum. + """ + # Retrieve the expected checksum only once for the download request, + # then compute and validate the checksum when the full download completes. + # Retried requests are range requests, and there's no way to detect + # data corruption for that byte range alone. + if self._expected_checksum is None and self._checksum_object is None: + # `_get_expected_checksum()` may return None even if a checksum was + # requested, in which case it will emit an info log _MISSING_CHECKSUM. + # If an invalid checksum type is specified, this will raise ValueError. + expected_checksum, checksum_object = _helpers._get_expected_checksum( + response, self._get_headers, self.media_url, checksum_type=self.checksum + ) + self._expected_checksum = expected_checksum + self._checksum_object = checksum_object + else: + expected_checksum = self._expected_checksum + checksum_object = self._checksum_object + + with response: + body_iter = response.raw.stream( + _request_helpers._SINGLE_GET_CHUNK_SIZE, decode_content=False + ) + for chunk in body_iter: + self._stream.write(chunk) + self._bytes_downloaded += len(chunk) + checksum_object.update(chunk) + response._content_consumed = True + + # Don't validate the checksum for partial responses. + if ( + expected_checksum is not None + and response.status_code != http.client.PARTIAL_CONTENT + ): + actual_checksum = _helpers.prepare_checksum_digest(checksum_object.digest()) + + if actual_checksum != expected_checksum: + headers = self._get_headers(response) + x_goog_encoding = headers.get("x-goog-stored-content-encoding") + x_goog_length = headers.get("x-goog-stored-content-length") + content_length_msg = _RESPONSE_HEADERS_INFO.format( + x_goog_length, x_goog_encoding, self._bytes_downloaded + ) + if ( + x_goog_length + and self._bytes_downloaded < int(x_goog_length) + and x_goog_encoding != "gzip" + ): + # The library will attempt to trigger a retry by raising a ConnectionError, if + # (a) bytes_downloaded is less than response header x-goog-stored-content-length, and + # (b) the object is not gzip-compressed when stored in Cloud Storage. + raise ConnectionError(content_length_msg) + else: + msg = _CHECKSUM_MISMATCH.format( + self.media_url, + expected_checksum, + actual_checksum, + checksum_type=self.checksum.upper(), + ) + msg += content_length_msg + raise common.DataCorruption(response, msg) + + def consume( + self, + transport, + timeout=( + _request_helpers._DEFAULT_CONNECT_TIMEOUT, + _request_helpers._DEFAULT_READ_TIMEOUT, + ), + ): + """Consume the resource to be downloaded. + + If a ``stream`` is attached to this download, then the downloaded + resource will be written to the stream. + + Args: + transport (~requests.Session): A ``requests`` object which can + make authenticated requests. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Returns: + ~requests.Response: The HTTP response returned by ``transport``. + + Raises: + ~google.resumable_media.common.DataCorruption: If the download's + checksum doesn't agree with server-computed checksum. + ValueError: If the current :class:`Download` has already + finished. + """ + method, _, payload, headers = self._prepare_request() + # NOTE: We assume "payload is None" but pass it along anyway. + request_kwargs = { + "data": payload, + "headers": headers, + "timeout": timeout, + "stream": True, + } + + # Assign object generation if generation is specified in the media url. + if self._object_generation is None: + self._object_generation = _helpers._get_generation_from_url(self.media_url) + + # Wrap the request business logic in a function to be retried. + def retriable_request(): + url = self.media_url + + # To restart an interrupted download, read from the offset of last byte + # received using a range request, and set object generation query param. + if self._bytes_downloaded > 0: + _download.add_bytes_range( + (self.start or 0) + self._bytes_downloaded, self.end, self._headers + ) + request_kwargs["headers"] = self._headers + + # Set object generation query param to ensure the same object content is requested. + if ( + self._object_generation is not None + and _helpers._get_generation_from_url(self.media_url) is None + ): + query_param = {"generation": self._object_generation} + url = _helpers.add_query_parameters(self.media_url, query_param) + + result = transport.request(method, url, **request_kwargs) + + # If a generation hasn't been specified, and this is the first response we get, let's record the + # generation. In future requests we'll specify the generation query param to avoid data races. + if self._object_generation is None: + self._object_generation = _helpers._parse_generation_header( + result, self._get_headers + ) + + self._process_response(result) + + # With decompressive transcoding, GCS serves back the whole file regardless of the range request, + # thus we reset the stream position to the start of the stream. + # See: https://cloud.google.com/storage/docs/transcoding#range + if self._stream is not None: + if _helpers._is_decompressive_transcoding(result, self._get_headers): + try: + self._stream.seek(0) + except Exception as exc: + msg = _STREAM_SEEK_ERROR.format(url) + raise Exception(msg) from exc + self._bytes_downloaded = 0 + + self._write_to_stream(result) + + return result + + return _request_helpers.wait_and_retry( + retriable_request, self._get_status_code, self._retry_strategy + ) + + +class ChunkedDownload(_request_helpers.RequestsMixin, _download.ChunkedDownload): + """Download a resource in chunks from a Google API. + + Args: + media_url (str): The URL containing the media to be downloaded. + chunk_size (int): The number of bytes to be retrieved in each + request. + stream (IO[bytes]): A write-able stream (i.e. file-like object) that + will be used to concatenate chunks of the resource as they are + downloaded. + start (int): The first byte in a range to be downloaded. If not + provided, defaults to ``0``. + end (int): The last byte in a range to be downloaded. If not + provided, will download to the end of the media. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with each request, e.g. headers for data encryption + key headers. + + Attributes: + media_url (str): The URL containing the media to be downloaded. + start (Optional[int]): The first byte in a range to be downloaded. + end (Optional[int]): The last byte in a range to be downloaded. + chunk_size (int): The number of bytes to be retrieved in each request. + + Raises: + ValueError: If ``start`` is negative. + """ + + def consume_next_chunk( + self, + transport, + timeout=( + _request_helpers._DEFAULT_CONNECT_TIMEOUT, + _request_helpers._DEFAULT_READ_TIMEOUT, + ), + ): + """Consume the next chunk of the resource to be downloaded. + + Args: + transport (~requests.Session): A ``requests`` object which can + make authenticated requests. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Returns: + ~requests.Response: The HTTP response returned by ``transport``. + + Raises: + ValueError: If the current download has finished. + """ + method, url, payload, headers = self._prepare_request() + + # Wrap the request business logic in a function to be retried. + def retriable_request(): + # NOTE: We assume "payload is None" but pass it along anyway. + result = transport.request( + method, + url, + data=payload, + headers=headers, + timeout=timeout, + ) + self._process_response(result) + return result + + return _request_helpers.wait_and_retry( + retriable_request, self._get_status_code, self._retry_strategy + ) + + +class RawChunkedDownload(_request_helpers.RawRequestsMixin, _download.ChunkedDownload): + """Download a raw resource in chunks from a Google API. + + Args: + media_url (str): The URL containing the media to be downloaded. + chunk_size (int): The number of bytes to be retrieved in each + request. + stream (IO[bytes]): A write-able stream (i.e. file-like object) that + will be used to concatenate chunks of the resource as they are + downloaded. + start (int): The first byte in a range to be downloaded. If not + provided, defaults to ``0``. + end (int): The last byte in a range to be downloaded. If not + provided, will download to the end of the media. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with each request, e.g. headers for data encryption + key headers. + + Attributes: + media_url (str): The URL containing the media to be downloaded. + start (Optional[int]): The first byte in a range to be downloaded. + end (Optional[int]): The last byte in a range to be downloaded. + chunk_size (int): The number of bytes to be retrieved in each request. + + Raises: + ValueError: If ``start`` is negative. + """ + + def consume_next_chunk( + self, + transport, + timeout=( + _request_helpers._DEFAULT_CONNECT_TIMEOUT, + _request_helpers._DEFAULT_READ_TIMEOUT, + ), + ): + """Consume the next chunk of the resource to be downloaded. + + Args: + transport (~requests.Session): A ``requests`` object which can + make authenticated requests. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Returns: + ~requests.Response: The HTTP response returned by ``transport``. + + Raises: + ValueError: If the current download has finished. + """ + method, url, payload, headers = self._prepare_request() + + # Wrap the request business logic in a function to be retried. + def retriable_request(): + # NOTE: We assume "payload is None" but pass it along anyway. + result = transport.request( + method, + url, + data=payload, + headers=headers, + stream=True, + timeout=timeout, + ) + self._process_response(result) + return result + + return _request_helpers.wait_and_retry( + retriable_request, self._get_status_code, self._retry_strategy + ) + + +def _add_decoder(response_raw, checksum): + """Patch the ``_decoder`` on a ``urllib3`` response. + + This is so that we can intercept the compressed bytes before they are + decoded. + + Only patches if the content encoding is ``gzip`` or ``br``. + + Args: + response_raw (urllib3.response.HTTPResponse): The raw response for + an HTTP request. + checksum (object): + A checksum which will be updated with compressed bytes. + + Returns: + object: Either the original ``checksum`` if ``_decoder`` is not + patched, or a ``_DoNothingHash`` if the decoder is patched, since the + caller will no longer need to hash to decoded bytes. + """ + encoding = response_raw.headers.get("content-encoding", "").lower() + if encoding == "gzip": + response_raw._decoder = _GzipDecoder(checksum) + return _helpers._DoNothingHash() + # Only activate if brotli is installed + elif encoding == "br" and _BrotliDecoder: # type: ignore + response_raw._decoder = _BrotliDecoder(checksum) + return _helpers._DoNothingHash() + else: + return checksum + + +class _GzipDecoder(urllib3.response.GzipDecoder): + """Custom subclass of ``urllib3`` decoder for ``gzip``-ed bytes. + + Allows a checksum function to see the compressed bytes before they are + decoded. This way the checksum of the compressed value can be computed. + + Args: + checksum (object): + A checksum which will be updated with compressed bytes. + """ + + def __init__(self, checksum): + super().__init__() + self._checksum = checksum + + def decompress(self, data, max_length=-1): + """Decompress the bytes. + + Args: + data (bytes): The compressed bytes to be decompressed. + max_length (int): Maximum number of bytes to return. -1 for no + limit. Forwarded to the underlying decoder when supported. + + Returns: + bytes: The decompressed bytes from ``data``. + """ + self._checksum.update(data) + try: + return super().decompress(data, max_length=max_length) + except TypeError: + return super().decompress(data) + + +# urllib3.response.BrotliDecoder might not exist depending on whether brotli is +# installed. +if hasattr(urllib3.response, "BrotliDecoder"): + + class _BrotliDecoder: + """Handler for ``brotli`` encoded bytes. + + Allows a checksum function to see the compressed bytes before they are + decoded. This way the checksum of the compressed value can be computed. + + Because BrotliDecoder's decompress method is dynamically created in + urllib3, a subclass is not practical. Instead, this class creates a + captive urllib3.requests.BrotliDecoder instance and acts as a proxy. + + Args: + checksum (object): + A checksum which will be updated with compressed bytes. + """ + + def __init__(self, checksum): + self._decoder = urllib3.response.BrotliDecoder() + self._checksum = checksum + + def decompress(self, data, max_length=-1): + """Decompress the bytes. + + Args: + data (bytes): The compressed bytes to be decompressed. + max_length (int): Maximum number of bytes to return. -1 for no + limit. Forwarded to the underlying decoder when supported. + + Returns: + bytes: The decompressed bytes from ``data``. + """ + self._checksum.update(data) + try: + return self._decoder.decompress(data, max_length=max_length) + except TypeError: + return self._decoder.decompress(data) + + @property + def has_unconsumed_tail(self): + try: + return self._decoder.has_unconsumed_tail + except AttributeError: + return False + + def flush(self): + return self._decoder.flush() + +else: # pragma: NO COVER + _BrotliDecoder = None # type: ignore # pragma: NO COVER diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/resumable_media/requests/upload.py b/loan-advisor-agent/.venv/Lib/site-packages/google/resumable_media/requests/upload.py new file mode 100644 index 0000000000000000000000000000000000000000..3233517d0930b3b8b8092a54dbee5a429117995b --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/resumable_media/requests/upload.py @@ -0,0 +1,761 @@ +# Copyright 2017 Google Inc. +# +# Licensed 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. + +"""Support for resumable uploads. + +Also supported here are simple (media) uploads and multipart +uploads that contain both metadata and a small file as payload. +""" + +from google.resumable_media import _upload +from google.resumable_media.requests import _request_helpers + + +class SimpleUpload(_request_helpers.RequestsMixin, _upload.SimpleUpload): + """Upload a resource to a Google API. + + A **simple** media upload sends no metadata and completes the upload + in a single request. + + Args: + upload_url (str): The URL where the content will be uploaded. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with the request, e.g. headers for encrypted data. + + Attributes: + upload_url (str): The URL where the content will be uploaded. + """ + + def transmit( + self, + transport, + data, + content_type, + timeout=( + _request_helpers._DEFAULT_CONNECT_TIMEOUT, + _request_helpers._DEFAULT_READ_TIMEOUT, + ), + ): + """Transmit the resource to be uploaded. + + Args: + transport (~requests.Session): A ``requests`` object which can + make authenticated requests. + data (bytes): The resource content to be uploaded. + content_type (str): The content type of the resource, e.g. a JPEG + image has content type ``image/jpeg``. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Returns: + ~requests.Response: The HTTP response returned by ``transport``. + """ + method, url, payload, headers = self._prepare_request(data, content_type) + + # Wrap the request business logic in a function to be retried. + def retriable_request(): + result = transport.request( + method, url, data=payload, headers=headers, timeout=timeout + ) + + self._process_response(result) + + return result + + return _request_helpers.wait_and_retry( + retriable_request, self._get_status_code, self._retry_strategy + ) + + +class MultipartUpload(_request_helpers.RequestsMixin, _upload.MultipartUpload): + """Upload a resource with metadata to a Google API. + + A **multipart** upload sends both metadata and the resource in a single + (multipart) request. + + Args: + upload_url (str): The URL where the content will be uploaded. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with the request, e.g. headers for encrypted data. + checksum Optional([str]): The type of checksum to compute to verify + the integrity of the object. The request metadata will be amended + to include the computed value. Using this option will override a + manually-set checksum value. Supported values are "md5", + "crc32c" and None. The default is None. + + Attributes: + upload_url (str): The URL where the content will be uploaded. + """ + + def transmit( + self, + transport, + data, + metadata, + content_type, + timeout=( + _request_helpers._DEFAULT_CONNECT_TIMEOUT, + _request_helpers._DEFAULT_READ_TIMEOUT, + ), + ): + """Transmit the resource to be uploaded. + + Args: + transport (~requests.Session): A ``requests`` object which can + make authenticated requests. + data (bytes): The resource content to be uploaded. + metadata (Mapping[str, str]): The resource metadata, such as an + ACL list. + content_type (str): The content type of the resource, e.g. a JPEG + image has content type ``image/jpeg``. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Returns: + ~requests.Response: The HTTP response returned by ``transport``. + """ + method, url, payload, headers = self._prepare_request( + data, metadata, content_type + ) + + # Wrap the request business logic in a function to be retried. + def retriable_request(): + result = transport.request( + method, url, data=payload, headers=headers, timeout=timeout + ) + + self._process_response(result) + + return result + + return _request_helpers.wait_and_retry( + retriable_request, self._get_status_code, self._retry_strategy + ) + + +class ResumableUpload(_request_helpers.RequestsMixin, _upload.ResumableUpload): + """Initiate and fulfill a resumable upload to a Google API. + + A **resumable** upload sends an initial request with the resource metadata + and then gets assigned an upload ID / upload URL to send bytes to. + Using the upload URL, the upload is then done in chunks (determined by + the user) until all bytes have been uploaded. + + When constructing a resumable upload, only the resumable upload URL and + the chunk size are required: + + .. testsetup:: resumable-constructor + + bucket = 'bucket-foo' + + .. doctest:: resumable-constructor + + >>> from google.resumable_media.requests import ResumableUpload + >>> + >>> url_template = ( + ... 'https://www.googleapis.com/upload/storage/v1/b/{bucket}/o?' + ... 'uploadType=resumable') + >>> upload_url = url_template.format(bucket=bucket) + >>> + >>> chunk_size = 3 * 1024 * 1024 # 3MB + >>> upload = ResumableUpload(upload_url, chunk_size) + + When initiating an upload (via :meth:`initiate`), the caller is expected + to pass the resource being uploaded as a file-like ``stream``. If the size + of the resource is explicitly known, it can be passed in directly: + + .. testsetup:: resumable-explicit-size + + import os + import tempfile + + import mock + import requests + import http.client + + from google.resumable_media.requests import ResumableUpload + + upload_url = 'http://test.invalid' + chunk_size = 3 * 1024 * 1024 # 3MB + upload = ResumableUpload(upload_url, chunk_size) + + file_desc, filename = tempfile.mkstemp() + os.close(file_desc) + + data = b'some bytes!' + with open(filename, 'wb') as file_obj: + file_obj.write(data) + + fake_response = requests.Response() + fake_response.status_code = int(http.client.OK) + fake_response._content = b'' + resumable_url = 'http://test.invalid?upload_id=7up' + fake_response.headers['location'] = resumable_url + + post_method = mock.Mock(return_value=fake_response, spec=[]) + transport = mock.Mock(request=post_method, spec=['request']) + + .. doctest:: resumable-explicit-size + + >>> import os + >>> + >>> upload.total_bytes is None + True + >>> + >>> stream = open(filename, 'rb') + >>> total_bytes = os.path.getsize(filename) + >>> metadata = {'name': filename} + >>> response = upload.initiate( + ... transport, stream, metadata, 'text/plain', + ... total_bytes=total_bytes) + >>> response + + >>> + >>> upload.total_bytes == total_bytes + True + + .. testcleanup:: resumable-explicit-size + + os.remove(filename) + + If the stream is in a "final" state (i.e. it won't have any more bytes + written to it), the total number of bytes can be determined implicitly + from the ``stream`` itself: + + .. testsetup:: resumable-implicit-size + + import io + + import mock + import requests + import http.client + + from google.resumable_media.requests import ResumableUpload + + upload_url = 'http://test.invalid' + chunk_size = 3 * 1024 * 1024 # 3MB + upload = ResumableUpload(upload_url, chunk_size) + + fake_response = requests.Response() + fake_response.status_code = int(http.client.OK) + fake_response._content = b'' + resumable_url = 'http://test.invalid?upload_id=7up' + fake_response.headers['location'] = resumable_url + + post_method = mock.Mock(return_value=fake_response, spec=[]) + transport = mock.Mock(request=post_method, spec=['request']) + + data = b'some MOAR bytes!' + metadata = {'name': 'some-file.jpg'} + content_type = 'image/jpeg' + + .. doctest:: resumable-implicit-size + + >>> stream = io.BytesIO(data) + >>> response = upload.initiate( + ... transport, stream, metadata, content_type) + >>> + >>> upload.total_bytes == len(data) + True + + If the size of the resource is **unknown** when the upload is initiated, + the ``stream_final`` argument can be used. This might occur if the + resource is being dynamically created on the client (e.g. application + logs). To use this argument: + + .. testsetup:: resumable-unknown-size + + import io + + import mock + import requests + import http.client + + from google.resumable_media.requests import ResumableUpload + + upload_url = 'http://test.invalid' + chunk_size = 3 * 1024 * 1024 # 3MB + upload = ResumableUpload(upload_url, chunk_size) + + fake_response = requests.Response() + fake_response.status_code = int(http.client.OK) + fake_response._content = b'' + resumable_url = 'http://test.invalid?upload_id=7up' + fake_response.headers['location'] = resumable_url + + post_method = mock.Mock(return_value=fake_response, spec=[]) + transport = mock.Mock(request=post_method, spec=['request']) + + metadata = {'name': 'some-file.jpg'} + content_type = 'application/octet-stream' + + stream = io.BytesIO(b'data') + + .. doctest:: resumable-unknown-size + + >>> response = upload.initiate( + ... transport, stream, metadata, content_type, + ... stream_final=False) + >>> + >>> upload.total_bytes is None + True + + Args: + upload_url (str): The URL where the resumable upload will be initiated. + chunk_size (int): The size of each chunk used to upload the resource. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with the :meth:`initiate` request, e.g. headers for + encrypted data. These **will not** be sent with + :meth:`transmit_next_chunk` or :meth:`recover` requests. + checksum Optional([str]): The type of checksum to compute to verify + the integrity of the object. After the upload is complete, the + server-computed checksum of the resulting object will be checked + and google.resumable_media.common.DataCorruption will be raised on + a mismatch. The corrupted file will not be deleted from the remote + host automatically. Supported values are "md5", "crc32c" and None. + The default is None. + + Attributes: + upload_url (str): The URL where the content will be uploaded. + + Raises: + ValueError: If ``chunk_size`` is not a multiple of + :data:`.UPLOAD_CHUNK_SIZE`. + """ + + def initiate( + self, + transport, + stream, + metadata, + content_type, + total_bytes=None, + stream_final=True, + timeout=( + _request_helpers._DEFAULT_CONNECT_TIMEOUT, + _request_helpers._DEFAULT_READ_TIMEOUT, + ), + ): + """Initiate a resumable upload. + + By default, this method assumes your ``stream`` is in a "final" + state ready to transmit. However, ``stream_final=False`` can be used + to indicate that the size of the resource is not known. This can happen + if bytes are being dynamically fed into ``stream``, e.g. if the stream + is attached to application logs. + + If ``stream_final=False`` is used, :attr:`chunk_size` bytes will be + read from the stream every time :meth:`transmit_next_chunk` is called. + If one of those reads produces strictly fewer bites than the chunk + size, the upload will be concluded. + + Args: + transport (~requests.Session): A ``requests`` object which can + make authenticated requests. + stream (IO[bytes]): The stream (i.e. file-like object) that will + be uploaded. The stream **must** be at the beginning (i.e. + ``stream.tell() == 0``). + metadata (Mapping[str, str]): The resource metadata, such as an + ACL list. + content_type (str): The content type of the resource, e.g. a JPEG + image has content type ``image/jpeg``. + total_bytes (Optional[int]): The total number of bytes to be + uploaded. If specified, the upload size **will not** be + determined from the stream (even if ``stream_final=True``). + stream_final (Optional[bool]): Indicates if the ``stream`` is + "final" (i.e. no more bytes will be added to it). In this case + we determine the upload size from the size of the stream. If + ``total_bytes`` is passed, this argument will be ignored. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Returns: + ~requests.Response: The HTTP response returned by ``transport``. + """ + method, url, payload, headers = self._prepare_initiate_request( + stream, + metadata, + content_type, + total_bytes=total_bytes, + stream_final=stream_final, + ) + + # Wrap the request business logic in a function to be retried. + def retriable_request(): + result = transport.request( + method, url, data=payload, headers=headers, timeout=timeout + ) + + self._process_initiate_response(result) + + return result + + return _request_helpers.wait_and_retry( + retriable_request, self._get_status_code, self._retry_strategy + ) + + def transmit_next_chunk( + self, + transport, + timeout=( + _request_helpers._DEFAULT_CONNECT_TIMEOUT, + _request_helpers._DEFAULT_READ_TIMEOUT, + ), + ): + """Transmit the next chunk of the resource to be uploaded. + + If the current upload was initiated with ``stream_final=False``, + this method will dynamically determine if the upload has completed. + The upload will be considered complete if the stream produces + fewer than :attr:`chunk_size` bytes when a chunk is read from it. + + In the case of failure, an exception is thrown that preserves the + failed response: + + .. testsetup:: bad-response + + import io + + import mock + import requests + import http.client + + from google import resumable_media + import google.resumable_media.requests.upload as upload_mod + + transport = mock.Mock(spec=['request']) + fake_response = requests.Response() + fake_response.status_code = int(http.client.BAD_REQUEST) + transport.request.return_value = fake_response + + upload_url = 'http://test.invalid' + upload = upload_mod.ResumableUpload( + upload_url, resumable_media.UPLOAD_CHUNK_SIZE) + # Fake that the upload has been initiate()-d + data = b'data is here' + upload._stream = io.BytesIO(data) + upload._total_bytes = len(data) + upload._resumable_url = 'http://test.invalid?upload_id=nope' + + .. doctest:: bad-response + :options: +NORMALIZE_WHITESPACE + + >>> error = None + >>> try: + ... upload.transmit_next_chunk(transport) + ... except resumable_media.InvalidResponse as caught_exc: + ... error = caught_exc + ... + >>> error + InvalidResponse('Request failed with status code', 400, + 'Expected one of', , ) + >>> error.response + + + Args: + transport (~requests.Session): A ``requests`` object which can + make authenticated requests. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Returns: + ~requests.Response: The HTTP response returned by ``transport``. + + Raises: + ~google.resumable_media.common.InvalidResponse: If the status + code is not 200 or http.client.PERMANENT_REDIRECT. + ~google.resumable_media.common.DataCorruption: If this is the final + chunk, a checksum validation was requested, and the checksum + does not match or is not available. + """ + method, url, payload, headers = self._prepare_request() + + # Wrap the request business logic in a function to be retried. + def retriable_request(): + result = transport.request( + method, url, data=payload, headers=headers, timeout=timeout + ) + + self._process_resumable_response(result, len(payload)) + + return result + + return _request_helpers.wait_and_retry( + retriable_request, self._get_status_code, self._retry_strategy + ) + + def recover(self, transport): + """Recover from a failure and check the status of the current upload. + + This will verify the progress with the server and make sure the + current upload is in a valid state before :meth:`transmit_next_chunk` + can be used again. See https://cloud.google.com/storage/docs/performing-resumable-uploads#status-check + for more information. + + This method can be used when a :class:`ResumableUpload` is in an + :attr:`~ResumableUpload.invalid` state due to a request failure. + + Args: + transport (~requests.Session): A ``requests`` object which can + make authenticated requests. + + Returns: + ~requests.Response: The HTTP response returned by ``transport``. + """ + timeout = ( + _request_helpers._DEFAULT_CONNECT_TIMEOUT, + _request_helpers._DEFAULT_READ_TIMEOUT, + ) + + method, url, payload, headers = self._prepare_recover_request() + # NOTE: We assume "payload is None" but pass it along anyway. + + # Wrap the request business logic in a function to be retried. + def retriable_request(): + result = transport.request( + method, url, data=payload, headers=headers, timeout=timeout + ) + + self._process_recover_response(result) + + return result + + return _request_helpers.wait_and_retry( + retriable_request, self._get_status_code, self._retry_strategy + ) + + +class XMLMPUContainer(_request_helpers.RequestsMixin, _upload.XMLMPUContainer): + """Initiate and close an upload using the XML MPU API. + + An XML MPU sends an initial request and then receives an upload ID. + Using the upload ID, the upload is then done in numbered parts and the + parts can be uploaded concurrently. + + In order to avoid concurrency issues with this container object, the + uploading of individual parts is handled separately, by XMLMPUPart objects + spawned from this container class. The XMLMPUPart objects are not + necessarily in the same process as the container, so they do not update the + container automatically. + + MPUs are sometimes referred to as "Multipart Uploads", which is ambiguous + given the JSON multipart upload, so the abbreviation "MPU" will be used + throughout. + + See: https://cloud.google.com/storage/docs/multipart-uploads + + Args: + upload_url (str): The URL of the object (without query parameters). The + initiate, PUT, and finalization requests will all use this URL, with + varying query parameters. + headers (Optional[Mapping[str, str]]): Extra headers that should + be sent with the :meth:`initiate` request, e.g. headers for + encrypted data. These headers will be propagated to individual + XMLMPUPart objects spawned from this container as well. + + Attributes: + upload_url (str): The URL where the content will be uploaded. + upload_id (Optional(int)): The ID of the upload from the initialization + response. + """ + + def initiate( + self, + transport, + content_type, + timeout=( + _request_helpers._DEFAULT_CONNECT_TIMEOUT, + _request_helpers._DEFAULT_READ_TIMEOUT, + ), + ): + """Initiate an MPU and record the upload ID. + + Args: + transport (object): An object which can make authenticated + requests. + content_type (str): The content type of the resource, e.g. a JPEG + image has content type ``image/jpeg``. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Returns: + ~requests.Response: The HTTP response returned by ``transport``. + """ + + method, url, payload, headers = self._prepare_initiate_request( + content_type, + ) + + # Wrap the request business logic in a function to be retried. + def retriable_request(): + result = transport.request( + method, url, data=payload, headers=headers, timeout=timeout + ) + + self._process_initiate_response(result) + + return result + + return _request_helpers.wait_and_retry( + retriable_request, self._get_status_code, self._retry_strategy + ) + + def finalize( + self, + transport, + timeout=( + _request_helpers._DEFAULT_CONNECT_TIMEOUT, + _request_helpers._DEFAULT_READ_TIMEOUT, + ), + ): + """Finalize an MPU request with all the parts. + + Args: + transport (object): An object which can make authenticated + requests. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Returns: + ~requests.Response: The HTTP response returned by ``transport``. + """ + method, url, payload, headers = self._prepare_finalize_request() + + # Wrap the request business logic in a function to be retried. + def retriable_request(): + result = transport.request( + method, url, data=payload, headers=headers, timeout=timeout + ) + + self._process_finalize_response(result) + + return result + + return _request_helpers.wait_and_retry( + retriable_request, self._get_status_code, self._retry_strategy + ) + + def cancel( + self, + transport, + timeout=( + _request_helpers._DEFAULT_CONNECT_TIMEOUT, + _request_helpers._DEFAULT_READ_TIMEOUT, + ), + ): + """Cancel an MPU request and permanently delete any uploaded parts. + + This cannot be undone. + + Args: + transport (object): An object which can make authenticated + requests. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Returns: + ~requests.Response: The HTTP response returned by ``transport``. + """ + method, url, payload, headers = self._prepare_cancel_request() + + # Wrap the request business logic in a function to be retried. + def retriable_request(): + result = transport.request( + method, url, data=payload, headers=headers, timeout=timeout + ) + + self._process_cancel_response(result) + + return result + + return _request_helpers.wait_and_retry( + retriable_request, self._get_status_code, self._retry_strategy + ) + + +class XMLMPUPart(_request_helpers.RequestsMixin, _upload.XMLMPUPart): + def upload( + self, + transport, + timeout=( + _request_helpers._DEFAULT_CONNECT_TIMEOUT, + _request_helpers._DEFAULT_READ_TIMEOUT, + ), + ): + """Upload the part. + + Args: + transport (object): An object which can make authenticated + requests. + timeout (Optional[Union[float, Tuple[float, float]]]): + The number of seconds to wait for the server response. + Depending on the retry strategy, a request may be repeated + several times using the same timeout each time. + + Can also be passed as a tuple (connect_timeout, read_timeout). + See :meth:`requests.Session.request` documentation for details. + + Returns: + ~requests.Response: The HTTP response returned by ``transport``. + """ + method, url, payload, headers = self._prepare_upload_request() + + # Wrap the request business logic in a function to be retried. + def retriable_request(): + result = transport.request( + method, url, data=payload, headers=headers, timeout=timeout + ) + + self._process_upload_response(result) + + return result + + return _request_helpers.wait_and_retry( + retriable_request, self._get_status_code, self._retry_strategy + ) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/__pycache__/code_pb2.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/__pycache__/code_pb2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d985762aad49ede7f6afa6d04c6ec8e54c14fd7 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/__pycache__/code_pb2.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/__pycache__/error_details_pb2.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/__pycache__/error_details_pb2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..683f45cd49b210d2ad7e5fe8e1a070517820501d Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/__pycache__/error_details_pb2.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/__pycache__/status_pb2.cpython-312.pyc b/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/__pycache__/status_pb2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fcecbd575ed515766681706b6d80a58f0a86d2c5 Binary files /dev/null and b/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/__pycache__/status_pb2.cpython-312.pyc differ diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/code.proto b/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/code.proto new file mode 100644 index 0000000000000000000000000000000000000000..46b5d75a78aa182e3353744d4fac76aed4d609cb --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/code.proto @@ -0,0 +1,186 @@ +// Copyright 2026 Google LLC +// +// Licensed 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. + +syntax = "proto3"; + +package google.rpc; + +option go_package = "google.golang.org/genproto/googleapis/rpc/code;code"; +option java_multiple_files = true; +option java_outer_classname = "CodeProto"; +option java_package = "com.google.rpc"; +option objc_class_prefix = "RPC"; + +// The canonical error codes for gRPC APIs. +// +// +// Sometimes multiple error codes may apply. Services should return +// the most specific error code that applies. For example, prefer +// `OUT_OF_RANGE` over `FAILED_PRECONDITION` if both codes apply. +// Similarly prefer `NOT_FOUND` or `ALREADY_EXISTS` over `FAILED_PRECONDITION`. +enum Code { + // Not an error; returned on success. + // + // HTTP Mapping: 200 OK + OK = 0; + + // The operation was cancelled, typically by the caller. + // + // HTTP Mapping: 499 Client Closed Request + CANCELLED = 1; + + // Unknown error. For example, this error may be returned when + // a `Status` value received from another address space belongs to + // an error space that is not known in this address space. Also + // errors raised by APIs that do not return enough error information + // may be converted to this error. + // + // HTTP Mapping: 500 Internal Server Error + UNKNOWN = 2; + + // The client specified an invalid argument. Note that this differs + // from `FAILED_PRECONDITION`. `INVALID_ARGUMENT` indicates arguments + // that are problematic regardless of the state of the system + // (e.g., a malformed file name). + // + // HTTP Mapping: 400 Bad Request + INVALID_ARGUMENT = 3; + + // The deadline expired before the operation could complete. For operations + // that change the state of the system, this error may be returned + // even if the operation has completed successfully. For example, a + // successful response from a server could have been delayed long + // enough for the deadline to expire. + // + // HTTP Mapping: 504 Gateway Timeout + DEADLINE_EXCEEDED = 4; + + // Some requested entity (e.g., file or directory) was not found. + // + // Note to server developers: if a request is denied for an entire class + // of users, such as gradual feature rollout or undocumented allowlist, + // `NOT_FOUND` may be used. If a request is denied for some users within + // a class of users, such as user-based access control, `PERMISSION_DENIED` + // must be used. + // + // HTTP Mapping: 404 Not Found + NOT_FOUND = 5; + + // The entity that a client attempted to create (e.g., file or directory) + // already exists. + // + // HTTP Mapping: 409 Conflict + ALREADY_EXISTS = 6; + + // The caller does not have permission to execute the specified + // operation. `PERMISSION_DENIED` must not be used for rejections + // caused by exhausting some resource (use `RESOURCE_EXHAUSTED` + // instead for those errors). `PERMISSION_DENIED` must not be + // used if the caller can not be identified (use `UNAUTHENTICATED` + // instead for those errors). This error code does not imply the + // request is valid or the requested entity exists or satisfies + // other pre-conditions. + // + // HTTP Mapping: 403 Forbidden + PERMISSION_DENIED = 7; + + // The request does not have valid authentication credentials for the + // operation. + // + // HTTP Mapping: 401 Unauthorized + UNAUTHENTICATED = 16; + + // Some resource has been exhausted, perhaps a per-user quota, or + // perhaps the entire file system is out of space. + // + // HTTP Mapping: 429 Too Many Requests + RESOURCE_EXHAUSTED = 8; + + // The operation was rejected because the system is not in a state + // required for the operation's execution. For example, the directory + // to be deleted is non-empty, an rmdir operation is applied to + // a non-directory, etc. + // + // Service implementors can use the following guidelines to decide + // between `FAILED_PRECONDITION`, `ABORTED`, and `UNAVAILABLE`: + // (a) Use `UNAVAILABLE` if the client can retry just the failing call. + // (b) Use `ABORTED` if the client should retry at a higher level. For + // example, when a client-specified test-and-set fails, indicating the + // client should restart a read-modify-write sequence. + // (c) Use `FAILED_PRECONDITION` if the client should not retry until + // the system state has been explicitly fixed. For example, if an "rmdir" + // fails because the directory is non-empty, `FAILED_PRECONDITION` + // should be returned since the client should not retry unless + // the files are deleted from the directory. + // + // HTTP Mapping: 400 Bad Request + FAILED_PRECONDITION = 9; + + // The operation was aborted, typically due to a concurrency issue such as + // a sequencer check failure or transaction abort. + // + // See the guidelines above for deciding between `FAILED_PRECONDITION`, + // `ABORTED`, and `UNAVAILABLE`. + // + // HTTP Mapping: 409 Conflict + ABORTED = 10; + + // The operation was attempted past the valid range. E.g., seeking or + // reading past end-of-file. + // + // Unlike `INVALID_ARGUMENT`, this error indicates a problem that may + // be fixed if the system state changes. For example, a 32-bit file + // system will generate `INVALID_ARGUMENT` if asked to read at an + // offset that is not in the range [0,2^32-1], but it will generate + // `OUT_OF_RANGE` if asked to read from an offset past the current + // file size. + // + // There is a fair bit of overlap between `FAILED_PRECONDITION` and + // `OUT_OF_RANGE`. We recommend using `OUT_OF_RANGE` (the more specific + // error) when it applies so that callers who are iterating through + // a space can easily look for an `OUT_OF_RANGE` error to detect when + // they are done. + // + // HTTP Mapping: 400 Bad Request + OUT_OF_RANGE = 11; + + // The operation is not implemented or is not supported/enabled in this + // service. + // + // HTTP Mapping: 501 Not Implemented + UNIMPLEMENTED = 12; + + // Internal errors. This means that some invariants expected by the + // underlying system have been broken. This error code is reserved + // for serious errors. + // + // HTTP Mapping: 500 Internal Server Error + INTERNAL = 13; + + // The service is currently unavailable. This is most likely a + // transient condition, which can be corrected by retrying with + // a backoff. Note that it is not always safe to retry + // non-idempotent operations. + // + // See the guidelines above for deciding between `FAILED_PRECONDITION`, + // `ABORTED`, and `UNAVAILABLE`. + // + // HTTP Mapping: 503 Service Unavailable + UNAVAILABLE = 14; + + // Unrecoverable data loss or corruption. + // + // HTTP Mapping: 500 Internal Server Error + DATA_LOSS = 15; +} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/code_pb2.py b/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/code_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..01e73960eb774dc12cd8306d354585d42bb9c99e --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/code_pb2.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- + +# Copyright 2025 Google LLC +# +# Licensed 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. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/rpc/code.proto +# Protobuf Python Version: 4.25.3 +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b"\n\x15google/rpc/code.proto\x12\ngoogle.rpc*\xb7\x02\n\x04\x43ode\x12\x06\n\x02OK\x10\x00\x12\r\n\tCANCELLED\x10\x01\x12\x0b\n\x07UNKNOWN\x10\x02\x12\x14\n\x10INVALID_ARGUMENT\x10\x03\x12\x15\n\x11\x44\x45\x41\x44LINE_EXCEEDED\x10\x04\x12\r\n\tNOT_FOUND\x10\x05\x12\x12\n\x0e\x41LREADY_EXISTS\x10\x06\x12\x15\n\x11PERMISSION_DENIED\x10\x07\x12\x13\n\x0fUNAUTHENTICATED\x10\x10\x12\x16\n\x12RESOURCE_EXHAUSTED\x10\x08\x12\x17\n\x13\x46\x41ILED_PRECONDITION\x10\t\x12\x0b\n\x07\x41\x42ORTED\x10\n\x12\x10\n\x0cOUT_OF_RANGE\x10\x0b\x12\x11\n\rUNIMPLEMENTED\x10\x0c\x12\x0c\n\x08INTERNAL\x10\r\x12\x0f\n\x0bUNAVAILABLE\x10\x0e\x12\r\n\tDATA_LOSS\x10\x0f\x42X\n\x0e\x63om.google.rpcB\tCodeProtoP\x01Z3google.golang.org/genproto/googleapis/rpc/code;code\xa2\x02\x03RPCb\x06proto3" +) + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, "google.rpc.code_pb2", _globals) +if _descriptor._USE_C_DESCRIPTORS == False: + _globals["DESCRIPTOR"]._options = None + _globals[ + "DESCRIPTOR" + ]._serialized_options = b"\n\016com.google.rpcB\tCodeProtoP\001Z3google.golang.org/genproto/googleapis/rpc/code;code\242\002\003RPC" + _globals["_CODE"]._serialized_start = 38 + _globals["_CODE"]._serialized_end = 349 +# @@protoc_insertion_point(module_scope) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/code_pb2.pyi b/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/code_pb2.pyi new file mode 100644 index 0000000000000000000000000000000000000000..17acb5af980096659a45effd3811a1ab577d6ffe --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/code_pb2.pyi @@ -0,0 +1,58 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. + +from typing import ClassVar as _ClassVar + +from google.protobuf import descriptor as _descriptor +from google.protobuf.internal import enum_type_wrapper as _enum_type_wrapper + +DESCRIPTOR: _descriptor.FileDescriptor + +class Code(int, metaclass=_enum_type_wrapper.EnumTypeWrapper): + __slots__ = () + OK: _ClassVar[Code] + CANCELLED: _ClassVar[Code] + UNKNOWN: _ClassVar[Code] + INVALID_ARGUMENT: _ClassVar[Code] + DEADLINE_EXCEEDED: _ClassVar[Code] + NOT_FOUND: _ClassVar[Code] + ALREADY_EXISTS: _ClassVar[Code] + PERMISSION_DENIED: _ClassVar[Code] + UNAUTHENTICATED: _ClassVar[Code] + RESOURCE_EXHAUSTED: _ClassVar[Code] + FAILED_PRECONDITION: _ClassVar[Code] + ABORTED: _ClassVar[Code] + OUT_OF_RANGE: _ClassVar[Code] + UNIMPLEMENTED: _ClassVar[Code] + INTERNAL: _ClassVar[Code] + UNAVAILABLE: _ClassVar[Code] + DATA_LOSS: _ClassVar[Code] + +OK: Code +CANCELLED: Code +UNKNOWN: Code +INVALID_ARGUMENT: Code +DEADLINE_EXCEEDED: Code +NOT_FOUND: Code +ALREADY_EXISTS: Code +PERMISSION_DENIED: Code +UNAUTHENTICATED: Code +RESOURCE_EXHAUSTED: Code +FAILED_PRECONDITION: Code +ABORTED: Code +OUT_OF_RANGE: Code +UNIMPLEMENTED: Code +INTERNAL: Code +UNAVAILABLE: Code +DATA_LOSS: Code diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/context/attribute_context.proto b/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/context/attribute_context.proto new file mode 100644 index 0000000000000000000000000000000000000000..55f95f844e74ac98185515a9f84cff941d8de188 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/context/attribute_context.proto @@ -0,0 +1,350 @@ +// Copyright 2026 Google LLC +// +// Licensed 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. + +syntax = "proto3"; + +package google.rpc.context; + +import "google/protobuf/any.proto"; +import "google/protobuf/duration.proto"; +import "google/protobuf/struct.proto"; +import "google/protobuf/timestamp.proto"; + +option go_package = "google.golang.org/genproto/googleapis/rpc/context/attribute_context;attribute_context"; +option java_multiple_files = true; +option java_outer_classname = "AttributeContextProto"; +option java_package = "com.google.rpc.context"; + +// This message defines the standard attribute vocabulary for Google APIs. +// +// An attribute is a piece of metadata that describes an activity on a network +// service. For example, the size of an HTTP request, or the status code of +// an HTTP response. +// +// Each attribute has a type and a name, which is logically defined as +// a proto message field in `AttributeContext`. The field type becomes the +// attribute type, and the field path becomes the attribute name. For example, +// the attribute `source.ip` maps to field `AttributeContext.source.ip`. +// +// This message definition is guaranteed not to have any wire breaking change. +// So you can use it directly for passing attributes across different systems. +// +// NOTE: Different system may generate different subset of attributes. Please +// verify the system specification before relying on an attribute generated +// a system. +message AttributeContext { + // This message defines attributes for a node that handles a network request. + // The node can be either a service or an application that sends, forwards, + // or receives the request. Service peers should fill in + // `principal` and `labels` as appropriate. + message Peer { + // The IP address of the peer. + string ip = 1; + + // The network port of the peer. + int64 port = 2; + + // The labels associated with the peer. + map labels = 6; + + // The identity of this peer. Similar to `Request.auth.principal`, but + // relative to the peer instead of the request. For example, the + // identity associated with a load balancer that forwarded the request. + string principal = 7; + + // The CLDR country/region code associated with the above IP address. + // If the IP address is private, the `region_code` should reflect the + // physical location where this peer is running. + string region_code = 8; + } + + // This message defines attributes associated with API operations, such as + // a network API request. The terminology is based on the conventions used + // by Google APIs, Istio, and OpenAPI. + message Api { + // The API service name. It is a logical identifier for a networked API, + // such as "pubsub.googleapis.com". The naming syntax depends on the + // API management system being used for handling the request. + string service = 1; + + // The API operation name. For gRPC requests, it is the fully qualified API + // method name, such as "google.pubsub.v1.Publisher.Publish". For OpenAPI + // requests, it is the `operationId`, such as "getPet". + string operation = 2; + + // The API protocol used for sending the request, such as "http", "https", + // "grpc", or "internal". + string protocol = 3; + + // The API version associated with the API operation above, such as "v1" or + // "v1alpha1". + string version = 4; + } + + // This message defines request authentication attributes. Terminology is + // based on the JSON Web Token (JWT) standard, but the terms also + // correlate to concepts in other standards. + message Auth { + // The authenticated principal. Reflects the issuer (`iss`) and subject + // (`sub`) claims within a JWT. The issuer and subject should be `/` + // delimited, with `/` percent-encoded within the subject fragment. For + // Google accounts, the principal format is: + // "https://accounts.google.com/{id}" + string principal = 1; + + // The intended audience(s) for this authentication information. Reflects + // the audience (`aud`) claim within a JWT. The audience + // value(s) depends on the `issuer`, but typically include one or more of + // the following pieces of information: + // + // * The services intended to receive the credential. For example, + // ["https://pubsub.googleapis.com/", "https://storage.googleapis.com/"]. + // * A set of service-based scopes. For example, + // ["https://www.googleapis.com/auth/cloud-platform"]. + // * The client id of an app, such as the Firebase project id for JWTs + // from Firebase Auth. + // + // Consult the documentation for the credential issuer to determine the + // information provided. + repeated string audiences = 2; + + // The authorized presenter of the credential. Reflects the optional + // Authorized Presenter (`azp`) claim within a JWT or the + // OAuth client id. For example, a Google Cloud Platform client id looks + // as follows: "123456789012.apps.googleusercontent.com". + string presenter = 3; + + // Structured claims presented with the credential. JWTs include + // `{key: value}` pairs for standard and private claims. The following + // is a subset of the standard required and optional claims that would + // typically be presented for a Google-based JWT: + // + // {'iss': 'accounts.google.com', + // 'sub': '113289723416554971153', + // 'aud': ['123456789012', 'pubsub.googleapis.com'], + // 'azp': '123456789012.apps.googleusercontent.com', + // 'email': 'jsmith@example.com', + // 'iat': 1353601026, + // 'exp': 1353604926} + // + // SAML assertions are similarly specified, but with an identity provider + // dependent structure. + google.protobuf.Struct claims = 4; + + // A list of access level resource names that allow resources to be + // accessed by authenticated requester. It is part of Secure GCP processing + // for the incoming request. An access level string has the format: + // "//{api_service_name}/accessPolicies/{policy_id}/accessLevels/{short_name}" + // + // Example: + // "//accesscontextmanager.googleapis.com/accessPolicies/MY_POLICY_ID/accessLevels/MY_LEVEL" + repeated string access_levels = 5; + } + + // This message defines attributes for an HTTP request. If the actual + // request is not an HTTP request, the runtime system should try to map + // the actual request to an equivalent HTTP request. + message Request { + // The unique ID for a request, which can be propagated to downstream + // systems. The ID should have low probability of collision + // within a single day for a specific service. + string id = 1; + + // The HTTP request method, such as `GET`, `POST`. + string method = 2; + + // The HTTP request headers. If multiple headers share the same key, they + // must be merged according to the HTTP spec. All header keys must be + // lowercased, because HTTP header keys are case-insensitive. + map headers = 3; + + // The HTTP URL path, excluding the query parameters. + string path = 4; + + // The HTTP request `Host` header value. + string host = 5; + + // The HTTP URL scheme, such as `http` and `https`. + string scheme = 6; + + // The HTTP URL query in the format of `name1=value1&name2=value2`, as it + // appears in the first line of the HTTP request. No decoding is performed. + string query = 7; + + // The timestamp when the `destination` service receives the last byte of + // the request. + google.protobuf.Timestamp time = 9; + + // The HTTP request size in bytes. If unknown, it must be -1. + int64 size = 10; + + // The network protocol used with the request, such as "http/1.1", + // "spdy/3", "h2", "h2c", "webrtc", "tcp", "udp", "quic". See + // https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids + // for details. + string protocol = 11; + + // A special parameter for request reason. It is used by security systems + // to associate auditing information with a request. + string reason = 12; + + // The request authentication. May be absent for unauthenticated requests. + // Derived from the HTTP request `Authorization` header or equivalent. + Auth auth = 13; + + // The values from Origin header from the HTTP request, such as + // "https://console.cloud.google.com". Modern browsers can only have one + // origin. Special browsers and/or HTTP clients may require multiple + // origins. + string origin = 14; + } + + // This message defines attributes for a typical network response. It + // generally models semantics of an HTTP response. + message Response { + // The HTTP response status code, such as `200` and `404`. + int64 code = 1; + + // The HTTP response size in bytes. If unknown, it must be -1. + int64 size = 2; + + // The HTTP response headers. If multiple headers share the same key, they + // must be merged according to HTTP spec. All header keys must be + // lowercased, because HTTP header keys are case-insensitive. + map headers = 3; + + // The timestamp when the `destination` service sends the last byte of + // the response. + google.protobuf.Timestamp time = 4; + + // The amount of time it takes the backend service to fully respond to a + // request. Measured from when the destination service starts to send the + // request to the backend until when the destination service receives the + // complete response from the backend. + google.protobuf.Duration backend_latency = 5; + } + + // This message defines core attributes for a resource. A resource is an + // addressable (named) entity provided by the destination service. For + // example, a file stored on a network storage service. + message Resource { + // The name of the service that this resource belongs to, such as + // `pubsub.googleapis.com`. The service may be different from the DNS + // hostname that actually serves the request. + string service = 1; + + // The stable identifier (name) of a resource on the `service`. A resource + // can be logically identified as "//{resource.service}/{resource.name}". + // The differences between a resource name and a URI are: + // + // * Resource name is a logical identifier, independent of network + // protocol and API version. For example, + // `//pubsub.googleapis.com/projects/123/topics/news-feed`. + // * URI often includes protocol and version information, so it can + // be used directly by applications. For example, + // `https://pubsub.googleapis.com/v1/projects/123/topics/news-feed`. + // + // See https://cloud.google.com/apis/design/resource_names for details. + string name = 2; + + // The type of the resource. The syntax is platform-specific because + // different platforms define their resources differently. + // + // For Google APIs, the type format must be "{service}/{kind}", such as + // "pubsub.googleapis.com/Topic". + string type = 3; + + // The labels or tags on the resource, such as AWS resource tags and + // Kubernetes resource labels. + map labels = 4; + + // The unique identifier of the resource. UID is unique in the time + // and space for this resource within the scope of the service. It is + // typically generated by the server on successful creation of a resource + // and must not be changed. UID is used to uniquely identify resources + // with resource name reuses. This should be a UUID4. + string uid = 5; + + // Annotations is an unstructured key-value map stored with a resource that + // may be set by external tools to store and retrieve arbitrary metadata. + // They are not queryable and should be preserved when modifying objects. + // + // More info: + // https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations/ + map annotations = 6; + + // Mutable. The display name set by clients. Must be <= 63 characters. + string display_name = 7; + + // Output only. The timestamp when the resource was created. This may + // be either the time creation was initiated or when it was completed. + google.protobuf.Timestamp create_time = 8; + + // Output only. The timestamp when the resource was last updated. Any + // change to the resource made by users must refresh this value. + // Changes to a resource made by the service should refresh this value. + google.protobuf.Timestamp update_time = 9; + + // Output only. The timestamp when the resource was deleted. + // If the resource is not deleted, this must be empty. + google.protobuf.Timestamp delete_time = 10; + + // Output only. An opaque value that uniquely identifies a version or + // generation of a resource. It can be used to confirm that the client + // and server agree on the ordering of a resource being written. + string etag = 11; + + // Immutable. The location of the resource. The location encoding is + // specific to the service provider, and new encoding may be introduced + // as the service evolves. + // + // For Google Cloud products, the encoding is what is used by Google Cloud + // APIs, such as `us-east1`, `aws-us-east-1`, and `azure-eastus2`. The + // semantics of `location` is identical to the + // `cloud.googleapis.com/location` label used by some Google Cloud APIs. + string location = 12; + } + + // The origin of a network activity. In a multi hop network activity, + // the origin represents the sender of the first hop. For the first hop, + // the `source` and the `origin` must have the same content. + Peer origin = 7; + + // The source of a network activity, such as starting a TCP connection. + // In a multi hop network activity, the source represents the sender of the + // last hop. + Peer source = 1; + + // The destination of a network activity, such as accepting a TCP connection. + // In a multi hop network activity, the destination represents the receiver of + // the last hop. + Peer destination = 2; + + // Represents a network request, such as an HTTP request. + Request request = 3; + + // Represents a network response, such as an HTTP response. + Response response = 4; + + // Represents a target resource that is involved with a network activity. + // If multiple resources are involved with an activity, this must be the + // primary one. + Resource resource = 5; + + // Represents an API operation that is involved to a network activity. + Api api = 6; + + // Supports extensions for advanced use cases, such as logs and metrics. + repeated google.protobuf.Any extensions = 8; +} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/context/attribute_context_pb2.py b/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/context/attribute_context_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..7d1064fb76f61fde3bd9f6260134b408fcc9777f --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/context/attribute_context_pb2.py @@ -0,0 +1,87 @@ +# -*- coding: utf-8 -*- + +# Copyright 2025 Google LLC +# +# Licensed 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. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/rpc/context/attribute_context.proto +# Protobuf Python Version: 4.25.3 +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.protobuf import any_pb2 as google_dot_protobuf_dot_any__pb2 +from google.protobuf import duration_pb2 as google_dot_protobuf_dot_duration__pb2 +from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2 +from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b"\n*google/rpc/context/attribute_context.proto\x12\x12google.rpc.context\x1a\x19google/protobuf/any.proto\x1a\x1egoogle/protobuf/duration.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto\"\x93\x10\n\x10\x41ttributeContext\x12\x39\n\x06origin\x18\x07 \x01(\x0b\x32).google.rpc.context.AttributeContext.Peer\x12\x39\n\x06source\x18\x01 \x01(\x0b\x32).google.rpc.context.AttributeContext.Peer\x12>\n\x0b\x64\x65stination\x18\x02 \x01(\x0b\x32).google.rpc.context.AttributeContext.Peer\x12=\n\x07request\x18\x03 \x01(\x0b\x32,.google.rpc.context.AttributeContext.Request\x12?\n\x08response\x18\x04 \x01(\x0b\x32-.google.rpc.context.AttributeContext.Response\x12?\n\x08resource\x18\x05 \x01(\x0b\x32-.google.rpc.context.AttributeContext.Resource\x12\x35\n\x03\x61pi\x18\x06 \x01(\x0b\x32(.google.rpc.context.AttributeContext.Api\x12(\n\nextensions\x18\x08 \x03(\x0b\x32\x14.google.protobuf.Any\x1a\xbe\x01\n\x04Peer\x12\n\n\x02ip\x18\x01 \x01(\t\x12\x0c\n\x04port\x18\x02 \x01(\x03\x12\x45\n\x06labels\x18\x06 \x03(\x0b\x32\x35.google.rpc.context.AttributeContext.Peer.LabelsEntry\x12\x11\n\tprincipal\x18\x07 \x01(\t\x12\x13\n\x0bregion_code\x18\x08 \x01(\t\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x1aL\n\x03\x41pi\x12\x0f\n\x07service\x18\x01 \x01(\t\x12\x11\n\toperation\x18\x02 \x01(\t\x12\x10\n\x08protocol\x18\x03 \x01(\t\x12\x0f\n\x07version\x18\x04 \x01(\t\x1a\x7f\n\x04\x41uth\x12\x11\n\tprincipal\x18\x01 \x01(\t\x12\x11\n\taudiences\x18\x02 \x03(\t\x12\x11\n\tpresenter\x18\x03 \x01(\t\x12'\n\x06\x63laims\x18\x04 \x01(\x0b\x32\x17.google.protobuf.Struct\x12\x15\n\raccess_levels\x18\x05 \x03(\t\x1a\xff\x02\n\x07Request\x12\n\n\x02id\x18\x01 \x01(\t\x12\x0e\n\x06method\x18\x02 \x01(\t\x12J\n\x07headers\x18\x03 \x03(\x0b\x32\x39.google.rpc.context.AttributeContext.Request.HeadersEntry\x12\x0c\n\x04path\x18\x04 \x01(\t\x12\x0c\n\x04host\x18\x05 \x01(\t\x12\x0e\n\x06scheme\x18\x06 \x01(\t\x12\r\n\x05query\x18\x07 \x01(\t\x12(\n\x04time\x18\t \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x0c\n\x04size\x18\n \x01(\x03\x12\x10\n\x08protocol\x18\x0b \x01(\t\x12\x0e\n\x06reason\x18\x0c \x01(\t\x12\x37\n\x04\x61uth\x18\r \x01(\x0b\x32).google.rpc.context.AttributeContext.Auth\x12\x0e\n\x06origin\x18\x0e \x01(\t\x1a.\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x1a\x81\x02\n\x08Response\x12\x0c\n\x04\x63ode\x18\x01 \x01(\x03\x12\x0c\n\x04size\x18\x02 \x01(\x03\x12K\n\x07headers\x18\x03 \x03(\x0b\x32:.google.rpc.context.AttributeContext.Response.HeadersEntry\x12(\n\x04time\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x32\n\x0f\x62\x61\x63kend_latency\x18\x05 \x01(\x0b\x32\x19.google.protobuf.Duration\x1a.\n\x0cHeadersEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x1a\x90\x04\n\x08Resource\x12\x0f\n\x07service\x18\x01 \x01(\t\x12\x0c\n\x04name\x18\x02 \x01(\t\x12\x0c\n\x04type\x18\x03 \x01(\t\x12I\n\x06labels\x18\x04 \x03(\x0b\x32\x39.google.rpc.context.AttributeContext.Resource.LabelsEntry\x12\x0b\n\x03uid\x18\x05 \x01(\t\x12S\n\x0b\x61nnotations\x18\x06 \x03(\x0b\x32>.google.rpc.context.AttributeContext.Resource.AnnotationsEntry\x12\x14\n\x0c\x64isplay_name\x18\x07 \x01(\t\x12/\n\x0b\x63reate_time\x18\x08 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12/\n\x0bupdate_time\x18\t \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12/\n\x0b\x64\x65lete_time\x18\n \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x0c\n\x04\x65tag\x18\x0b \x01(\t\x12\x10\n\x08location\x18\x0c \x01(\t\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x1a\x32\n\x10\x41nnotationsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x42\x88\x01\n\x16\x63om.google.rpc.contextB\x15\x41ttributeContextProtoP\x01ZUgoogle.golang.org/genproto/googleapis/rpc/context/attribute_context;attribute_contextb\x06proto3" +) + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages( + DESCRIPTOR, "google.rpc.context.attribute_context_pb2", _globals +) +if _descriptor._USE_C_DESCRIPTORS == False: + _globals["DESCRIPTOR"]._options = None + _globals[ + "DESCRIPTOR" + ]._serialized_options = b"\n\026com.google.rpc.contextB\025AttributeContextProtoP\001ZUgoogle.golang.org/genproto/googleapis/rpc/context/attribute_context;attribute_context" + _globals["_ATTRIBUTECONTEXT_PEER_LABELSENTRY"]._options = None + _globals["_ATTRIBUTECONTEXT_PEER_LABELSENTRY"]._serialized_options = b"8\001" + _globals["_ATTRIBUTECONTEXT_REQUEST_HEADERSENTRY"]._options = None + _globals["_ATTRIBUTECONTEXT_REQUEST_HEADERSENTRY"]._serialized_options = b"8\001" + _globals["_ATTRIBUTECONTEXT_RESPONSE_HEADERSENTRY"]._options = None + _globals["_ATTRIBUTECONTEXT_RESPONSE_HEADERSENTRY"]._serialized_options = b"8\001" + _globals["_ATTRIBUTECONTEXT_RESOURCE_LABELSENTRY"]._options = None + _globals["_ATTRIBUTECONTEXT_RESOURCE_LABELSENTRY"]._serialized_options = b"8\001" + _globals["_ATTRIBUTECONTEXT_RESOURCE_ANNOTATIONSENTRY"]._options = None + _globals[ + "_ATTRIBUTECONTEXT_RESOURCE_ANNOTATIONSENTRY" + ]._serialized_options = b"8\001" + _globals["_ATTRIBUTECONTEXT"]._serialized_start = 189 + _globals["_ATTRIBUTECONTEXT"]._serialized_end = 2256 + _globals["_ATTRIBUTECONTEXT_PEER"]._serialized_start = 682 + _globals["_ATTRIBUTECONTEXT_PEER"]._serialized_end = 872 + _globals["_ATTRIBUTECONTEXT_PEER_LABELSENTRY"]._serialized_start = 827 + _globals["_ATTRIBUTECONTEXT_PEER_LABELSENTRY"]._serialized_end = 872 + _globals["_ATTRIBUTECONTEXT_API"]._serialized_start = 874 + _globals["_ATTRIBUTECONTEXT_API"]._serialized_end = 950 + _globals["_ATTRIBUTECONTEXT_AUTH"]._serialized_start = 952 + _globals["_ATTRIBUTECONTEXT_AUTH"]._serialized_end = 1079 + _globals["_ATTRIBUTECONTEXT_REQUEST"]._serialized_start = 1082 + _globals["_ATTRIBUTECONTEXT_REQUEST"]._serialized_end = 1465 + _globals["_ATTRIBUTECONTEXT_REQUEST_HEADERSENTRY"]._serialized_start = 1419 + _globals["_ATTRIBUTECONTEXT_REQUEST_HEADERSENTRY"]._serialized_end = 1465 + _globals["_ATTRIBUTECONTEXT_RESPONSE"]._serialized_start = 1468 + _globals["_ATTRIBUTECONTEXT_RESPONSE"]._serialized_end = 1725 + _globals["_ATTRIBUTECONTEXT_RESPONSE_HEADERSENTRY"]._serialized_start = 1419 + _globals["_ATTRIBUTECONTEXT_RESPONSE_HEADERSENTRY"]._serialized_end = 1465 + _globals["_ATTRIBUTECONTEXT_RESOURCE"]._serialized_start = 1728 + _globals["_ATTRIBUTECONTEXT_RESOURCE"]._serialized_end = 2256 + _globals["_ATTRIBUTECONTEXT_RESOURCE_LABELSENTRY"]._serialized_start = 827 + _globals["_ATTRIBUTECONTEXT_RESOURCE_LABELSENTRY"]._serialized_end = 872 + _globals["_ATTRIBUTECONTEXT_RESOURCE_ANNOTATIONSENTRY"]._serialized_start = 2206 + _globals["_ATTRIBUTECONTEXT_RESOURCE_ANNOTATIONSENTRY"]._serialized_end = 2256 +# @@protoc_insertion_point(module_scope) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/context/attribute_context_pb2.pyi b/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/context/attribute_context_pb2.pyi new file mode 100644 index 0000000000000000000000000000000000000000..a068b06626f7e2fc85513eed6c0d782ac0e00783 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/context/attribute_context_pb2.pyi @@ -0,0 +1,313 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. + +from typing import ClassVar as _ClassVar +from typing import Iterable as _Iterable +from typing import Mapping as _Mapping +from typing import Optional as _Optional +from typing import Union as _Union + +from google.protobuf import any_pb2 as _any_pb2 +from google.protobuf import descriptor as _descriptor +from google.protobuf import duration_pb2 as _duration_pb2 +from google.protobuf import message as _message +from google.protobuf import struct_pb2 as _struct_pb2 +from google.protobuf import timestamp_pb2 as _timestamp_pb2 +from google.protobuf.internal import containers as _containers + +DESCRIPTOR: _descriptor.FileDescriptor + +class AttributeContext(_message.Message): + __slots__ = ( + "origin", + "source", + "destination", + "request", + "response", + "resource", + "api", + "extensions", + ) + class Peer(_message.Message): + __slots__ = ("ip", "port", "labels", "principal", "region_code") + class LabelsEntry(_message.Message): + __slots__ = ("key", "value") + KEY_FIELD_NUMBER: _ClassVar[int] + VALUE_FIELD_NUMBER: _ClassVar[int] + key: str + value: str + def __init__( + self, key: _Optional[str] = ..., value: _Optional[str] = ... + ) -> None: ... + + IP_FIELD_NUMBER: _ClassVar[int] + PORT_FIELD_NUMBER: _ClassVar[int] + LABELS_FIELD_NUMBER: _ClassVar[int] + PRINCIPAL_FIELD_NUMBER: _ClassVar[int] + REGION_CODE_FIELD_NUMBER: _ClassVar[int] + ip: str + port: int + labels: _containers.ScalarMap[str, str] + principal: str + region_code: str + def __init__( + self, + ip: _Optional[str] = ..., + port: _Optional[int] = ..., + labels: _Optional[_Mapping[str, str]] = ..., + principal: _Optional[str] = ..., + region_code: _Optional[str] = ..., + ) -> None: ... + + class Api(_message.Message): + __slots__ = ("service", "operation", "protocol", "version") + SERVICE_FIELD_NUMBER: _ClassVar[int] + OPERATION_FIELD_NUMBER: _ClassVar[int] + PROTOCOL_FIELD_NUMBER: _ClassVar[int] + VERSION_FIELD_NUMBER: _ClassVar[int] + service: str + operation: str + protocol: str + version: str + def __init__( + self, + service: _Optional[str] = ..., + operation: _Optional[str] = ..., + protocol: _Optional[str] = ..., + version: _Optional[str] = ..., + ) -> None: ... + + class Auth(_message.Message): + __slots__ = ("principal", "audiences", "presenter", "claims", "access_levels") + PRINCIPAL_FIELD_NUMBER: _ClassVar[int] + AUDIENCES_FIELD_NUMBER: _ClassVar[int] + PRESENTER_FIELD_NUMBER: _ClassVar[int] + CLAIMS_FIELD_NUMBER: _ClassVar[int] + ACCESS_LEVELS_FIELD_NUMBER: _ClassVar[int] + principal: str + audiences: _containers.RepeatedScalarFieldContainer[str] + presenter: str + claims: _struct_pb2.Struct + access_levels: _containers.RepeatedScalarFieldContainer[str] + def __init__( + self, + principal: _Optional[str] = ..., + audiences: _Optional[_Iterable[str]] = ..., + presenter: _Optional[str] = ..., + claims: _Optional[_Union[_struct_pb2.Struct, _Mapping]] = ..., + access_levels: _Optional[_Iterable[str]] = ..., + ) -> None: ... + + class Request(_message.Message): + __slots__ = ( + "id", + "method", + "headers", + "path", + "host", + "scheme", + "query", + "time", + "size", + "protocol", + "reason", + "auth", + "origin", + ) + class HeadersEntry(_message.Message): + __slots__ = ("key", "value") + KEY_FIELD_NUMBER: _ClassVar[int] + VALUE_FIELD_NUMBER: _ClassVar[int] + key: str + value: str + def __init__( + self, key: _Optional[str] = ..., value: _Optional[str] = ... + ) -> None: ... + + ID_FIELD_NUMBER: _ClassVar[int] + METHOD_FIELD_NUMBER: _ClassVar[int] + HEADERS_FIELD_NUMBER: _ClassVar[int] + PATH_FIELD_NUMBER: _ClassVar[int] + HOST_FIELD_NUMBER: _ClassVar[int] + SCHEME_FIELD_NUMBER: _ClassVar[int] + QUERY_FIELD_NUMBER: _ClassVar[int] + TIME_FIELD_NUMBER: _ClassVar[int] + SIZE_FIELD_NUMBER: _ClassVar[int] + PROTOCOL_FIELD_NUMBER: _ClassVar[int] + REASON_FIELD_NUMBER: _ClassVar[int] + AUTH_FIELD_NUMBER: _ClassVar[int] + ORIGIN_FIELD_NUMBER: _ClassVar[int] + id: str + method: str + headers: _containers.ScalarMap[str, str] + path: str + host: str + scheme: str + query: str + time: _timestamp_pb2.Timestamp + size: int + protocol: str + reason: str + auth: AttributeContext.Auth + origin: str + def __init__( + self, + id: _Optional[str] = ..., + method: _Optional[str] = ..., + headers: _Optional[_Mapping[str, str]] = ..., + path: _Optional[str] = ..., + host: _Optional[str] = ..., + scheme: _Optional[str] = ..., + query: _Optional[str] = ..., + time: _Optional[_Union[_timestamp_pb2.Timestamp, _Mapping]] = ..., + size: _Optional[int] = ..., + protocol: _Optional[str] = ..., + reason: _Optional[str] = ..., + auth: _Optional[_Union[AttributeContext.Auth, _Mapping]] = ..., + origin: _Optional[str] = ..., + ) -> None: ... + + class Response(_message.Message): + __slots__ = ("code", "size", "headers", "time", "backend_latency") + class HeadersEntry(_message.Message): + __slots__ = ("key", "value") + KEY_FIELD_NUMBER: _ClassVar[int] + VALUE_FIELD_NUMBER: _ClassVar[int] + key: str + value: str + def __init__( + self, key: _Optional[str] = ..., value: _Optional[str] = ... + ) -> None: ... + + CODE_FIELD_NUMBER: _ClassVar[int] + SIZE_FIELD_NUMBER: _ClassVar[int] + HEADERS_FIELD_NUMBER: _ClassVar[int] + TIME_FIELD_NUMBER: _ClassVar[int] + BACKEND_LATENCY_FIELD_NUMBER: _ClassVar[int] + code: int + size: int + headers: _containers.ScalarMap[str, str] + time: _timestamp_pb2.Timestamp + backend_latency: _duration_pb2.Duration + def __init__( + self, + code: _Optional[int] = ..., + size: _Optional[int] = ..., + headers: _Optional[_Mapping[str, str]] = ..., + time: _Optional[_Union[_timestamp_pb2.Timestamp, _Mapping]] = ..., + backend_latency: _Optional[_Union[_duration_pb2.Duration, _Mapping]] = ..., + ) -> None: ... + + class Resource(_message.Message): + __slots__ = ( + "service", + "name", + "type", + "labels", + "uid", + "annotations", + "display_name", + "create_time", + "update_time", + "delete_time", + "etag", + "location", + ) + class LabelsEntry(_message.Message): + __slots__ = ("key", "value") + KEY_FIELD_NUMBER: _ClassVar[int] + VALUE_FIELD_NUMBER: _ClassVar[int] + key: str + value: str + def __init__( + self, key: _Optional[str] = ..., value: _Optional[str] = ... + ) -> None: ... + + class AnnotationsEntry(_message.Message): + __slots__ = ("key", "value") + KEY_FIELD_NUMBER: _ClassVar[int] + VALUE_FIELD_NUMBER: _ClassVar[int] + key: str + value: str + def __init__( + self, key: _Optional[str] = ..., value: _Optional[str] = ... + ) -> None: ... + + SERVICE_FIELD_NUMBER: _ClassVar[int] + NAME_FIELD_NUMBER: _ClassVar[int] + TYPE_FIELD_NUMBER: _ClassVar[int] + LABELS_FIELD_NUMBER: _ClassVar[int] + UID_FIELD_NUMBER: _ClassVar[int] + ANNOTATIONS_FIELD_NUMBER: _ClassVar[int] + DISPLAY_NAME_FIELD_NUMBER: _ClassVar[int] + CREATE_TIME_FIELD_NUMBER: _ClassVar[int] + UPDATE_TIME_FIELD_NUMBER: _ClassVar[int] + DELETE_TIME_FIELD_NUMBER: _ClassVar[int] + ETAG_FIELD_NUMBER: _ClassVar[int] + LOCATION_FIELD_NUMBER: _ClassVar[int] + service: str + name: str + type: str + labels: _containers.ScalarMap[str, str] + uid: str + annotations: _containers.ScalarMap[str, str] + display_name: str + create_time: _timestamp_pb2.Timestamp + update_time: _timestamp_pb2.Timestamp + delete_time: _timestamp_pb2.Timestamp + etag: str + location: str + def __init__( + self, + service: _Optional[str] = ..., + name: _Optional[str] = ..., + type: _Optional[str] = ..., + labels: _Optional[_Mapping[str, str]] = ..., + uid: _Optional[str] = ..., + annotations: _Optional[_Mapping[str, str]] = ..., + display_name: _Optional[str] = ..., + create_time: _Optional[_Union[_timestamp_pb2.Timestamp, _Mapping]] = ..., + update_time: _Optional[_Union[_timestamp_pb2.Timestamp, _Mapping]] = ..., + delete_time: _Optional[_Union[_timestamp_pb2.Timestamp, _Mapping]] = ..., + etag: _Optional[str] = ..., + location: _Optional[str] = ..., + ) -> None: ... + + ORIGIN_FIELD_NUMBER: _ClassVar[int] + SOURCE_FIELD_NUMBER: _ClassVar[int] + DESTINATION_FIELD_NUMBER: _ClassVar[int] + REQUEST_FIELD_NUMBER: _ClassVar[int] + RESPONSE_FIELD_NUMBER: _ClassVar[int] + RESOURCE_FIELD_NUMBER: _ClassVar[int] + API_FIELD_NUMBER: _ClassVar[int] + EXTENSIONS_FIELD_NUMBER: _ClassVar[int] + origin: AttributeContext.Peer + source: AttributeContext.Peer + destination: AttributeContext.Peer + request: AttributeContext.Request + response: AttributeContext.Response + resource: AttributeContext.Resource + api: AttributeContext.Api + extensions: _containers.RepeatedCompositeFieldContainer[_any_pb2.Any] + def __init__( + self, + origin: _Optional[_Union[AttributeContext.Peer, _Mapping]] = ..., + source: _Optional[_Union[AttributeContext.Peer, _Mapping]] = ..., + destination: _Optional[_Union[AttributeContext.Peer, _Mapping]] = ..., + request: _Optional[_Union[AttributeContext.Request, _Mapping]] = ..., + response: _Optional[_Union[AttributeContext.Response, _Mapping]] = ..., + resource: _Optional[_Union[AttributeContext.Resource, _Mapping]] = ..., + api: _Optional[_Union[AttributeContext.Api, _Mapping]] = ..., + extensions: _Optional[_Iterable[_Union[_any_pb2.Any, _Mapping]]] = ..., + ) -> None: ... diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/context/audit_context.proto b/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/context/audit_context.proto new file mode 100644 index 0000000000000000000000000000000000000000..03c5ab9a508659be37500885a137c071f73f565c --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/context/audit_context.proto @@ -0,0 +1,48 @@ +// Copyright 2026 Google LLC +// +// Licensed 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. + +syntax = "proto3"; + +package google.rpc.context; + +import "google/protobuf/struct.proto"; + +option go_package = "google.golang.org/genproto/googleapis/rpc/context;context"; +option java_multiple_files = true; +option java_outer_classname = "AuditContextProto"; +option java_package = "com.google.rpc.context"; + +// `AuditContext` provides information that is needed for audit logging. +message AuditContext { + // Serialized audit log. + bytes audit_log = 1; + + // An API request message that is scrubbed based on the method annotation. + // This field should only be filled if audit_log field is present. + // Service Control will use this to assemble a complete log for Cloud Audit + // Logs and Google internal audit logs. + google.protobuf.Struct scrubbed_request = 2; + + // An API response message that is scrubbed based on the method annotation. + // This field should only be filled if audit_log field is present. + // Service Control will use this to assemble a complete log for Cloud Audit + // Logs and Google internal audit logs. + google.protobuf.Struct scrubbed_response = 3; + + // Number of scrubbed response items. + int32 scrubbed_response_item_count = 4; + + // Audit resource name which is scrubbed. + string target_resource = 5; +} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/context/audit_context_pb2.py b/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/context/audit_context_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..8d52ec1220582eeb9d77a0aa7bf52d6c11901045 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/context/audit_context_pb2.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- + +# Copyright 2025 Google LLC +# +# Licensed 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. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/rpc/context/audit_context.proto +# Protobuf Python Version: 4.25.3 +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2 + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b'\n&google/rpc/context/audit_context.proto\x12\x12google.rpc.context\x1a\x1cgoogle/protobuf/struct.proto"\xc7\x01\n\x0c\x41uditContext\x12\x11\n\taudit_log\x18\x01 \x01(\x0c\x12\x31\n\x10scrubbed_request\x18\x02 \x01(\x0b\x32\x17.google.protobuf.Struct\x12\x32\n\x11scrubbed_response\x18\x03 \x01(\x0b\x32\x17.google.protobuf.Struct\x12$\n\x1cscrubbed_response_item_count\x18\x04 \x01(\x05\x12\x17\n\x0ftarget_resource\x18\x05 \x01(\tBh\n\x16\x63om.google.rpc.contextB\x11\x41uditContextProtoP\x01Z9google.golang.org/genproto/googleapis/rpc/context;contextb\x06proto3' +) + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages( + DESCRIPTOR, "google.rpc.context.audit_context_pb2", _globals +) +if _descriptor._USE_C_DESCRIPTORS == False: + _globals["DESCRIPTOR"]._options = None + _globals[ + "DESCRIPTOR" + ]._serialized_options = b"\n\026com.google.rpc.contextB\021AuditContextProtoP\001Z9google.golang.org/genproto/googleapis/rpc/context;context" + _globals["_AUDITCONTEXT"]._serialized_start = 93 + _globals["_AUDITCONTEXT"]._serialized_end = 292 +# @@protoc_insertion_point(module_scope) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/context/audit_context_pb2.pyi b/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/context/audit_context_pb2.pyi new file mode 100644 index 0000000000000000000000000000000000000000..8583ec169fb2cfc55a23053e4942c9601061a571 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/context/audit_context_pb2.pyi @@ -0,0 +1,51 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. + +from typing import ClassVar as _ClassVar +from typing import Mapping as _Mapping +from typing import Optional as _Optional +from typing import Union as _Union + +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf import struct_pb2 as _struct_pb2 + +DESCRIPTOR: _descriptor.FileDescriptor + +class AuditContext(_message.Message): + __slots__ = ( + "audit_log", + "scrubbed_request", + "scrubbed_response", + "scrubbed_response_item_count", + "target_resource", + ) + AUDIT_LOG_FIELD_NUMBER: _ClassVar[int] + SCRUBBED_REQUEST_FIELD_NUMBER: _ClassVar[int] + SCRUBBED_RESPONSE_FIELD_NUMBER: _ClassVar[int] + SCRUBBED_RESPONSE_ITEM_COUNT_FIELD_NUMBER: _ClassVar[int] + TARGET_RESOURCE_FIELD_NUMBER: _ClassVar[int] + audit_log: bytes + scrubbed_request: _struct_pb2.Struct + scrubbed_response: _struct_pb2.Struct + scrubbed_response_item_count: int + target_resource: str + def __init__( + self, + audit_log: _Optional[bytes] = ..., + scrubbed_request: _Optional[_Union[_struct_pb2.Struct, _Mapping]] = ..., + scrubbed_response: _Optional[_Union[_struct_pb2.Struct, _Mapping]] = ..., + scrubbed_response_item_count: _Optional[int] = ..., + target_resource: _Optional[str] = ..., + ) -> None: ... diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/error_details.proto b/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/error_details.proto new file mode 100644 index 0000000000000000000000000000000000000000..43b7d04d2baa116ed0f943322bec1db65af66e55 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/error_details.proto @@ -0,0 +1,363 @@ +// Copyright 2026 Google LLC +// +// Licensed 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. + +syntax = "proto3"; + +package google.rpc; + +import "google/protobuf/duration.proto"; + +option go_package = "google.golang.org/genproto/googleapis/rpc/errdetails;errdetails"; +option java_multiple_files = true; +option java_outer_classname = "ErrorDetailsProto"; +option java_package = "com.google.rpc"; +option objc_class_prefix = "RPC"; + +// Describes the cause of the error with structured details. +// +// Example of an error when contacting the "pubsub.googleapis.com" API when it +// is not enabled: +// +// { "reason": "API_DISABLED" +// "domain": "googleapis.com" +// "metadata": { +// "resource": "projects/123", +// "service": "pubsub.googleapis.com" +// } +// } +// +// This response indicates that the pubsub.googleapis.com API is not enabled. +// +// Example of an error that is returned when attempting to create a Spanner +// instance in a region that is out of stock: +// +// { "reason": "STOCKOUT" +// "domain": "spanner.googleapis.com", +// "metadata": { +// "availableRegions": "us-central1,us-east2" +// } +// } +message ErrorInfo { + // The reason of the error. This is a constant value that identifies the + // proximate cause of the error. Error reasons are unique within a particular + // domain of errors. This should be at most 63 characters and match a + // regular expression of `[A-Z][A-Z0-9_]+[A-Z0-9]`, which represents + // UPPER_SNAKE_CASE. + string reason = 1; + + // The logical grouping to which the "reason" belongs. The error domain + // is typically the registered service name of the tool or product that + // generates the error. Example: "pubsub.googleapis.com". If the error is + // generated by some common infrastructure, the error domain must be a + // globally unique value that identifies the infrastructure. For Google API + // infrastructure, the error domain is "googleapis.com". + string domain = 2; + + // Additional structured details about this error. + // + // Keys must match a regular expression of `[a-z][a-zA-Z0-9-_]+` but should + // ideally be lowerCamelCase. Also, they must be limited to 64 characters in + // length. When identifying the current value of an exceeded limit, the units + // should be contained in the key, not the value. For example, rather than + // `{"instanceLimit": "100/request"}`, should be returned as, + // `{"instanceLimitPerRequest": "100"}`, if the client exceeds the number of + // instances that can be created in a single (batch) request. + map metadata = 3; +} + +// Describes when the clients can retry a failed request. Clients could ignore +// the recommendation here or retry when this information is missing from error +// responses. +// +// It's always recommended that clients should use exponential backoff when +// retrying. +// +// Clients should wait until `retry_delay` amount of time has passed since +// receiving the error response before retrying. If retrying requests also +// fail, clients should use an exponential backoff scheme to gradually increase +// the delay between retries based on `retry_delay`, until either a maximum +// number of retries have been reached or a maximum retry delay cap has been +// reached. +message RetryInfo { + // Clients should wait at least this long between retrying the same request. + google.protobuf.Duration retry_delay = 1; +} + +// Describes additional debugging info. +message DebugInfo { + // The stack trace entries indicating where the error occurred. + repeated string stack_entries = 1; + + // Additional debugging information provided by the server. + string detail = 2; +} + +// Describes how a quota check failed. +// +// For example if a daily limit was exceeded for the calling project, +// a service could respond with a QuotaFailure detail containing the project +// id and the description of the quota limit that was exceeded. If the +// calling project hasn't enabled the service in the developer console, then +// a service could respond with the project id and set `service_disabled` +// to true. +// +// Also see RetryInfo and Help types for other details about handling a +// quota failure. +message QuotaFailure { + // A message type used to describe a single quota violation. For example, a + // daily quota or a custom quota that was exceeded. + message Violation { + // The subject on which the quota check failed. + // For example, "clientip:" or "project:". + string subject = 1; + + // A description of how the quota check failed. Clients can use this + // description to find more about the quota configuration in the service's + // public documentation, or find the relevant quota limit to adjust through + // developer console. + // + // For example: "Service disabled" or "Daily Limit for read operations + // exceeded". + string description = 2; + + // The API Service from which the `QuotaFailure.Violation` orginates. In + // some cases, Quota issues originate from an API Service other than the one + // that was called. In other words, a dependency of the called API Service + // could be the cause of the `QuotaFailure`, and this field would have the + // dependency API service name. + // + // For example, if the called API is Kubernetes Engine API + // (container.googleapis.com), and a quota violation occurs in the + // Kubernetes Engine API itself, this field would be + // "container.googleapis.com". On the other hand, if the quota violation + // occurs when the Kubernetes Engine API creates VMs in the Compute Engine + // API (compute.googleapis.com), this field would be + // "compute.googleapis.com". + string api_service = 3; + + // The metric of the violated quota. A quota metric is a named counter to + // measure usage, such as API requests or CPUs. When an activity occurs in a + // service, such as Virtual Machine allocation, one or more quota metrics + // may be affected. + // + // For example, "compute.googleapis.com/cpus_per_vm_family", + // "storage.googleapis.com/internet_egress_bandwidth". + string quota_metric = 4; + + // The id of the violated quota. Also know as "limit name", this is the + // unique identifier of a quota in the context of an API service. + // + // For example, "CPUS-PER-VM-FAMILY-per-project-region". + string quota_id = 5; + + // The dimensions of the violated quota. Every non-global quota is enforced + // on a set of dimensions. While quota metric defines what to count, the + // dimensions specify for what aspects the counter should be increased. + // + // For example, the quota "CPUs per region per VM family" enforces a limit + // on the metric "compute.googleapis.com/cpus_per_vm_family" on dimensions + // "region" and "vm_family". And if the violation occurred in region + // "us-central1" and for VM family "n1", the quota_dimensions would be, + // + // { + // "region": "us-central1", + // "vm_family": "n1", + // } + // + // When a quota is enforced globally, the quota_dimensions would always be + // empty. + map quota_dimensions = 6; + + // The enforced quota value at the time of the `QuotaFailure`. + // + // For example, if the enforced quota value at the time of the + // `QuotaFailure` on the number of CPUs is "10", then the value of this + // field would reflect this quantity. + int64 quota_value = 7; + + // The new quota value being rolled out at the time of the violation. At the + // completion of the rollout, this value will be enforced in place of + // quota_value. If no rollout is in progress at the time of the violation, + // this field is not set. + // + // For example, if at the time of the violation a rollout is in progress + // changing the number of CPUs quota from 10 to 20, 20 would be the value of + // this field. + optional int64 future_quota_value = 8; + } + + // Describes all quota violations. + repeated Violation violations = 1; +} + +// Describes what preconditions have failed. +// +// For example, if an RPC failed because it required the Terms of Service to be +// acknowledged, it could list the terms of service violation in the +// PreconditionFailure message. +message PreconditionFailure { + // A message type used to describe a single precondition failure. + message Violation { + // The type of PreconditionFailure. We recommend using a service-specific + // enum type to define the supported precondition violation subjects. For + // example, "TOS" for "Terms of Service violation". + string type = 1; + + // The subject, relative to the type, that failed. + // For example, "google.com/cloud" relative to the "TOS" type would indicate + // which terms of service is being referenced. + string subject = 2; + + // A description of how the precondition failed. Developers can use this + // description to understand how to fix the failure. + // + // For example: "Terms of service not accepted". + string description = 3; + } + + // Describes all precondition violations. + repeated Violation violations = 1; +} + +// Describes violations in a client request. This error type focuses on the +// syntactic aspects of the request. +message BadRequest { + // A message type used to describe a single bad request field. + message FieldViolation { + // A path that leads to a field in the request body. The value will be a + // sequence of dot-separated identifiers that identify a protocol buffer + // field. + // + // Consider the following: + // + // message CreateContactRequest { + // message EmailAddress { + // enum Type { + // TYPE_UNSPECIFIED = 0; + // HOME = 1; + // WORK = 2; + // } + // + // optional string email = 1; + // repeated EmailType type = 2; + // } + // + // string full_name = 1; + // repeated EmailAddress email_addresses = 2; + // } + // + // In this example, in proto `field` could take one of the following values: + // + // * `full_name` for a violation in the `full_name` value + // * `email_addresses[0].email` for a violation in the `email` field of the + // first `email_addresses` message + // * `email_addresses[2].type[1]` for a violation in the second `type` + // value in the third `email_addresses` message. + // + // In JSON, the same values are represented as: + // + // * `fullName` for a violation in the `fullName` value + // * `emailAddresses[0].email` for a violation in the `email` field of the + // first `emailAddresses` message + // * `emailAddresses[2].type[1]` for a violation in the second `type` + // value in the third `emailAddresses` message. + string field = 1; + + // A description of why the request element is bad. + string description = 2; + + // The reason of the field-level error. This is a constant value that + // identifies the proximate cause of the field-level error. It should + // uniquely identify the type of the FieldViolation within the scope of the + // google.rpc.ErrorInfo.domain. This should be at most 63 + // characters and match a regular expression of `[A-Z][A-Z0-9_]+[A-Z0-9]`, + // which represents UPPER_SNAKE_CASE. + string reason = 3; + + // Provides a localized error message for field-level errors that is safe to + // return to the API consumer. + LocalizedMessage localized_message = 4; + } + + // Describes all violations in a client request. + repeated FieldViolation field_violations = 1; +} + +// Contains metadata about the request that clients can attach when filing a bug +// or providing other forms of feedback. +message RequestInfo { + // An opaque string that should only be interpreted by the service generating + // it. For example, it can be used to identify requests in the service's logs. + string request_id = 1; + + // Any data that was used to serve this request. For example, an encrypted + // stack trace that can be sent back to the service provider for debugging. + string serving_data = 2; +} + +// Describes the resource that is being accessed. +message ResourceInfo { + // A name for the type of resource being accessed, e.g. "sql table", + // "cloud storage bucket", "file", "Google calendar"; or the type URL + // of the resource: e.g. "type.googleapis.com/google.pubsub.v1.Topic". + string resource_type = 1; + + // The name of the resource being accessed. For example, a shared calendar + // name: "example.com_4fghdhgsrgh@group.calendar.google.com", if the current + // error is + // [google.rpc.Code.PERMISSION_DENIED][google.rpc.Code.PERMISSION_DENIED]. + string resource_name = 2; + + // The owner of the resource (optional). + // For example, "user:" or "project:". + string owner = 3; + + // Describes what error is encountered when accessing this resource. + // For example, updating a cloud project may require the `writer` permission + // on the developer console project. + string description = 4; +} + +// Provides links to documentation or for performing an out of band action. +// +// For example, if a quota check failed with an error indicating the calling +// project hasn't enabled the accessed service, this can contain a URL pointing +// directly to the right place in the developer console to flip the bit. +message Help { + // Describes a URL link. + message Link { + // Describes what the link offers. + string description = 1; + + // The URL of the link. + string url = 2; + } + + // URL(s) pointing to additional information on handling the current error. + repeated Link links = 1; +} + +// Provides a localized error message that is safe to return to the user +// which can be attached to an RPC error. +message LocalizedMessage { + // The locale used following the specification defined at + // https://www.rfc-editor.org/rfc/bcp/bcp47.txt. + // Examples are: "en-US", "fr-CH", "es-MX" + string locale = 1; + + // The localized error message in the above locale. + string message = 2; +} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/error_details_pb2.py b/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/error_details_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..c00419b08fd6e4c3a5b10f659e5d5812cf47e0a6 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/error_details_pb2.py @@ -0,0 +1,86 @@ +# -*- coding: utf-8 -*- + +# Copyright 2025 Google LLC +# +# Licensed 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. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/rpc/error_details.proto +# Protobuf Python Version: 4.25.3 +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.protobuf import duration_pb2 as google_dot_protobuf_dot_duration__pb2 + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b'\n\x1egoogle/rpc/error_details.proto\x12\ngoogle.rpc\x1a\x1egoogle/protobuf/duration.proto"\x93\x01\n\tErrorInfo\x12\x0e\n\x06reason\x18\x01 \x01(\t\x12\x0e\n\x06\x64omain\x18\x02 \x01(\t\x12\x35\n\x08metadata\x18\x03 \x03(\x0b\x32#.google.rpc.ErrorInfo.MetadataEntry\x1a/\n\rMetadataEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01";\n\tRetryInfo\x12.\n\x0bretry_delay\x18\x01 \x01(\x0b\x32\x19.google.protobuf.Duration"2\n\tDebugInfo\x12\x15\n\rstack_entries\x18\x01 \x03(\t\x12\x0e\n\x06\x64\x65tail\x18\x02 \x01(\t"\x8f\x03\n\x0cQuotaFailure\x12\x36\n\nviolations\x18\x01 \x03(\x0b\x32".google.rpc.QuotaFailure.Violation\x1a\xc6\x02\n\tViolation\x12\x0f\n\x07subject\x18\x01 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x02 \x01(\t\x12\x13\n\x0b\x61pi_service\x18\x03 \x01(\t\x12\x14\n\x0cquota_metric\x18\x04 \x01(\t\x12\x10\n\x08quota_id\x18\x05 \x01(\t\x12Q\n\x10quota_dimensions\x18\x06 \x03(\x0b\x32\x37.google.rpc.QuotaFailure.Violation.QuotaDimensionsEntry\x12\x13\n\x0bquota_value\x18\x07 \x01(\x03\x12\x1f\n\x12\x66uture_quota_value\x18\x08 \x01(\x03H\x00\x88\x01\x01\x1a\x36\n\x14QuotaDimensionsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x42\x15\n\x13_future_quota_value"\x95\x01\n\x13PreconditionFailure\x12=\n\nviolations\x18\x01 \x03(\x0b\x32).google.rpc.PreconditionFailure.Violation\x1a?\n\tViolation\x12\x0c\n\x04type\x18\x01 \x01(\t\x12\x0f\n\x07subject\x18\x02 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x03 \x01(\t"\xcc\x01\n\nBadRequest\x12?\n\x10\x66ield_violations\x18\x01 \x03(\x0b\x32%.google.rpc.BadRequest.FieldViolation\x1a}\n\x0e\x46ieldViolation\x12\r\n\x05\x66ield\x18\x01 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x02 \x01(\t\x12\x0e\n\x06reason\x18\x03 \x01(\t\x12\x37\n\x11localized_message\x18\x04 \x01(\x0b\x32\x1c.google.rpc.LocalizedMessage"7\n\x0bRequestInfo\x12\x12\n\nrequest_id\x18\x01 \x01(\t\x12\x14\n\x0cserving_data\x18\x02 \x01(\t"`\n\x0cResourceInfo\x12\x15\n\rresource_type\x18\x01 \x01(\t\x12\x15\n\rresource_name\x18\x02 \x01(\t\x12\r\n\x05owner\x18\x03 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x04 \x01(\t"V\n\x04Help\x12$\n\x05links\x18\x01 \x03(\x0b\x32\x15.google.rpc.Help.Link\x1a(\n\x04Link\x12\x13\n\x0b\x64\x65scription\x18\x01 \x01(\t\x12\x0b\n\x03url\x18\x02 \x01(\t"3\n\x10LocalizedMessage\x12\x0e\n\x06locale\x18\x01 \x01(\t\x12\x0f\n\x07message\x18\x02 \x01(\tBl\n\x0e\x63om.google.rpcB\x11\x45rrorDetailsProtoP\x01Z?google.golang.org/genproto/googleapis/rpc/errdetails;errdetails\xa2\x02\x03RPCb\x06proto3' +) + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages( + DESCRIPTOR, "google.rpc.error_details_pb2", _globals +) +if _descriptor._USE_C_DESCRIPTORS == False: + _globals["DESCRIPTOR"]._options = None + _globals[ + "DESCRIPTOR" + ]._serialized_options = b"\n\016com.google.rpcB\021ErrorDetailsProtoP\001Z?google.golang.org/genproto/googleapis/rpc/errdetails;errdetails\242\002\003RPC" + _globals["_ERRORINFO_METADATAENTRY"]._options = None + _globals["_ERRORINFO_METADATAENTRY"]._serialized_options = b"8\001" + _globals["_QUOTAFAILURE_VIOLATION_QUOTADIMENSIONSENTRY"]._options = None + _globals[ + "_QUOTAFAILURE_VIOLATION_QUOTADIMENSIONSENTRY" + ]._serialized_options = b"8\001" + _globals["_ERRORINFO"]._serialized_start = 79 + _globals["_ERRORINFO"]._serialized_end = 226 + _globals["_ERRORINFO_METADATAENTRY"]._serialized_start = 179 + _globals["_ERRORINFO_METADATAENTRY"]._serialized_end = 226 + _globals["_RETRYINFO"]._serialized_start = 228 + _globals["_RETRYINFO"]._serialized_end = 287 + _globals["_DEBUGINFO"]._serialized_start = 289 + _globals["_DEBUGINFO"]._serialized_end = 339 + _globals["_QUOTAFAILURE"]._serialized_start = 342 + _globals["_QUOTAFAILURE"]._serialized_end = 741 + _globals["_QUOTAFAILURE_VIOLATION"]._serialized_start = 415 + _globals["_QUOTAFAILURE_VIOLATION"]._serialized_end = 741 + _globals["_QUOTAFAILURE_VIOLATION_QUOTADIMENSIONSENTRY"]._serialized_start = 664 + _globals["_QUOTAFAILURE_VIOLATION_QUOTADIMENSIONSENTRY"]._serialized_end = 718 + _globals["_PRECONDITIONFAILURE"]._serialized_start = 744 + _globals["_PRECONDITIONFAILURE"]._serialized_end = 893 + _globals["_PRECONDITIONFAILURE_VIOLATION"]._serialized_start = 830 + _globals["_PRECONDITIONFAILURE_VIOLATION"]._serialized_end = 893 + _globals["_BADREQUEST"]._serialized_start = 896 + _globals["_BADREQUEST"]._serialized_end = 1100 + _globals["_BADREQUEST_FIELDVIOLATION"]._serialized_start = 975 + _globals["_BADREQUEST_FIELDVIOLATION"]._serialized_end = 1100 + _globals["_REQUESTINFO"]._serialized_start = 1102 + _globals["_REQUESTINFO"]._serialized_end = 1157 + _globals["_RESOURCEINFO"]._serialized_start = 1159 + _globals["_RESOURCEINFO"]._serialized_end = 1255 + _globals["_HELP"]._serialized_start = 1257 + _globals["_HELP"]._serialized_end = 1343 + _globals["_HELP_LINK"]._serialized_start = 1303 + _globals["_HELP_LINK"]._serialized_end = 1343 + _globals["_LOCALIZEDMESSAGE"]._serialized_start = 1345 + _globals["_LOCALIZEDMESSAGE"]._serialized_end = 1396 +# @@protoc_insertion_point(module_scope) diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/error_details_pb2.pyi b/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/error_details_pb2.pyi new file mode 100644 index 0000000000000000000000000000000000000000..034121e8e10d2fee8117cbfa5686effec19be56c --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/error_details_pb2.pyi @@ -0,0 +1,246 @@ +# Copyright 2025 Google LLC +# +# Licensed 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. + +from typing import ClassVar as _ClassVar +from typing import Iterable as _Iterable +from typing import Mapping as _Mapping +from typing import Optional as _Optional +from typing import Union as _Union + +from google.protobuf import descriptor as _descriptor +from google.protobuf import duration_pb2 as _duration_pb2 +from google.protobuf import message as _message +from google.protobuf.internal import containers as _containers + +DESCRIPTOR: _descriptor.FileDescriptor + +class ErrorInfo(_message.Message): + __slots__ = ("reason", "domain", "metadata") + class MetadataEntry(_message.Message): + __slots__ = ("key", "value") + KEY_FIELD_NUMBER: _ClassVar[int] + VALUE_FIELD_NUMBER: _ClassVar[int] + key: str + value: str + def __init__( + self, key: _Optional[str] = ..., value: _Optional[str] = ... + ) -> None: ... + + REASON_FIELD_NUMBER: _ClassVar[int] + DOMAIN_FIELD_NUMBER: _ClassVar[int] + METADATA_FIELD_NUMBER: _ClassVar[int] + reason: str + domain: str + metadata: _containers.ScalarMap[str, str] + def __init__( + self, + reason: _Optional[str] = ..., + domain: _Optional[str] = ..., + metadata: _Optional[_Mapping[str, str]] = ..., + ) -> None: ... + +class RetryInfo(_message.Message): + __slots__ = ("retry_delay",) + RETRY_DELAY_FIELD_NUMBER: _ClassVar[int] + retry_delay: _duration_pb2.Duration + def __init__( + self, retry_delay: _Optional[_Union[_duration_pb2.Duration, _Mapping]] = ... + ) -> None: ... + +class DebugInfo(_message.Message): + __slots__ = ("stack_entries", "detail") + STACK_ENTRIES_FIELD_NUMBER: _ClassVar[int] + DETAIL_FIELD_NUMBER: _ClassVar[int] + stack_entries: _containers.RepeatedScalarFieldContainer[str] + detail: str + def __init__( + self, + stack_entries: _Optional[_Iterable[str]] = ..., + detail: _Optional[str] = ..., + ) -> None: ... + +class QuotaFailure(_message.Message): + __slots__ = ("violations",) + class Violation(_message.Message): + __slots__ = ( + "subject", + "description", + "api_service", + "quota_metric", + "quota_id", + "quota_dimensions", + "quota_value", + "future_quota_value", + ) + class QuotaDimensionsEntry(_message.Message): + __slots__ = ("key", "value") + KEY_FIELD_NUMBER: _ClassVar[int] + VALUE_FIELD_NUMBER: _ClassVar[int] + key: str + value: str + def __init__( + self, key: _Optional[str] = ..., value: _Optional[str] = ... + ) -> None: ... + + SUBJECT_FIELD_NUMBER: _ClassVar[int] + DESCRIPTION_FIELD_NUMBER: _ClassVar[int] + API_SERVICE_FIELD_NUMBER: _ClassVar[int] + QUOTA_METRIC_FIELD_NUMBER: _ClassVar[int] + QUOTA_ID_FIELD_NUMBER: _ClassVar[int] + QUOTA_DIMENSIONS_FIELD_NUMBER: _ClassVar[int] + QUOTA_VALUE_FIELD_NUMBER: _ClassVar[int] + FUTURE_QUOTA_VALUE_FIELD_NUMBER: _ClassVar[int] + subject: str + description: str + api_service: str + quota_metric: str + quota_id: str + quota_dimensions: _containers.ScalarMap[str, str] + quota_value: int + future_quota_value: int + def __init__( + self, + subject: _Optional[str] = ..., + description: _Optional[str] = ..., + api_service: _Optional[str] = ..., + quota_metric: _Optional[str] = ..., + quota_id: _Optional[str] = ..., + quota_dimensions: _Optional[_Mapping[str, str]] = ..., + quota_value: _Optional[int] = ..., + future_quota_value: _Optional[int] = ..., + ) -> None: ... + + VIOLATIONS_FIELD_NUMBER: _ClassVar[int] + violations: _containers.RepeatedCompositeFieldContainer[QuotaFailure.Violation] + def __init__( + self, + violations: _Optional[ + _Iterable[_Union[QuotaFailure.Violation, _Mapping]] + ] = ..., + ) -> None: ... + +class PreconditionFailure(_message.Message): + __slots__ = ("violations",) + class Violation(_message.Message): + __slots__ = ("type", "subject", "description") + TYPE_FIELD_NUMBER: _ClassVar[int] + SUBJECT_FIELD_NUMBER: _ClassVar[int] + DESCRIPTION_FIELD_NUMBER: _ClassVar[int] + type: str + subject: str + description: str + def __init__( + self, + type: _Optional[str] = ..., + subject: _Optional[str] = ..., + description: _Optional[str] = ..., + ) -> None: ... + + VIOLATIONS_FIELD_NUMBER: _ClassVar[int] + violations: _containers.RepeatedCompositeFieldContainer[ + PreconditionFailure.Violation + ] + def __init__( + self, + violations: _Optional[ + _Iterable[_Union[PreconditionFailure.Violation, _Mapping]] + ] = ..., + ) -> None: ... + +class BadRequest(_message.Message): + __slots__ = ("field_violations",) + class FieldViolation(_message.Message): + __slots__ = ("field", "description", "reason", "localized_message") + FIELD_FIELD_NUMBER: _ClassVar[int] + DESCRIPTION_FIELD_NUMBER: _ClassVar[int] + REASON_FIELD_NUMBER: _ClassVar[int] + LOCALIZED_MESSAGE_FIELD_NUMBER: _ClassVar[int] + field: str + description: str + reason: str + localized_message: LocalizedMessage + def __init__( + self, + field: _Optional[str] = ..., + description: _Optional[str] = ..., + reason: _Optional[str] = ..., + localized_message: _Optional[_Union[LocalizedMessage, _Mapping]] = ..., + ) -> None: ... + + FIELD_VIOLATIONS_FIELD_NUMBER: _ClassVar[int] + field_violations: _containers.RepeatedCompositeFieldContainer[ + BadRequest.FieldViolation + ] + def __init__( + self, + field_violations: _Optional[ + _Iterable[_Union[BadRequest.FieldViolation, _Mapping]] + ] = ..., + ) -> None: ... + +class RequestInfo(_message.Message): + __slots__ = ("request_id", "serving_data") + REQUEST_ID_FIELD_NUMBER: _ClassVar[int] + SERVING_DATA_FIELD_NUMBER: _ClassVar[int] + request_id: str + serving_data: str + def __init__( + self, request_id: _Optional[str] = ..., serving_data: _Optional[str] = ... + ) -> None: ... + +class ResourceInfo(_message.Message): + __slots__ = ("resource_type", "resource_name", "owner", "description") + RESOURCE_TYPE_FIELD_NUMBER: _ClassVar[int] + RESOURCE_NAME_FIELD_NUMBER: _ClassVar[int] + OWNER_FIELD_NUMBER: _ClassVar[int] + DESCRIPTION_FIELD_NUMBER: _ClassVar[int] + resource_type: str + resource_name: str + owner: str + description: str + def __init__( + self, + resource_type: _Optional[str] = ..., + resource_name: _Optional[str] = ..., + owner: _Optional[str] = ..., + description: _Optional[str] = ..., + ) -> None: ... + +class Help(_message.Message): + __slots__ = ("links",) + class Link(_message.Message): + __slots__ = ("description", "url") + DESCRIPTION_FIELD_NUMBER: _ClassVar[int] + URL_FIELD_NUMBER: _ClassVar[int] + description: str + url: str + def __init__( + self, description: _Optional[str] = ..., url: _Optional[str] = ... + ) -> None: ... + + LINKS_FIELD_NUMBER: _ClassVar[int] + links: _containers.RepeatedCompositeFieldContainer[Help.Link] + def __init__( + self, links: _Optional[_Iterable[_Union[Help.Link, _Mapping]]] = ... + ) -> None: ... + +class LocalizedMessage(_message.Message): + __slots__ = ("locale", "message") + LOCALE_FIELD_NUMBER: _ClassVar[int] + MESSAGE_FIELD_NUMBER: _ClassVar[int] + locale: str + message: str + def __init__( + self, locale: _Optional[str] = ..., message: _Optional[str] = ... + ) -> None: ... diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/http.proto b/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/http.proto new file mode 100644 index 0000000000000000000000000000000000000000..9d97b601d9fb43f4f1653409477353555c1cd2db --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/http.proto @@ -0,0 +1,64 @@ +// Copyright 2026 Google LLC +// +// Licensed 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. + +syntax = "proto3"; + +package google.rpc; + +option go_package = "google.golang.org/genproto/googleapis/rpc/http;http"; +option java_multiple_files = true; +option java_outer_classname = "HttpProto"; +option java_package = "com.google.rpc"; +option objc_class_prefix = "RPC"; + +// Represents an HTTP request. +message HttpRequest { + // The HTTP request method. + string method = 1; + + // The HTTP request URI. + string uri = 2; + + // The HTTP request headers. The ordering of the headers is significant. + // Multiple headers with the same key may present for the request. + repeated HttpHeader headers = 3; + + // The HTTP request body. If the body is not expected, it should be empty. + bytes body = 4; +} + +// Represents an HTTP response. +message HttpResponse { + // The HTTP status code, such as 200 or 404. + int32 status = 1; + + // The HTTP reason phrase, such as "OK" or "Not Found". + string reason = 2; + + // The HTTP response headers. The ordering of the headers is significant. + // Multiple headers with the same key may present for the response. + repeated HttpHeader headers = 3; + + // The HTTP response body. If the body is not expected, it should be empty. + bytes body = 4; +} + +// Represents an HTTP header. +message HttpHeader { + // The HTTP header key. It is case insensitive. + string key = 1; + + // The HTTP header value. + string value = 2; +} diff --git a/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/http_pb2.py b/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/http_pb2.py new file mode 100644 index 0000000000000000000000000000000000000000..87d86bfa9366d78e0c6f84aeb318e393ef809a00 --- /dev/null +++ b/loan-advisor-agent/.venv/Lib/site-packages/google/rpc/http_pb2.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- + +# Copyright 2025 Google LLC +# +# Licensed 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. + +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/rpc/http.proto +# Protobuf Python Version: 4.25.3 +"""Generated protocol buffer code.""" + +from google.protobuf import descriptor as _descriptor +from google.protobuf import descriptor_pool as _descriptor_pool +from google.protobuf import symbol_database as _symbol_database +from google.protobuf.internal import builder as _builder + +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile( + b'\n\x15google/rpc/http.proto\x12\ngoogle.rpc"a\n\x0bHttpRequest\x12\x0e\n\x06method\x18\x01 \x01(\t\x12\x0b\n\x03uri\x18\x02 \x01(\t\x12\'\n\x07headers\x18\x03 \x03(\x0b\x32\x16.google.rpc.HttpHeader\x12\x0c\n\x04\x62ody\x18\x04 \x01(\x0c"e\n\x0cHttpResponse\x12\x0e\n\x06status\x18\x01 \x01(\x05\x12\x0e\n\x06reason\x18\x02 \x01(\t\x12\'\n\x07headers\x18\x03 \x03(\x0b\x32\x16.google.rpc.HttpHeader\x12\x0c\n\x04\x62ody\x18\x04 \x01(\x0c"(\n\nHttpHeader\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\tBX\n\x0e\x63om.google.rpcB\tHttpProtoP\x01Z3google.golang.org/genproto/googleapis/rpc/http;http\xa2\x02\x03RPCb\x06proto3' +) + +_globals = globals() +_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) +_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, "google.rpc.http_pb2", _globals) +if _descriptor._USE_C_DESCRIPTORS == False: + _globals["DESCRIPTOR"]._options = None + _globals[ + "DESCRIPTOR" + ]._serialized_options = b"\n\016com.google.rpcB\tHttpProtoP\001Z3google.golang.org/genproto/googleapis/rpc/http;http\242\002\003RPC" + _globals["_HTTPREQUEST"]._serialized_start = 37 + _globals["_HTTPREQUEST"]._serialized_end = 134 + _globals["_HTTPRESPONSE"]._serialized_start = 136 + _globals["_HTTPRESPONSE"]._serialized_end = 237 + _globals["_HTTPHEADER"]._serialized_start = 239 + _globals["_HTTPHEADER"]._serialized_end = 279 +# @@protoc_insertion_point(module_scope)