langchain-google-genai 3.0.1__tar.gz → 3.0.2__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 (53) hide show
  1. langchain_google_genai-3.0.2/.gitignore +1 -0
  2. langchain_google_genai-3.0.2/Makefile +70 -0
  3. langchain_google_genai-3.0.2/PKG-INFO +50 -0
  4. langchain_google_genai-3.0.2/README.md +30 -0
  5. langchain_google_genai-3.0.2/langchain_google_genai/__init__.py +93 -0
  6. {langchain_google_genai-3.0.1 → langchain_google_genai-3.0.2}/langchain_google_genai/_common.py +77 -65
  7. {langchain_google_genai-3.0.1 → langchain_google_genai-3.0.2}/langchain_google_genai/_compat.py +7 -7
  8. {langchain_google_genai-3.0.1 → langchain_google_genai-3.0.2}/langchain_google_genai/_enums.py +1 -1
  9. {langchain_google_genai-3.0.1 → langchain_google_genai-3.0.2}/langchain_google_genai/_function_utils.py +37 -86
  10. {langchain_google_genai-3.0.1 → langchain_google_genai-3.0.2}/langchain_google_genai/_genai_extension.py +69 -69
  11. {langchain_google_genai-3.0.1 → langchain_google_genai-3.0.2}/langchain_google_genai/_image_utils.py +11 -9
  12. {langchain_google_genai-3.0.1 → langchain_google_genai-3.0.2}/langchain_google_genai/chat_models.py +692 -709
  13. {langchain_google_genai-3.0.1 → langchain_google_genai-3.0.2}/langchain_google_genai/embeddings.py +126 -108
  14. {langchain_google_genai-3.0.1 → langchain_google_genai-3.0.2}/langchain_google_genai/genai_aqa.py +17 -16
  15. {langchain_google_genai-3.0.1 → langchain_google_genai-3.0.2}/langchain_google_genai/google_vector_store.py +80 -71
  16. {langchain_google_genai-3.0.1 → langchain_google_genai-3.0.2}/langchain_google_genai/llms.py +14 -12
  17. langchain_google_genai-3.0.2/pyproject.toml +153 -0
  18. langchain_google_genai-3.0.2/scripts/check_imports.py +17 -0
  19. langchain_google_genai-3.0.2/scripts/lint_imports.sh +17 -0
  20. {langchain_google_genai-3.0.1 → langchain_google_genai-3.0.2}/tests/integration_tests/test_chat_models.py +73 -51
  21. langchain_google_genai-3.0.2/tests/integration_tests/test_structured_output_integration.py +316 -0
  22. {langchain_google_genai-3.0.1 → langchain_google_genai-3.0.2}/tests/unit_tests/test_chat_models.py +541 -34
  23. langchain_google_genai-3.0.2/tests/unit_tests/test_common.py +68 -0
  24. {langchain_google_genai-3.0.1 → langchain_google_genai-3.0.2}/tests/unit_tests/test_embeddings.py +26 -0
  25. {langchain_google_genai-3.0.1 → langchain_google_genai-3.0.2}/tests/unit_tests/test_function_utils.py +18 -75
  26. langchain_google_genai-3.0.2/uv.lock +2080 -0
  27. langchain_google_genai-3.0.1/PKG-INFO +0 -265
  28. langchain_google_genai-3.0.1/README.md +0 -250
  29. langchain_google_genai-3.0.1/langchain_google_genai/__init__.py +0 -93
  30. langchain_google_genai-3.0.1/pyproject.toml +0 -138
  31. langchain_google_genai-3.0.1/tests/unit_tests/test_common.py +0 -31
  32. {langchain_google_genai-3.0.1 → langchain_google_genai-3.0.2}/LICENSE +0 -0
  33. {langchain_google_genai-3.0.1 → langchain_google_genai-3.0.2}/langchain_google_genai/py.typed +0 -0
  34. {langchain_google_genai-3.0.1 → langchain_google_genai-3.0.2}/tests/__init__.py +0 -0
  35. {langchain_google_genai-3.0.1 → langchain_google_genai-3.0.2}/tests/conftest.py +0 -0
  36. {langchain_google_genai-3.0.1 → langchain_google_genai-3.0.2}/tests/integration_tests/.env.example +0 -0
  37. {langchain_google_genai-3.0.1 → langchain_google_genai-3.0.2}/tests/integration_tests/__init__.py +0 -0
  38. {langchain_google_genai-3.0.1 → langchain_google_genai-3.0.2}/tests/integration_tests/terraform/main.tf +0 -0
  39. {langchain_google_genai-3.0.1 → langchain_google_genai-3.0.2}/tests/integration_tests/test_callbacks.py +0 -0
  40. {langchain_google_genai-3.0.1 → langchain_google_genai-3.0.2}/tests/integration_tests/test_compile.py +0 -0
  41. {langchain_google_genai-3.0.1 → langchain_google_genai-3.0.2}/tests/integration_tests/test_embeddings.py +0 -0
  42. {langchain_google_genai-3.0.1 → langchain_google_genai-3.0.2}/tests/integration_tests/test_function_call.py +0 -0
  43. {langchain_google_genai-3.0.1 → langchain_google_genai-3.0.2}/tests/integration_tests/test_llms.py +0 -0
  44. {langchain_google_genai-3.0.1 → langchain_google_genai-3.0.2}/tests/integration_tests/test_standard.py +0 -0
  45. {langchain_google_genai-3.0.1 → langchain_google_genai-3.0.2}/tests/integration_tests/test_tools.py +0 -0
  46. {langchain_google_genai-3.0.1 → langchain_google_genai-3.0.2}/tests/unit_tests/__init__.py +0 -0
  47. {langchain_google_genai-3.0.1 → langchain_google_genai-3.0.2}/tests/unit_tests/__snapshots__/test_standard.ambr +0 -0
  48. {langchain_google_genai-3.0.1 → langchain_google_genai-3.0.2}/tests/unit_tests/test_chat_models_protobuf_fix.py +0 -0
  49. {langchain_google_genai-3.0.1 → langchain_google_genai-3.0.2}/tests/unit_tests/test_genai_aqa.py +0 -0
  50. {langchain_google_genai-3.0.1 → langchain_google_genai-3.0.2}/tests/unit_tests/test_google_vector_store.py +0 -0
  51. {langchain_google_genai-3.0.1 → langchain_google_genai-3.0.2}/tests/unit_tests/test_imports.py +0 -0
  52. {langchain_google_genai-3.0.1 → langchain_google_genai-3.0.2}/tests/unit_tests/test_llms.py +0 -0
  53. {langchain_google_genai-3.0.1 → langchain_google_genai-3.0.2}/tests/unit_tests/test_standard.py +0 -0
