ai_api_unified 3.26.0__tar.gz → 3.28.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/PKG-INFO +40 -3
  2. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/README.md +39 -2
  3. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/pyproject.toml +1 -1
  4. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/__version__.py +1 -1
  5. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/ai_base.py +2 -0
  6. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/ai_google_base.py +83 -5
  7. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/ai_models_config.py +2 -1
  8. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/ai_provider_exceptions.py +9 -0
  9. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/completions/ai_google_gemini_completions.py +2 -1
  10. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/embeddings/ai_google_gemini_embeddings.py +1 -1
  11. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/middleware/guardrails.py +350 -25
  12. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/middleware/middleware_config.py +38 -0
  13. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/middleware/moderation_backends.py +21 -3
  14. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/schemas/middleware.schema.json +35 -1
  15. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/schemas/models.schema.json +35 -1
  16. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/voice/ai_voice_google.py +9 -4
  17. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/LICENSE +0 -0
  18. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/__init__.py +0 -0
  19. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/ai_anthropic_base.py +0 -0
  20. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/ai_bedrock_base.py +0 -0
  21. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/ai_completions_exceptions.py +0 -0
  22. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/ai_factory.py +0 -0
  23. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/ai_openai_base.py +0 -0
  24. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/ai_provider_error_mapping.py +0 -0
  25. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/ai_provider_loader.py +0 -0
  26. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/ai_provider_registry.py +0 -0
  27. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/classification/__init__.py +0 -0
  28. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/classification/ai_openai_decisions_classifier.py +0 -0
  29. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/classification/ai_structured_output_classifier.py +0 -0
  30. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/completions/__init__.py +0 -0
  31. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/completions/ai_anthropic_completions.py +0 -0
  32. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/completions/ai_bedrock_completions.py +0 -0
  33. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/completions/ai_fallback_completions.py +0 -0
  34. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/completions/ai_fallback_cooldown.py +0 -0
  35. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/completions/ai_google_gemini_capabilities.py +0 -0
  36. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/completions/ai_model_pin.py +0 -0
  37. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/completions/ai_openai_compatible_completions.py +0 -0
  38. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/completions/ai_openai_completions.py +0 -0
  39. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/completions/ai_openai_responses_completions.py +0 -0
  40. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/completions/ai_router_completions.py +0 -0
  41. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/config_schema.py +0 -0
  42. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/embeddings/__init__.py +0 -0
  43. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/embeddings/ai_openai_embeddings.py +0 -0
  44. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/embeddings/ai_titan_embeddings.py +0 -0
  45. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/embeddings/ai_voyage_embeddings.py +0 -0
  46. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/images/__init__.py +0 -0
  47. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/images/ai_bedrock_images.py +0 -0
  48. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/images/ai_google_gemini_images.py +0 -0
  49. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/images/ai_openai_images.py +0 -0
  50. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/middleware/__init__.py +0 -0
  51. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/middleware/cache_store.py +0 -0
  52. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/middleware/impl/__init__.py +0 -0
  53. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/middleware/impl/_presidio_redactor.py +0 -0
  54. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/middleware/impl/base_redactor.py +0 -0
  55. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/middleware/impl/custom_recognizer_factory.py +0 -0
  56. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/middleware/impl/noop_redactor.py +0 -0
  57. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/middleware/impl/presidio_log_control.py +0 -0
  58. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/middleware/middleware.py +0 -0
  59. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/middleware/observability.py +0 -0
  60. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/middleware/observability_runtime.py +0 -0
  61. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/middleware/pii_redactor.py +0 -0
  62. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/middleware/redaction_exceptions.py +0 -0
  63. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/middleware/request_cost.py +0 -0
  64. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/middleware/response_cache.py +0 -0
  65. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/pricing/__init__.py +0 -0
  66. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/pricing/model_pricing.py +0 -0
  67. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/pricing/pricing_registry.py +0 -0
  68. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/routing/__init__.py +0 -0
  69. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/routing/config_checks.py +0 -0
  70. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/routing/router_config.py +0 -0
  71. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/thinking.py +0 -0
  72. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/util/__init__.py +0 -0
  73. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/util/_lazy_pydub.py +0 -0
  74. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/util/ai_model_checker.py +0 -0
  75. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/util/ai_model_probes.py +0 -0
  76. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/util/env_settings.py +0 -0
  77. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/util/package_metadata_validation.py +0 -0
  78. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/util/utils.py +0 -0
  79. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/videos/__init__.py +0 -0
  80. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/videos/ai_bedrock_videos.py +0 -0
  81. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/videos/ai_google_gemini_videos.py +0 -0
  82. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/videos/ai_openai_videos.py +0 -0
  83. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/videos/frame_helpers.py +0 -0
  84. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/voice/__init__.py +0 -0
  85. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/voice/ai_voice_azure.py +0 -0
  86. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/voice/ai_voice_base.py +0 -0
  87. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/voice/ai_voice_elevenlabs.py +0 -0
  88. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/voice/ai_voice_factory.py +0 -0
  89. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/voice/ai_voice_google_gemini_voices.py +0 -0
  90. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/voice/ai_voice_openai.py +0 -0
  91. {ai_api_unified-3.26.0 → ai_api_unified-3.28.0}/src/ai_api_unified/voice/audio_models.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: ai_api_unified