@@ -0,0 +1 @@
1
+ __pycache__
@@ -0,0 +1,70 @@
1
+ .PHONY: all format lint test tests integration_tests help
2
+
3
+ # Default target executed when no arguments are given to make.
4
+ all: help
5
+
6
+ .EXPORT_ALL_VARIABLES:
7
+ UV_FROZEN = true
8
+
9
+ # Define a variable for the test file path.
10
+ TEST_FILE ?= tests/unit_tests/
11
+
12
+ integration_test integration_tests: TEST_FILE = tests/integration_tests/
13
+
14
+ test tests:
15
+ uv run --group test pytest --disable-socket --allow-unix-socket $(TEST_FILE)
16
+
17
+ integration_test integration_tests:
18
+ uv run --group test --group test_integration pytest --retries 3 --retry-delay 1 $(TEST_FILE)
19
+
20
+ check_imports: $(shell find langchain_google_genai -name '*.py')
21
+ uv run --all-groups python ./scripts/check_imports.py $^
22
+
23
+ test_watch:
24
+ uv run ptw --snapshot-update --now . -- -vv $(TEST_FILE)
25
+
26
+ # Run unit tests and generate a coverage report.
27
+ coverage:
28
+ uv run pytest --cov \
29
+ --cov-config=.coveragerc \
30
+ --cov-report xml \
31
+ --cov-report term-missing:skip-covered \
32
+ $(TEST_FILE)
33
+
34
+ ######################
35
+ # LINTING AND FORMATTING
36
+ ######################
37
+
38
+ # Define a variable for Python and notebook files.
39
+ PYTHON_FILES=.
40
+ MYPY_CACHE=.mypy_cache
41
+ lint format: PYTHON_FILES=.
42
+ lint_diff format_diff: PYTHON_FILES=$(shell git diff --name-only --diff-filter=d main | grep -E '\.py$$|\.ipynb$$')
43
+ lint_package: PYTHON_FILES=langchain_google_genai
44
+ lint_tests: PYTHON_FILES=tests
45
+ lint_tests: MYPY_CACHE=.mypy_cache_test
46
+
47
+ lint lint_diff lint_package lint_tests:
48
+ ./scripts/lint_imports.sh
49
+ [ "$(PYTHON_FILES)" = "" ] || uv run --all-groups ruff check $(PYTHON_FILES)
50
+ [ "$(PYTHON_FILES)" = "" ] || uv run --all-groups ruff format $(PYTHON_FILES) --diff
51
+ [ "$(PYTHON_FILES)" = "" ] || uv run --all-groups ruff check --select I $(PYTHON_FILES)
52
+ [ "$(PYTHON_FILES)" = "" ] || mkdir -p $(MYPY_CACHE) && uv run --all-groups mypy $(PYTHON_FILES) --cache-dir $(MYPY_CACHE)
53
+
54
+ format format_diff:
55
+ [ "$(PYTHON_FILES)" = "" ] || uv run --all-groups ruff format $(PYTHON_FILES)
56
+ [ "$(PYTHON_FILES)" = "" ] || uv run --all-groups ruff check --fix $(PYTHON_FILES)
57
+
58
+ ######################
59
+ # HELP
60
+ ######################
61
+
62
+ help:
63
+ @echo '----'
64
+ @echo 'check_imports - check imports'
65
+ @echo 'format - run code formatters'
66
+ @echo 'lint - run linters'
67
+ @echo 'test - run unit tests'
68
+ @echo 'tests - run unit tests'
69
+ @echo 'integration_test - run integration tests(NOTE: "export GOOGLE_API_KEY=..." is needed.)'
70
+ @echo 'test TEST_FILE=<test_file> - run all tests in file'
@@ -0,0 +1,50 @@
1
+ Metadata-Version: 2.4
2
+ Name: langchain-google-genai
3
+ Version: 3.0.2
4
+ Summary: An integration package connecting Google's genai package and LangChain
5
+ Project-URL: Homepage, https://docs.langchain.com/oss/python/integrations/providers/google
6
+ Project-URL: Documentation, https://reference.langchain.com/python/integrations/langchain_google_genai/
7
+ Project-URL: Source, https://github.com/langchain-ai/langchain-google/tree/master/libs/genai
8
+ Project-URL: Changelog, https://github.com/langchain-ai/langchain-google/releases?q=%22genai%22
9
+ Project-URL: Twitter, https://x.com/LangChainAI
10
+ Project-URL: Slack, https://www.langchain.com/join-community
11
+ Project-URL: Reddit, https://www.reddit.com/r/LangChain/
12
+ License: MIT
13
+ License-File: LICENSE
14
+ Requires-Python: <4.0.0,>=3.10.0
15
+ Requires-Dist: filetype<2.0.0,>=1.2.0
16
+ Requires-Dist: google-ai-generativelanguage<1.0.0,>=0.7.0
17
+ Requires-Dist: langchain-core<2.0.0,>=1.0.0
18
+ Requires-Dist: pydantic<3.0.0,>=2.0.0
19
+ Description-Content-Type: text/markdown
20
+
21
+ # langchain-google-genai
22
+
23
+ [![PyPI - Version](https://img.shields.io/pypi/v/langchain-google-genai?label=%20)](https://pypi.org/project/langchain-google-genai/#history)
24
+ [![PyPI - License](https://img.shields.io/pypi/l/langchain-google-genai)](https://opensource.org/licenses/MIT)
25
+ [![PyPI - Downloads](https://img.shields.io/pepy/dt/langchain-google-genai)](https://pypistats.org/packages/langchain-google-genai)
26
+ [![Twitter](https://img.shields.io/twitter/url/https/twitter.com/langchainai.svg?style=social&label=Follow%20%40LangChainAI)](https://twitter.com/langchainai)
27
+
28
+ Looking for the JS/TS version? Check out [LangChain.js](https://github.com/langchain-ai/langchainjs).
29
+
30
+ This package provides access to Google Gemini's chat, vision, embeddings, and other capabilities within the LangChain ecosystem.
31
+
32
+ ## Quick Install
33
+
34
+ ```bash
35
+ pip install langchain-google-genai
36
+ ```
37
+
38
+ ## 📖 Documentation
39
+
40
+ For full documentation, see the [API reference](https://reference.langchain.com/python/integrations/langchain_google_genai/). For conceptual guides, tutorials, and examples on using these classes, see the [LangChain Docs](https://docs.langchain.com/oss/python/integrations/providers/google#google-generative-ai).
41
+
42
+ ## 📕 Releases & Versioning
43
+
44
+ See our [Releases](https://docs.langchain.com/oss/python/release-policy) and [Versioning](https://docs.langchain.com/oss/python/versioning) policies.
45
+
46
+ ## 💁 Contributing
47
+
48
+ As an open-source project in a rapidly developing field, we are extremely open to contributions, whether it be in the form of a new feature, improved infrastructure, or better documentation.
49
+
50
+ For detailed information on how to contribute, see the [Contributing Guide](https://docs.langchain.com/oss/python/contributing/overview).
@@ -0,0 +1,30 @@
1
+ # langchain-google-genai
2
+
3
+ [![PyPI - Version](https://img.shields.io/pypi/v/langchain-google-genai?label=%20)](https://pypi.org/project/langchain-google-genai/#history)
4
+ [![PyPI - License](https://img.shields.io/pypi/l/langchain-google-genai)](https://opensource.org/licenses/MIT)
5
+ [![PyPI - Downloads](https://img.shields.io/pepy/dt/langchain-google-genai)](https://pypistats.org/packages/langchain-google-genai)
6
+ [![Twitter](https://img.shields.io/twitter/url/https/twitter.com/langchainai.svg?style=social&label=Follow%20%40LangChainAI)](https://twitter.com/langchainai)
7
+
8
+ Looking for the JS/TS version? Check out [LangChain.js](https://github.com/langchain-ai/langchainjs).
9
+
10
+ This package provides access to Google Gemini's chat, vision, embeddings, and other capabilities within the LangChain ecosystem.
11
+
12
+ ## Quick Install
13
+
14
+ ```bash
15
+ pip install langchain-google-genai
16
+ ```
17
+
18
+ ## 📖 Documentation
19
+
20
+ For full documentation, see the [API reference](https://reference.langchain.com/python/integrations/langchain_google_genai/). For conceptual guides, tutorials, and examples on using these classes, see the [LangChain Docs](https://docs.langchain.com/oss/python/integrations/providers/google#google-generative-ai).
21
+
22
+ ## 📕 Releases & Versioning
23
+
24
+ See our [Releases](https://docs.langchain.com/oss/python/release-policy) and [Versioning](https://docs.langchain.com/oss/python/versioning) policies.
25
+
26
+ ## 💁 Contributing
27
+
28
+ As an open-source project in a rapidly developing field, we are extremely open to contributions, whether it be in the form of a new feature, improved infrastructure, or better documentation.
29
+
30
+ For detailed information on how to contribute, see the [Contributing Guide](https://docs.langchain.com/oss/python/contributing/overview).
@@ -0,0 +1,93 @@
1
+ """LangChain Google Generative AI Integration (GenAI).
2
+
3
+ This module integrates Google's Generative AI models, specifically the Gemini series,
4
+ with the LangChain framework. It provides classes for interacting with chat models and
5
+ generating embeddings, leveraging Google's advanced AI capabilities.
6
+
7
+ **Chat Models**
8
+
9
+ The `ChatGoogleGenerativeAI` class is the primary interface for interacting with
10
+ Google's Gemini chat models. It allows users to send and receive messages using a
11
+ specified Gemini model, suitable for various conversational AI applications.
12
+
13
+ **LLMs**
14
+
15
+ The `GoogleGenerativeAI` class is the primary interface for interacting with Google's
16
+ Gemini LLMs. It allows users to generate text using a specified Gemini model.
17
+
18
+ **Embeddings**
19
+
20
+ The `GoogleGenerativeAIEmbeddings` class provides functionalities to generate embeddings
21
+ using Google's models. These embeddings can be used for a range of NLP tasks, including
22
+ semantic analysis, similarity comparisons, and more.
23
+
24
+ **Using Chat Models**
25
+
26
+ After setting up your environment with the required API key, you can interact with the
27
+ Google Gemini models.
28
+
29
+ ```python
30
+ from langchain_google_genai import ChatGoogleGenerativeAI
31
+
32
+ llm = ChatGoogleGenerativeAI(model="gemini-2.5-pro")
33
+ llm.invoke("Sing a ballad of LangChain.")
34
+ ```
35
+
36
+ **Using LLMs**
37
+
38
+ The package also supports generating text with Google's models.
39
+
40
+ ```python
41
+ from langchain_google_genai import GoogleGenerativeAI
42
+
43
+ llm = GoogleGenerativeAI(model="gemini-2.5-pro")
44
+ llm.invoke("Once upon a time, a library called LangChain")
45
+ ```
46
+
47
+ **Embedding Generation**
48
+
49
+ The package also supports creating embeddings with Google's models, useful for textual
50
+ similarity and other NLP applications.
51
+
52
+ ```python
53
+ from langchain_google_genai import GoogleGenerativeAIEmbeddings
54
+
55
+ embeddings = GoogleGenerativeAIEmbeddings(model="models/gemini-embedding-001")
56
+ embeddings.embed_query("hello, world!")
57
+ ```
58
+ """
59
+
60
+ from langchain_google_genai._enums import (
61
+ HarmBlockThreshold,
62
+ HarmCategory,
63
+ MediaResolution,
64
+ Modality,
65
+ )
66
+ from langchain_google_genai.chat_models import ChatGoogleGenerativeAI
67
+ from langchain_google_genai.embeddings import GoogleGenerativeAIEmbeddings
68
+ from langchain_google_genai.genai_aqa import (
69
+ AqaInput,
70
+ AqaOutput,
71
+ GenAIAqa,
72
+ )
73
+ from langchain_google_genai.google_vector_store import (
74
+ DoesNotExistsException,
75
+ GoogleVectorStore,
76
+ )
77
+ from langchain_google_genai.llms import GoogleGenerativeAI
78
+
79
+ __all__ = [
80
+ "AqaInput",
81
+ "AqaOutput",
82
+ "ChatGoogleGenerativeAI",
83
+ "DoesNotExistsException",
84
+ "DoesNotExistsException",
85
+ "GenAIAqa",
86
+ "GoogleGenerativeAI",
87
+ "GoogleGenerativeAIEmbeddings",
88
+ "GoogleVectorStore",
89
+ "HarmBlockThreshold",
90
+ "HarmCategory",
91
+ "MediaResolution",
92
+ "Modality",
93
+ ]
@@ -1,6 +1,6 @@
1
1
  import os
2
2
  from importlib import metadata
3
- from typing import Any, Dict, List, Optional, Tuple, TypedDict
3
+ from typing import Any, TypedDict
4
4
 
5
5
  from google.api_core.gapic_v1.client_info import ClientInfo
6
6
  from langchain_core.utils import secret_from_env
@@ -16,6 +16,12 @@ from langchain_google_genai._enums import (
16
16
  _TELEMETRY_TAG = "remote_reasoning_engine"
17
17
  _TELEMETRY_ENV_VARIABLE_NAME = "GOOGLE_CLOUD_AGENT_ENGINE_ID"
18
18
 
19
+ # Cache package version at module import time to avoid blocking I/O in async contexts
20
+ try:
21
+ LC_GOOGLE_GENAI_VERSION = metadata.version("langchain-google-genai")
22
+ except metadata.PackageNotFoundError:
23
+ LC_GOOGLE_GENAI_VERSION = "0.0.0"
24
+
19
25
 
20
26
  class GoogleGenerativeAIError(Exception):
21
27
  """Custom exception class for errors associated with the `Google GenAI` API."""
@@ -27,116 +33,132 @@ class _BaseGoogleGenerativeAI(BaseModel):
27
33
  model: str = Field(...)
28
34
  """Model name to use."""
29
35
 
30
- google_api_key: Optional[SecretStr] = Field(
36
+ google_api_key: SecretStr | None = Field(
31
37
  alias="api_key", default_factory=secret_from_env("GOOGLE_API_KEY", default=None)
32
38
  )
33
39
  """Google AI API key.
34
-
35
- If not specified will be read from env var å`GOOGLE_API_KEY`.
40
+
41
+ If not specified will be read from env var `GOOGLE_API_KEY`.
36
42
  """
37
43
 
38
44
  credentials: Any = None
39
- """The default custom credentials (`google.auth.credentials.Credentials`) to use
40
- when making API calls.
41
-
45
+ """The default custom credentials to use when making API calls.
46
+
42
47
  If not provided, credentials will be ascertained from the `GOOGLE_API_KEY` env var.
43
48
  """
44
49
 
45
50
  temperature: float = 0.7
46
- """Run inference with this temperature. Must be within `[0.0, 2.0]`.
47
-
48
- If unset, will default to `0.7`.
51
+ """Run inference with this temperature.
52
+
53
+ Must be within `[0.0, 2.0]`.
49
54
  """
50
55
 
51
- top_p: Optional[float] = None
52
- """Decode using nucleus sampling: consider the smallest set of tokens whose
53
- probability sum is at least `top_p`.
54
-
56
+ top_p: float | None = None
57
+ """Decode using nucleus sampling.
58
+
59
+ Consider the smallest set of tokens whose probability sum is at least `top_p`.
60
+
55
61
  Must be within `[0.0, 1.0]`.
56
62
  """
57
63
 
58
- top_k: Optional[int] = None
64
+ top_k: int | None = None
59
65
  """Decode using top-k sampling: consider the set of `top_k` most probable tokens.
60
-
66
+
61
67
  Must be positive.
62
68
  """
63
69
 
64
- max_output_tokens: Optional[int] = Field(default=None, alias="max_tokens")
65
- """Maximum number of tokens to include in a candidate. Must be greater than zero.
66
-
70
+ max_output_tokens: int | None = Field(default=None, alias="max_tokens")
71
+ """Maximum number of tokens to include in a candidate.
72
+
73
+ Must be greater than zero.
74
+
67
75
  If unset, will use the model's default value, which varies by model.
68
-
69
- See https://ai.google.dev/gemini-api/docs/models for model-specific limits.
76
+
77
+ See [docs](https://ai.google.dev/gemini-api/docs/models) for model-specific limits.
70
78
  """
71
79
 
72
80
  n: int = 1
73
81
  """Number of chat completions to generate for each prompt.
74
-
82
+
75
83
  Note that the API may not return the full `n` completions if duplicates are
76
84
  generated.
77
85
  """
78
86
 
79
87
  max_retries: int = Field(default=6, alias="retries")
80
- """The maximum number of retries to make when generating.
81
-
82
- If unset, will default to `6`.
83
- """
88
+ """The maximum number of retries to make when generating."""
84
89
 
85
- timeout: Optional[float] = Field(default=None, alias="request_timeout")
90
+ timeout: float | None = Field(default=None, alias="request_timeout")
86
91
  """The maximum number of seconds to wait for a response."""
87
92
 
88
- client_options: Optional[Dict] = Field(
93
+ client_options: dict | None = Field(
89
94
  default=None,
90
95
  )
91
- """"A dictionary of client options to pass to the Google API client, such as
92
- `api_endpoint`.
96
+ """A dictionary of client options to pass to the Google API client.
97
+
98
+ Example: `api_endpoint`
99
+
100
+ !!! warning
101
+
102
+ If both `client_options['api_endpoint']` and `base_url` are specified,
103
+ the `api_endpoint` in `client_options` takes precedence.
93
104
  """
94
105
 
95
- base_url: Optional[str] = Field(
106
+ base_url: str | None = Field(
96
107
  default=None,
97
108
  )
98
- """The base URL to use for the API client.
99
-
100
- Alias of `client_options['api_endpoint']`.
109
+ """Base URL to use for the API client.
110
+
111
+ This is a convenience alias for `client_options['api_endpoint']`.
112
+
113
+ !!! warning
114
+
115
+ If `client_options` already contains an `api_endpoint`, this parameter will be
116
+ ignored in favor of the existing value.
101
117
  """
102
118
 
103
- transport: Optional[str] = Field(
119
+ transport: str | None = Field(
104
120
  default=None,
105
121
  alias="api_transport",
106
122
  )
107
- """A string, one of: `[rest, grpc, grpc_asyncio]`."""
123
+ """A string, one of: `['rest', 'grpc', 'grpc_asyncio']`.
108
124
 
109
- additional_headers: Optional[Dict[str, str]] = Field(
125
+ The Google client library defaults to `'grpc'` for sync clients.
126
+
127
+ For async clients, `'rest'` is converted to `'grpc_asyncio'` unless
128
+ a custom endpoint is specified.
129
+ """
130
+
131
+ additional_headers: dict[str, str] | None = Field(
110
132
  default=None,
111
133
  )
112
- """"Key-value dictionary representing additional headers for the model call"""
134
+ """Key-value dictionary representing additional headers for the model call"""
113
135
 
114
- response_modalities: Optional[List[Modality]] = Field(
136
+ response_modalities: list[Modality] | None = Field(
115
137
  default=None,
116
138
  )
117
139
  """A list of modalities of the response"""
118
140
 
119
- thinking_budget: Optional[int] = Field(
141
+ thinking_budget: int | None = Field(
120
142
  default=None,
121
143
  )
122
144
  """Indicates the thinking budget in tokens."""
123
145
 
124
- media_resolution: Optional[MediaResolution] = Field(
146
+ media_resolution: MediaResolution | None = Field(
125
147
  default=None,
126
148
  )
127
149
  """Media resolution for the input media."""
128
150
 
129
- include_thoughts: Optional[bool] = Field(
151
+ include_thoughts: bool | None = Field(
130
152
  default=None,
131
153
  )
132
154
  """Indicates whether to include thoughts in the response."""
133
155
 
134
- safety_settings: Optional[Dict[HarmCategory, HarmBlockThreshold]] = None
135
- """The default safety settings to use for all generations.
156
+ safety_settings: dict[HarmCategory, HarmBlockThreshold] | None = None
157
+ """Default safety settings to use for all generations.
136
158
 
137
- For example:
159
+ !!! example
138
160
 
139
- .. code-block:: python
161
+ ```python
140
162
  from google.generativeai.types.safety_types import HarmBlockThreshold, HarmCategory
141
163
 
142
164
  safety_settings = {
@@ -145,14 +167,15 @@ class _BaseGoogleGenerativeAI(BaseModel):
145
167
  HarmCategory.HARM_CATEGORY_HARASSMENT: HarmBlockThreshold.BLOCK_LOW_AND_ABOVE,
146
168
  HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: HarmBlockThreshold.BLOCK_NONE,
147
169
  }
170
+ ```
148
171
  """ # noqa: E501
149
172
 
150
173
  @property
151
- def lc_secrets(self) -> Dict[str, str]:
174
+ def lc_secrets(self) -> dict[str, str]:
152
175
  return {"google_api_key": "GOOGLE_API_KEY"}
153
176
 
154
177
  @property
155
- def _identifying_params(self) -> Dict[str, Any]:
178
+ def _identifying_params(self) -> dict[str, Any]:
156
179
  """Get the identifying parameters."""
157
180
  return {
158
181
  "model": self.model,
@@ -164,37 +187,25 @@ class _BaseGoogleGenerativeAI(BaseModel):
164
187
  }
165
188
 
166
189
 
167
- def get_user_agent(module: Optional[str] = None) -> Tuple[str, str]:
190
+ def get_user_agent(module: str | None = None) -> tuple[str, str]:
168
191
  r"""Returns a custom user agent header.
169
192
 
170
193
  Args:
171
- module (Optional[str]):
172
- Optional. The module for a custom user agent header.
173
-
174
- Returns:
175
- Tuple[str, str]
194
+ module: The module for a custom user agent header.
176
195
  """
177
- try:
178
- langchain_version = metadata.version("langchain-google-genai")
179
- except metadata.PackageNotFoundError:
180
- langchain_version = "0.0.0"
181
196
  client_library_version = (
182
- f"{langchain_version}-{module}" if module else langchain_version
197
+ f"{LC_GOOGLE_GENAI_VERSION}-{module}" if module else LC_GOOGLE_GENAI_VERSION
183
198
  )
184
199
  if os.environ.get(_TELEMETRY_ENV_VARIABLE_NAME):
185
200
  client_library_version += f"+{_TELEMETRY_TAG}"
186
201
  return client_library_version, f"langchain-google-genai/{client_library_version}"
187
202
 
188
203
 
189
- def get_client_info(module: Optional[str] = None) -> "ClientInfo":
204
+ def get_client_info(module: str | None = None) -> "ClientInfo":
190
205
  r"""Returns a client info object with a custom user agent header.
191
206
 
192
207
  Args:
193
- module (Optional[str]):
194
- Optional. The module for a custom user agent header.
195
-
196
- Returns:
197
- ``google.api_core.gapic_v1.client_info.ClientInfo``
208
+ module: The module for a custom user agent header.
198
209
  """
199
210
  client_library_version, user_agent = get_user_agent(module)
200
211
  # TODO: remove ignore once google-auth has types.
@@ -206,4 +217,5 @@ def get_client_info(module: Optional[str] = None) -> "ClientInfo":
206
217
 
207
218
  class SafetySettingDict(TypedDict):
208
219
  category: HarmCategory
220
+
209
221
  threshold: HarmBlockThreshold
@@ -1,18 +1,18 @@
1
1
  """Go from v1 content blocks to generativelanguage_v1beta format."""
2
2
 
3
3
  import json
4
- from typing import Any, Optional, cast
4
+ from typing import Any, cast
5
5
 
6
6
  from langchain_core.messages import content as types
7
7
 
8
8
 
9
9
  def translate_citations_to_grounding_metadata(
10
- citations: list[types.Citation], web_search_queries: Optional[list[str]] = None
10
+ citations: list[types.Citation], web_search_queries: list[str] | None = None
11
11
  ) -> dict[str, Any]:
12
12
  """Translate LangChain Citations to Google AI grounding metadata format.
13
13
 
14
14
  Args:
15
- citations: List of Citation content blocks.
15
+ citations: List of `Citation` content blocks.
16
16
  web_search_queries: Optional list of search queries that generated
17
17
  the grounding data.
18
18
 
@@ -40,7 +40,7 @@ def translate_citations_to_grounding_metadata(
40
40
 
41
41
  # Group citations by text segment (start_index, end_index, cited_text)
42
42
  segment_to_citations: dict[
43
- tuple[Optional[int], Optional[int], Optional[str]], list[types.Citation]
43
+ tuple[int | None, int | None, str | None], list[types.Citation]
44
44
  ] = {}
45
45
 
46
46
  for citation in citations:
@@ -131,7 +131,7 @@ def _convert_from_v1_to_generativelanguage_v1beta(
131
131
 
132
132
  Returns:
133
133
  List of dictionaries in `google.ai.generativelanguage_v1beta.types.Content`
134
- format, ready to be sent to the API.
134
+ format, ready to be sent to the API.
135
135
  """
136
136
  new_content: list = []
137
137
  for block in content:
@@ -247,7 +247,7 @@ def _convert_from_v1_to_generativelanguage_v1beta(
247
247
  elif block_dict["type"] == "server_tool_call":
248
248
  if block_dict.get("name") == "code_interpreter":
249
249
  # LangChain v0 format
250
- args = cast(dict, block_dict.get("args", {}))
250
+ args = cast("dict", block_dict.get("args", {}))
251
251
  executable_code = {
252
252
  "type": "executable_code",
253
253
  "executable_code": args.get("code", ""),
@@ -265,7 +265,7 @@ def _convert_from_v1_to_generativelanguage_v1beta(
265
265
  )
266
266
 
267
267
  elif block_dict["type"] == "server_tool_result":
268
- extras = cast(dict, block_dict.get("extras", {}))
268
+ extras = cast("dict", block_dict.get("extras", {}))
269
269
  if extras.get("block_type") == "code_execution_result":
270
270
  # LangChain v0 format
271
271
  code_execution_result = {
@@ -5,4 +5,4 @@ HarmCategory = genai.HarmCategory
5
5
  Modality = genai.GenerationConfig.Modality
6
6
  MediaResolution = genai.GenerationConfig.MediaResolution
7
7
 
8
- __all__ = ["HarmBlockThreshold", "HarmCategory", "Modality", "MediaResolution"]
8
+ __all__ = ["HarmBlockThreshold", "HarmCategory", "MediaResolution", "Modality"]