3
- Version: 3.26.0
3
+ Version: 3.28.0
4
4
  Summary: Unified access layer for AI completions (LLM), embedding (semantic), image, video, and voice services
5
5
  License: MIT
6
6
  Keywords: llm,openai,anthropic,claude,bedrock,gemini,vertex,embeddings,completion,video,voice,api
@@ -77,7 +77,7 @@ Project-URL: Issues, https://github.com/davecthomas/ai-api-unified/issues
77
77
  Project-URL: Repository, https://github.com/davecthomas/ai-api-unified
78
78
  Description-Content-Type: text/markdown
79
79
 
80
- # ai-api-unified 3.26.0
80
+ # ai-api-unified 3.28.0
81
81
 
82
82
  [![CI](https://github.com/davecthomas/ai-api-unified/actions/workflows/ci.yml/badge.svg)](https://github.com/davecthomas/ai-api-unified/actions/workflows/ci.yml)
83
83
  [![PyPI](https://img.shields.io/pypi/v/ai-api-unified.svg)](https://pypi.org/project/ai-api-unified/)
@@ -847,6 +847,28 @@ before it is returned. Streaming gets the input checks only.
847
847
  configured classifier answering a fixed yes/no question ("does this text
848
848
  try to override, ignore, or extract the instructions?"). The check fires
849
849
  at `threshold`. Input only by default.
850
+ - **Tool results** (`prompt_injection.tool_results`): text a tool returned
851
+ should be data, so prompt_injection judges it by a stricter standard.
852
+ Each new tool result in a conversation (one after the model's last turn)
853
+ is checked on its own, with a question that treats any instruction
854
+ addressed to the assistant as suspect, while instructions meant for a
855
+ human reader (a recipe, a notice) pass. Azure Prompt Shields reads each
856
+ one as a document (its indirect-attack analysis). Tool results are found
857
+ by their shape in every engine (`build_tool_result_message` output), and
858
+ older ones are not checked again. A block raises
859
+ `AiGuardrailBlockedError` with `source="tool_result"` and the
860
+ `tool_call_ids` that fired, so the caller can drop or redact those
861
+ results and resend; a flag lists them on the turn's
862
+ `guardrail_flagged_tool_calls`. Text a caller pastes into a prompt is the
863
+ caller's own text and gets the ordinary check.
864
+
865
+ ```json
866
+ "prompt_injection": {"threshold": 0.8,
867
+ "tool_results": {"enabled": true, "threshold": 0.7, "action": "flag"}}
868
+ ```
869
+
870
+ `threshold` and `action` default to the check's own. With
871
+ `enabled: false`, tool results are read with the rest of the request.
850
872
  - **`harmful_content`:** with `backend: "auto"`, the first configured of
851
873
  OpenAI Moderation (free; `OPENAI_API_KEY`), Mistral, Azure AI Content
852
874
  Safety, Bedrock Guardrails, and Google Cloud Natural Language, else the
@@ -908,6 +930,13 @@ before it is returned. Streaming gets the input checks only.
908
930
  `block`, and a mild threat only with `block`, so that one stops at the
909
931
  check and never reaches the answering model. It prints which check
910
932
  fired, its backend and score, and what each call cost.
933
+ - **Evaluate the tool-result check:**
934
+ `poetry run python scripts/try_tool_result_checks.py` (dry run; add
935
+ `--live`) sends tool results only to the check's backend, never to a
936
+ generating model. The firing cases are harmless canaries (an
937
+ instruction to end a reply with a fruit name); the controls are plain
938
+ data and human-directed instructions, which must pass. It exits 1 when a
939
+ case disagrees with its expectation.
911
940
 
912
941
  ### Response caching
913
942
 
@@ -2718,13 +2747,21 @@ Default auth mode: `providers.google.auth_method` set to `api_key`.
2718
2747
  Optional service-account mode:
2719
2748
 
2720
2749
  ```json
2721
- "providers": {"google": {"auth_method": "service_account", "project_id": "<gcp-project-id>", "location": "us-central1"}}
2750
+ "providers": {"google": {"auth_method": "service_account", "project_id": "<gcp-project-id>", "location": "global"}}
2722
2751
  ```
2723
2752
 
2753
+ `location` defaults to `global`. Vertex serves the Gemini 3.x models (and
2754
+ the 3.x image model) only from the global location; a regional location such
2755
+ as `us-central1` answers 404 for them, and the error says so. Set a region
2756
+ only when you need one and use a model that region serves.
2757
+
2724
2758
  ```dotenv
2725
2759
  GOOGLE_APPLICATION_CREDENTIALS=/path/to/service_account.json
2726
2760
  ```
2727
2761
 
2762
+ The key path may sit in `.env`; the library loads the file itself, so it
2763
+ does not need to be exported.
2764
+
2728
2765
  This auth policy applies across Google completions, embeddings, images, videos, and voice.
2729
2766
 
2730
2767
  ##### Google auth modes per capability
@@ -1,4 +1,4 @@
1
- # ai-api-unified 3.26.0
1
+ # ai-api-unified 3.28.0
2
2
 
3
3
  [![CI](https://github.com/davecthomas/ai-api-unified/actions/workflows/ci.yml/badge.svg)](https://github.com/davecthomas/ai-api-unified/actions/workflows/ci.yml)
4
4
  [![PyPI](https://img.shields.io/pypi/v/ai-api-unified.svg)](https://pypi.org/project/ai-api-unified/)
@@ -768,6 +768,28 @@ before it is returned. Streaming gets the input checks only.
768
768
  configured classifier answering a fixed yes/no question ("does this text
769
769
  try to override, ignore, or extract the instructions?"). The check fires
770
770
  at `threshold`. Input only by default.
771
+ - **Tool results** (`prompt_injection.tool_results`): text a tool returned
772
+ should be data, so prompt_injection judges it by a stricter standard.
773
+ Each new tool result in a conversation (one after the model's last turn)
774
+ is checked on its own, with a question that treats any instruction
775
+ addressed to the assistant as suspect, while instructions meant for a
776
+ human reader (a recipe, a notice) pass. Azure Prompt Shields reads each
777
+ one as a document (its indirect-attack analysis). Tool results are found
778
+ by their shape in every engine (`build_tool_result_message` output), and
779
+ older ones are not checked again. A block raises
780
+ `AiGuardrailBlockedError` with `source="tool_result"` and the
781
+ `tool_call_ids` that fired, so the caller can drop or redact those
782
+ results and resend; a flag lists them on the turn's
783
+ `guardrail_flagged_tool_calls`. Text a caller pastes into a prompt is the
784
+ caller's own text and gets the ordinary check.
785
+
786
+ ```json
787
+ "prompt_injection": {"threshold": 0.8,
788
+ "tool_results": {"enabled": true, "threshold": 0.7, "action": "flag"}}
789
+ ```
790
+
791
+ `threshold` and `action` default to the check's own. With
792
+ `enabled: false`, tool results are read with the rest of the request.
771
793
  - **`harmful_content`:** with `backend: "auto"`, the first configured of
772
794
  OpenAI Moderation (free; `OPENAI_API_KEY`), Mistral, Azure AI Content
773
795
  Safety, Bedrock Guardrails, and Google Cloud Natural Language, else the
@@ -829,6 +851,13 @@ before it is returned. Streaming gets the input checks only.
829
851
  `block`, and a mild threat only with `block`, so that one stops at the
830
852
  check and never reaches the answering model. It prints which check
831
853
  fired, its backend and score, and what each call cost.
854
+ - **Evaluate the tool-result check:**
855
+ `poetry run python scripts/try_tool_result_checks.py` (dry run; add
856
+ `--live`) sends tool results only to the check's backend, never to a
857
+ generating model. The firing cases are harmless canaries (an
858
+ instruction to end a reply with a fruit name); the controls are plain
859
+ data and human-directed instructions, which must pass. It exits 1 when a
860
+ case disagrees with its expectation.
832
861
 
833
862
  ### Response caching
834
863
 
@@ -2639,13 +2668,21 @@ Default auth mode: `providers.google.auth_method` set to `api_key`.
2639
2668
  Optional service-account mode:
2640
2669
 
2641
2670
  ```json
2642
- "providers": {"google": {"auth_method": "service_account", "project_id": "<gcp-project-id>", "location": "us-central1"}}
2671
+ "providers": {"google": {"auth_method": "service_account", "project_id": "<gcp-project-id>", "location": "global"}}
2643
2672
  ```
2644
2673
 
2674
+ `location` defaults to `global`. Vertex serves the Gemini 3.x models (and
2675
+ the 3.x image model) only from the global location; a regional location such
2676
+ as `us-central1` answers 404 for them, and the error says so. Set a region
2677
+ only when you need one and use a model that region serves.
2678
+
2645
2679
  ```dotenv
2646
2680
  GOOGLE_APPLICATION_CREDENTIALS=/path/to/service_account.json
2647
2681
  ```
2648
2682
 
2683
+ The key path may sit in `.env`; the library loads the file itself, so it
2684
+ does not need to be exported.
2685
+
2649
2686
  This auth policy applies across Google completions, embeddings, images, videos, and voice.
2650
2687
 
2651
2688
  ##### Google auth modes per capability
@@ -36,7 +36,7 @@
36
36
  [project]
37
37
  name = "ai_api_unified"
38
38
 
39
- version = "3.26.0" # keep in sync with src/ai_api_unified/__version__.py and the README.md title
39
+ version = "3.28.0" # keep in sync with src/ai_api_unified/__version__.py and the README.md title
40
40
  description = "Unified access layer for AI completions (LLM), embedding (semantic), image, video, and voice services"
41
41
  authors = [{ name = "Dave Thomas", email = "davidcthomas@gmail.com" }]
42
42
  license = "MIT"
@@ -9,4 +9,4 @@ from __future__ import annotations
9
9
 
10
10
  __all__: list[str] = ["__version__"]
11
11
 
12
- __version__: str = "3.26.0"
12
+ __version__: str = "3.28.0"
@@ -767,6 +767,8 @@ class AITurnResult(BaseModel):
767
767
  usd_saved: Decimal | None = None
768
768
  # Guardrail checks that flagged this call (input or output), by name.
769
769
  guardrail_flags: list[str] = Field(default_factory=list)
770
+ # Tool calls whose results a flagging check fired on, by id.
771
+ guardrail_flagged_tool_calls: list[str] = Field(default_factory=list)
770
772
 
771
773
 
772
774
  class AIStructuredOutputResult(BaseModel):
@@ -23,11 +23,20 @@ from google.genai import pagers
23
23
 
24
24
  from ai_api_unified.ai_provider_exceptions import (
25
25
  AiFallbackReason,
26
+ AiProviderConfigurationValueError,
26
27
  classify_fallback_reason_by_status,
27
28
  )
28
29
  from ai_api_unified.util.env_settings import EnvSettings
29
30
 
30
31
  GOOGLE_BASE_URL_OVERRIDE_SETTING: str = "GOOGLE_GEMINI_BASE_URL_OVERRIDE"
32
+ GOOGLE_CREDENTIALS_FILE_SETTING: str = "GOOGLE_APPLICATION_CREDENTIALS"
33
+ GOOGLE_CLOUD_PLATFORM_SCOPE: str = "https://www.googleapis.com/auth/cloud-platform"
34
+ # Vertex location when GOOGLE_LOCATION is unset. Gemini 3.x models (and the
35
+ # 3.x image model) are served only from the global endpoint; a regional
36
+ # location such as us-central1 answers 404 on generateContent for them
37
+ # while models.get still answers 200 (probed 2026-10-21, issue #45).
38
+ GOOGLE_LOCATION_GLOBAL: str = "global"
39
+ DEFAULT_GOOGLE_LOCATION: str = GOOGLE_LOCATION_GLOBAL
31
40
 
32
41
  T = TypeVar("T")
33
42
 
@@ -171,6 +180,66 @@ class AIGoogleBase:
171
180
  GOOGLE_AUTH_METHOD_API_KEY: ClassVar[str] = "api_key"
172
181
  GOOGLE_AUTH_METHOD_SERVICE_ACCOUNT: ClassVar[str] = "service_account"
173
182
 
183
+ def _load_service_account_credentials(self, env_settings: EnvSettings) -> Any:
184
+ """
185
+ Credentials from the key file GOOGLE_APPLICATION_CREDENTIALS names,
186
+ read through EnvSettings so a path set in `.env` works
187
+ the same as an exported one. None when unset, so the Google client
188
+ falls back to Application Default Credentials.
189
+
190
+ Raises:
191
+ AiProviderConfigurationValueError: The path is set but the file is
192
+ missing or is not a service account key.
193
+ """
194
+ str_path: str = str(
195
+ env_settings.get_setting(GOOGLE_CREDENTIALS_FILE_SETTING, "") or ""
196
+ ).strip()
197
+ if not str_path:
198
+ # Early return: no key file, so the client uses ADC.
199
+ return None
200
+ from google.oauth2 import service_account
201
+
202
+ try:
203
+ credentials: Any = service_account.Credentials.from_service_account_file(
204
+ str_path, scopes=[GOOGLE_CLOUD_PLATFORM_SCOPE]
205
+ )
206
+ except (OSError, ValueError, KeyError) as error:
207
+ raise AiProviderConfigurationValueError(
208
+ f"{GOOGLE_CREDENTIALS_FILE_SETTING}={str_path} could not be loaded "
209
+ f"as a service account key ({error.__class__.__name__}). Point it "
210
+ "at the JSON key file downloaded for the service account."
211
+ ) from error
212
+ # Normal return with the key file's credentials.
213
+ return credentials
214
+
215
+ def _vertex_location_hint(self, status_code: int | None) -> str:
216
+ """
217
+ Advice appended to a 404 from Vertex in a regional location, where
218
+ the model exists but is not served; empty otherwise.
219
+ """
220
+ if status_code != 404:
221
+ # Early return: only a missing model gets the hint.
222
+ return ""
223
+ env_settings: EnvSettings = EnvSettings()
224
+ if (
225
+ self._resolve_google_auth_method(env_settings)
226
+ == self.GOOGLE_AUTH_METHOD_API_KEY
227
+ ):
228
+ # Early return: the Gemini API has no locations.
229
+ return ""
230
+ str_location: str = str(
231
+ env_settings.get_setting("GOOGLE_LOCATION", None) or DEFAULT_GOOGLE_LOCATION
232
+ ).strip()
233
+ if str_location.lower() == GOOGLE_LOCATION_GLOBAL:
234
+ # Early return: already on the global endpoint.
235
+ return ""
236
+ # Normal return with the advice.
237
+ return (
238
+ f" Vertex location {str_location!r} does not serve this model; "
239
+ "Gemini 3.x models are served only from the global location. Set "
240
+ "providers.google.location (GOOGLE_LOCATION) to 'global'."
241
+ )
242
+
174
243
  def _resolve_google_auth_method(
175
244
  self,
176
245
  env_settings: EnvSettings,
@@ -237,6 +306,11 @@ class AIGoogleBase:
237
306
  str_env_key=GOOGLE_BASE_URL_OVERRIDE_SETTING,
238
307
  str_explicit=base_url,
239
308
  )
309
+ credentials: Any = (
310
+ None
311
+ if auth_method == self.GOOGLE_AUTH_METHOD_API_KEY
312
+ else self._load_service_account_credentials(env_settings)
313
+ )
240
314
  dict_client_kwargs: dict[str, Any] = {}
241
315
  if str_base_url:
242
316
  dict_client_kwargs["http_options"] = genai.types.HttpOptions(
@@ -257,13 +331,15 @@ class AIGoogleBase:
257
331
  )
258
332
  else:
259
333
  project_id: str = env_settings.get_setting("GOOGLE_PROJECT_ID", "")
260
- location: str = env_settings.get_setting(
261
- "GOOGLE_LOCATION", "us-central1"
334
+ location: str = (
335
+ env_settings.get_setting("GOOGLE_LOCATION", None)
336
+ or DEFAULT_GOOGLE_LOCATION
262
337
  )
263
338
  client = genai.Client(
264
339
  vertexai=True,
265
340
  project=project_id,
266
341
  location=location,
342
+ credentials=credentials,
267
343
  **dict_client_kwargs,
268
344
  )
269
345
 
@@ -610,12 +686,13 @@ class AIGoogleBase:
610
686
  ) from gemini_error
611
687
 
612
688
  message_text_gemini: str = str(gemini_error)
689
+ str_hint: str = self._vertex_location_hint(status_code)
613
690
  if _cannot_recover(status_code, message_text_gemini):
614
691
  # Early exit: quota or model gone, so backoff is wasted.
615
692
  # Wrapped like the non-retryable branch below, so the
616
693
  # public exception type does not change.
617
694
  raise RuntimeError(
618
- f"Google Gemini error{f' ({status_code})' if status_code is not None else ''}: {gemini_error}"
695
+ f"Google Gemini error{f' ({status_code})' if status_code is not None else ''}: {gemini_error}{str_hint}"
619
696
  ) from gemini_error
620
697
  if (
621
698
  status_code in self.retryable_http_status_codes
@@ -629,12 +706,13 @@ class AIGoogleBase:
629
706
  continue
630
707
 
631
708
  _LOGGER.error(
632
- "Non-retryable Google Gemini error%s: %s",
709
+ "Non-retryable Google Gemini error%s: %s%s",
633
710
  f" ({status_code})" if status_code is not None else "",
634
711
  gemini_error,
712
+ str_hint,
635
713
  )
636
714
  raise RuntimeError(
637
- f"Google Gemini error{f' ({status_code})' if status_code is not None else ''}: {gemini_error}"
715
+ f"Google Gemini error{f' ({status_code})' if status_code is not None else ''}: {gemini_error}{str_hint}"
638
716
  ) from gemini_error
639
717
 
640
718
  except gerr.APIError as gemini_api_error:
@@ -260,7 +260,8 @@ class AIGoogleProviderSettings(BaseModel):
260
260
  model_config = ConfigDict(frozen=True, extra="forbid")
261
261
 
262
262
  auth_method: Literal["api_key", "service_account"] | None = None
263
- # Vertex AI project and region, for service-account auth.
263
+ # Vertex AI project and location, for service-account auth. The location
264
+ # defaults to "global", the only one serving Gemini 3.x models.
264
265
  project_id: str | None = None
265
266
  location: str | None = None
266
267
  base_url: str | None = None
@@ -192,6 +192,11 @@ class AiGuardrailBlockedError(AiProviderRuntimeError):
192
192
  backend: What made the decision (rules, classifier, openai_moderation).
193
193
  score: The backend's score or probability, when it reports one.
194
194
  categories: Category labels the backend reported, when any.
195
+ source: "request" (the caller's own text) or "tool_result" (text a
196
+ tool returned, sent back in a conversation).
197
+ tool_call_ids: For a tool_result block, the ids of the tool calls
198
+ whose results fired, so the caller can drop or redact them and
199
+ send the turn again.
195
200
  """
196
201
 
197
202
  def __init__(
@@ -203,6 +208,8 @@ class AiGuardrailBlockedError(AiProviderRuntimeError):
203
208
  backend: str,
204
209
  score: float | None = None,
205
210
  categories: tuple[str, ...] = (),
211
+ source: str = "request",
212
+ tool_call_ids: tuple[str, ...] = (),
206
213
  ) -> None:
207
214
  super().__init__(message)
208
215
  self.check: str = check
@@ -210,6 +217,8 @@ class AiGuardrailBlockedError(AiProviderRuntimeError):
210
217
  self.backend: str = backend
211
218
  self.score: float | None = score
212
219
  self.categories: tuple[str, ...] = categories
220
+ self.source: str = source
221
+ self.tool_call_ids: tuple[str, ...] = tool_call_ids
213
222
  # A guardrail decision is final; nothing about it says another
214
223
  # model would answer differently.
215
224
  self.fallback_reason: AiFallbackReason | None = None
@@ -1192,7 +1192,8 @@ class GoogleGeminiCompletions(AIBaseCompletions, AIGoogleBase):
1192
1192
  int_status, str(candidate)
1193
1193
  )
1194
1194
  raise AiProviderRequestError(
1195
- f"Google Gemini request failed: {candidate}",
1195
+ f"Google Gemini request failed: {candidate}"
1196
+ f"{self._vertex_location_hint(int_status)}",
1196
1197
  status_code=int_status,
1197
1198
  provider_engine=self.PROVIDER_ENGINE_TOKEN,
1198
1199
  fallback_reason=reason,
@@ -16,7 +16,7 @@ Environment Variables:
16
16
  GOOGLE_AUTH_METHOD: api_key | service_account
17
17
  GOOGLE_APPLICATION_CREDENTIALS: Path to service account JSON credentials.
18
18
  GOOGLE_PROJECT_ID: Google Cloud project ID used for Vertex AI requests.
19
- GOOGLE_LOCATION: (optional) Vertex AI region, defaults to us-central1.
19
+ GOOGLE_LOCATION: (optional) Vertex AI location, defaults to global.
20
20
 
21
21
  Model/runtime tuning:
22
22
  EMBEDDING_MODEL_NAME: (optional) Override default model 'gemini-embedding-001'.